context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.IdentifiersShouldNotContainUnderscoresAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpIdentifiersShouldNotContainUnderscoresFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.IdentifiersShouldNotContainUnderscoresAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicIdentifiersShouldNotContainUnderscoresFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class IdentifiersShouldNotContainUnderscoresTests
{
#region CSharp Tests
[Fact]
public async Task CA1707_ForAssembly_CSharpAsync() // TODO: How to test the code fixer for this?
{
await new VerifyCS.Test
{
TestCode = @"
public class DoesNotMatter
{
}
",
SolutionTransforms =
{
(solution, projectId) =>
solution.WithProjectAssemblyName(projectId, "AssemblyNameHasUnderScore_")
},
ExpectedDiagnostics =
{
GetCA1707CSharpResultAt(line: 2, column: 1, symbolKind: SymbolKind.Assembly, identifierNames: "AssemblyNameHasUnderScore_")
}
}.RunAsync();
}
[Fact]
public async Task CA1707_ForAssembly_NoDiagnostics_CSharpAsync()
{
await new VerifyCS.Test
{
TestCode = @"
public class DoesNotMatter
{
}
",
SolutionTransforms =
{
(solution, projectId) =>
solution.WithProjectAssemblyName(projectId, "AssemblyNameHasNoUnderScore")
}
}.RunAsync();
}
[Fact]
public async Task CA1707_ForNamespace_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
namespace OuterNamespace
{
namespace {|#0:HasUnderScore_|}
{
public class DoesNotMatter
{
}
}
}
namespace HasNoUnderScore
{
public class DoesNotMatter
{
}
}",
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.NamespaceRule).WithLocation(0).WithArguments("OuterNamespace.HasUnderScore_"), @"
namespace OuterNamespace
{
namespace HasUnderScore
{
public class DoesNotMatter
{
}
}
}
namespace HasNoUnderScore
{
public class DoesNotMatter
{
}
}");
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task CA1707_ForTypes_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class OuterType
{
public class {|#0:UnderScoreInName_|}
{
}
private class UnderScoreInNameButPrivate_
{
}
internal class UnderScoreInNameButInternal_
{
}
}
internal class OuterType2
{
public class UnderScoreInNameButNotExternallyVisible_
{
}
}
",
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.TypeRule).WithLocation(0).WithArguments("OuterType.UnderScoreInName_"), @"
public class OuterType
{
public class UnderScoreInName
{
}
private class UnderScoreInNameButPrivate_
{
}
internal class UnderScoreInNameButInternal_
{
}
}
internal class OuterType2
{
public class UnderScoreInNameButNotExternallyVisible_
{
}
}
");
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task CA1707_ForFields_CSharpAsync()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{ @"
public class DoesNotMatter
{
public const int {|#0:ConstField_|} = 5;
public static readonly int {|#1:StaticReadOnlyField_|} = 5;
// No diagnostics for the below
private string InstanceField_;
private static string StaticField_;
public string _field;
protected string Another_field;
}
public enum DoesNotMatterEnum
{
{|#2:_EnumWithUnderscore|},
{|#3:_|}
}
public class C
{
internal class C2
{
public const int ConstField_ = 5;
}
}
",
},
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatter.ConstField_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("DoesNotMatter.StaticReadOnlyField_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("DoesNotMatterEnum._EnumWithUnderscore"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("DoesNotMatterEnum._"),
}
},
FixedState =
{
Sources =
{
@"
public class DoesNotMatter
{
public const int ConstField = 5;
public static readonly int StaticReadOnlyField = 5;
// No diagnostics for the below
private string InstanceField_;
private static string StaticField_;
public string _field;
protected string Another_field;
}
public enum DoesNotMatterEnum
{
EnumWithUnderscore,
{|#0:_|}
}
public class C
{
internal class C2
{
public const int ConstField_ = 5;
}
}
",
},
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatterEnum._"),
},
},
}.RunAsync();
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task CA1707_ForMethods_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class DoesNotMatter
{
public void {|#0:PublicM1_|}() { }
private void PrivateM2_() { } // No diagnostic
internal void InternalM3_() { } // No diagnostic
protected void {|#1:ProtectedM4_|}() { }
}
public interface I1
{
void {|#2:M_|}();
}
public class ImplementI1 : I1
{
public void M_() { } // No diagnostic
public virtual void {|#3:M2_|}() { }
}
public class Derives : ImplementI1
{
public override void M2_() { } // No diagnostic
}
internal class C
{
public class DoesNotMatter2
{
public void PublicM1_() { } // No diagnostic
protected void ProtectedM4_() { } // No diagnostic
}
}", new[]
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatter.PublicM1_()"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("DoesNotMatter.ProtectedM4_()"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("I1.M_()"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("ImplementI1.M2_()")
}, @"
public class DoesNotMatter
{
public void PublicM1() { }
private void PrivateM2_() { } // No diagnostic
internal void InternalM3_() { } // No diagnostic
protected void ProtectedM4() { }
}
public interface I1
{
void M();
}
public class ImplementI1 : I1
{
public void M() { } // No diagnostic
public virtual void M2() { }
}
public class Derives : ImplementI1
{
public override void M2() { } // No diagnostic
}
internal class C
{
public class DoesNotMatter2
{
public void PublicM1_() { } // No diagnostic
protected void ProtectedM4_() { } // No diagnostic
}
}");
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task CA1707_ForProperties_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class DoesNotMatter
{
public int {|#0:PublicP1_|} { get; set; }
private int PrivateP2_ { get; set; } // No diagnostic
internal int InternalP3_ { get; set; } // No diagnostic
protected int {|#1:ProtectedP4_|} { get; set; }
}
public interface I1
{
int {|#2:P_|} { get; set; }
}
public class ImplementI1 : I1
{
public int P_ { get; set; } // No diagnostic
public virtual int {|#3:P2_|} { get; set; }
}
public class Derives : ImplementI1
{
public override int P2_ { get; set; } // No diagnostic
}
internal class C
{
public class DoesNotMatter2
{
public int PublicP1_ { get; set; }// No diagnostic
protected int ProtectedP4_ { get; set; } // No diagnostic
}
}", new[]
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatter.PublicP1_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("DoesNotMatter.ProtectedP4_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("I1.P_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("ImplementI1.P2_")
}, @"
public class DoesNotMatter
{
public int PublicP1 { get; set; }
private int PrivateP2_ { get; set; } // No diagnostic
internal int InternalP3_ { get; set; } // No diagnostic
protected int ProtectedP4 { get; set; }
}
public interface I1
{
int P { get; set; }
}
public class ImplementI1 : I1
{
public int P { get; set; } // No diagnostic
public virtual int P2 { get; set; }
}
public class Derives : ImplementI1
{
public override int P2 { get; set; } // No diagnostic
}
internal class C
{
public class DoesNotMatter2
{
public int PublicP1_ { get; set; }// No diagnostic
protected int ProtectedP4_ { get; set; } // No diagnostic
}
}");
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task CA1707_ForEvents_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
using System;
public class DoesNotMatter
{
public event EventHandler {|#0:PublicE1_|};
private event EventHandler PrivateE2_; // No diagnostic
internal event EventHandler InternalE3_; // No diagnostic
protected event EventHandler {|#1:ProtectedE4_|};
}
public interface I1
{
event EventHandler {|#2:E_|};
}
public class ImplementI1 : I1
{
public event EventHandler E_;// No diagnostic
public virtual event EventHandler {|#3:E2_|};
}
public class Derives : ImplementI1
{
public override event EventHandler E2_; // No diagnostic
}
internal class C
{
public class DoesNotMatter
{
public event EventHandler PublicE1_; // No diagnostic
protected event EventHandler ProtectedE4_; // No diagnostic
}
}", new[]
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatter.PublicE1_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("DoesNotMatter.ProtectedE4_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("I1.E_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("ImplementI1.E2_")
}, @"
using System;
public class DoesNotMatter
{
public event EventHandler PublicE1;
private event EventHandler PrivateE2_; // No diagnostic
internal event EventHandler InternalE3_; // No diagnostic
protected event EventHandler ProtectedE4;
}
public interface I1
{
event EventHandler E;
}
public class ImplementI1 : I1
{
public event EventHandler E;// No diagnostic
public virtual event EventHandler E2;
}
public class Derives : ImplementI1
{
public override event EventHandler E2; // No diagnostic
}
internal class C
{
public class DoesNotMatter
{
public event EventHandler PublicE1_; // No diagnostic
protected event EventHandler ProtectedE4_; // No diagnostic
}
}");
}
[Fact]
public async Task CA1707_ForDelegates_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public delegate void Dele(int {|#0:intPublic_|}, string {|#1:stringPublic_|});
internal delegate void Dele2(int intInternal_, string stringInternal_); // No diagnostics
public delegate T Del<T>(int {|#2:t_|});
", new[]
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.DelegateParameterRule).WithLocation(0).WithArguments("Dele", "intPublic_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.DelegateParameterRule).WithLocation(1).WithArguments("Dele", "stringPublic_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.DelegateParameterRule).WithLocation(2).WithArguments("Del<T>", "t_")
}, @"
public delegate void Dele(int intPublic, string stringPublic);
internal delegate void Dele2(int intInternal_, string stringInternal_); // No diagnostics
public delegate T Del<T>(int t);
");
}
[Fact]
public async Task CA1707_ForMemberparameters_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class DoesNotMatter
{
public void PublicM1(int {|#0:int_|}) { }
private void PrivateM2(int int_) { } // No diagnostic
internal void InternalM3(int int_) { } // No diagnostic
protected void ProtectedM4(int {|#1:int_|}) { }
}
public interface I
{
void M(int {|#2:int_|});
}
public class implementI : I
{
public void M(int int_) // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
}
}
public abstract class Base
{
public virtual void M1(int {|#3:int_|})
{
}
public abstract void M2(int {|#4:int_|});
}
public class Der : Base
{
public override void M2(int int_) // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
throw new System.NotImplementedException();
}
public override void M1(int int_) // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
base.M1(int_);
}
}", new[]
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(0).WithArguments("DoesNotMatter.PublicM1(int)", "int_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(1).WithArguments("DoesNotMatter.ProtectedM4(int)", "int_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(2).WithArguments("I.M(int)", "int_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(3).WithArguments("Base.M1(int)", "int_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(4).WithArguments("Base.M2(int)", "int_")
}, @"
public class DoesNotMatter
{
public void PublicM1(int @int) { }
private void PrivateM2(int int_) { } // No diagnostic
internal void InternalM3(int int_) { } // No diagnostic
protected void ProtectedM4(int @int) { }
}
public interface I
{
void M(int @int);
}
public class implementI : I
{
public void M(int int_) // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
}
}
public abstract class Base
{
public virtual void M1(int @int)
{
}
public abstract void M2(int @int);
}
public class Der : Base
{
public override void M2(int int_) // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
throw new System.NotImplementedException();
}
public override void M1(int int_) // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
base.M1(int_);
}
}");
}
[Fact]
public async Task CA1707_ForTypeTypeParameters_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class DoesNotMatter<{|#0:T_|}>
{
}
class NoDiag<U_>
{
}", VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.TypeTypeParameterRule).WithLocation(0).WithArguments("DoesNotMatter<T_>", "T_"), @"
public class DoesNotMatter<T>
{
}
class NoDiag<U_>
{
}");
}
[Fact]
public async Task CA1707_ForMemberTypeParameters_CSharpAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
public class DoesNotMatter22
{
public void PublicM1<{|#0:T1_|}>() { }
private void PrivateM2<U_>() { } // No diagnostic
internal void InternalM3<W_>() { } // No diagnostic
protected void ProtectedM4<{|#1:D_|}>() { }
}
public interface I
{
void M<{|#2:T_|}>();
}
public class implementI : I
{
public void M<U_>()
{
throw new System.NotImplementedException();
}
}
public abstract class Base
{
public virtual void M1<{|#3:T_|}>()
{
}
public abstract void M2<{|#4:U_|}>();
}
public class Der : Base
{
public override void M2<U_>() // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
throw new System.NotImplementedException();
}
public override void M1<T_>() // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
base.M1<T_>();
}
}", new[]
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(0).WithArguments("DoesNotMatter22.PublicM1<T1_>()", "T1_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(1).WithArguments("DoesNotMatter22.ProtectedM4<D_>()", "D_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(2).WithArguments("I.M<T_>()", "T_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(3).WithArguments("Base.M1<T_>()", "T_"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(4).WithArguments("Base.M2<U_>()", "U_")
}, @"
public class DoesNotMatter22
{
public void PublicM1<T1>() { }
private void PrivateM2<U_>() { } // No diagnostic
internal void InternalM3<W_>() { } // No diagnostic
protected void ProtectedM4<D>() { }
}
public interface I
{
void M<T>();
}
public class implementI : I
{
public void M<U_>()
{
throw new System.NotImplementedException();
}
}
public abstract class Base
{
public virtual void M1<T>()
{
}
public abstract void M2<U>();
}
public class Der : Base
{
public override void M2<U_>() // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
throw new System.NotImplementedException();
}
public override void M1<T_>() // This is not renamed due to https://github.com/dotnet/roslyn/issues/46663
{
base.M1<T_>();
}
}");
}
[Fact, WorkItem(947, "https://github.com/dotnet/roslyn-analyzers/issues/947")]
public async Task CA1707_ForOperators_CSharpAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public struct S
{
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}
");
}
[Fact, WorkItem(1319, "https://github.com/dotnet/roslyn-analyzers/issues/1319")]
public async Task CA1707_CustomOperator_CSharpAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Span
{
public static implicit operator Span(string text) => new Span(text);
public static explicit operator string(Span span) => span.GetText();
private string _text;
public Span(string text)
{
this._text = text;
}
public string GetText() => _text;
}
");
}
[Fact]
public async Task CA1707_CSharp_DiscardSymbolParameter_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public static class MyHelper
{
public static int GetSomething(this string _) => 42;
public static void SomeMethod()
{
SomeOtherMethod(out _);
}
public static void SomeOtherMethod(out int p)
{
p = 42;
}
}");
}
[Fact]
public async Task CA1707_CSharp_DiscardSymbolTuple_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class SomeClass
{
public SomeClass()
{
var (_, d) = GetSomething();
}
private static (string, double) GetSomething() => ("""", 0);
}");
}
[Fact]
public async Task CA1707_CSharp_DiscardSymbolPatternMatching_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class SomeClass
{
public SomeClass(object o)
{
switch (o)
{
case object _:
break;
}
}
}");
}
[Fact]
public async Task CA1707_CSharp_StandaloneDiscardSymbol_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class SomeClass
{
public SomeClass(object o)
{
_ = GetSomething();
}
public int GetSomething() => 42;
}");
}
[Fact, WorkItem(3121, "https://github.com/dotnet/roslyn-analyzers/issues/3121")]
public async Task CA1707_CSharp_GlobalAsaxSpecialMethodsAsync()
{
await VerifyCS.VerifyCodeFixAsync(@"
using System;
namespace System.Web
{
public class HttpApplication {}
}
public class ValidContext : System.Web.HttpApplication
{
protected void Application_AuthenticateRequest(object sender, EventArgs e) {}
protected void Application_BeginRequest(object sender, EventArgs e) {}
protected void Application_End(object sender, EventArgs e) {}
protected void Application_EndRequest(object sender, EventArgs e) {}
protected void Application_Error(object sender, EventArgs e) {}
protected void Application_Init(object sender, EventArgs e) {}
protected void Application_Start(object sender, EventArgs e) {}
protected void Session_End(object sender, EventArgs e) {}
protected void Session_Start(object sender, EventArgs e) {}
}
public class InvalidContext
{
protected void {|#0:Application_AuthenticateRequest|}(object sender, EventArgs e) {}
protected void {|#1:Application_BeginRequest|}(object sender, EventArgs e) {}
protected void {|#2:Application_End|}(object sender, EventArgs e) {}
protected void {|#3:Application_EndRequest|}(object sender, EventArgs e) {}
protected void {|#4:Application_Error|}(object sender, EventArgs e) {}
protected void {|#5:Application_Init|}(object sender, EventArgs e) {}
protected void {|#6:Application_Start|}(object sender, EventArgs e) {}
protected void {|#7:Session_End|}(object sender, EventArgs e) {}
protected void {|#8:Session_Start|}(object sender, EventArgs e) {}
}", new[]
{
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("InvalidContext.Application_AuthenticateRequest(object, System.EventArgs)"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("InvalidContext.Application_BeginRequest(object, System.EventArgs)"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("InvalidContext.Application_End(object, System.EventArgs)"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("InvalidContext.Application_EndRequest(object, System.EventArgs)"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(4).WithArguments("InvalidContext.Application_Error(object, System.EventArgs)"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(5).WithArguments("InvalidContext.Application_Init(object, System.EventArgs)"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(6).WithArguments("InvalidContext.Application_Start(object, System.EventArgs)"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(7).WithArguments("InvalidContext.Session_End(object, System.EventArgs)"),
VerifyCS.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(8).WithArguments("InvalidContext.Session_Start(object, System.EventArgs)")
}, @"
using System;
namespace System.Web
{
public class HttpApplication {}
}
public class ValidContext : System.Web.HttpApplication
{
protected void Application_AuthenticateRequest(object sender, EventArgs e) {}
protected void Application_BeginRequest(object sender, EventArgs e) {}
protected void Application_End(object sender, EventArgs e) {}
protected void Application_EndRequest(object sender, EventArgs e) {}
protected void Application_Error(object sender, EventArgs e) {}
protected void Application_Init(object sender, EventArgs e) {}
protected void Application_Start(object sender, EventArgs e) {}
protected void Session_End(object sender, EventArgs e) {}
protected void Session_Start(object sender, EventArgs e) {}
}
public class InvalidContext
{
protected void ApplicationAuthenticateRequest(object sender, EventArgs e) {}
protected void ApplicationBeginRequest(object sender, EventArgs e) {}
protected void ApplicationEnd(object sender, EventArgs e) {}
protected void ApplicationEndRequest(object sender, EventArgs e) {}
protected void ApplicationError(object sender, EventArgs e) {}
protected void ApplicationInit(object sender, EventArgs e) {}
protected void ApplicationStart(object sender, EventArgs e) {}
protected void SessionEnd(object sender, EventArgs e) {}
protected void SessionStart(object sender, EventArgs e) {}
}");
}
#endregion
#region Visual Basic Tests
[Fact]
public async Task CA1707_ForAssembly_VisualBasicAsync()
{
await new VerifyVB.Test
{
TestCode = @"
Public Class DoesNotMatter
End Class
",
SolutionTransforms =
{
(solution, projectId) =>
solution.WithProjectAssemblyName(projectId, "AssemblyNameHasUnderScore_")
},
ExpectedDiagnostics =
{
GetCA1707BasicResultAt(line: 2, column: 1, symbolKind: SymbolKind.Assembly, identifierNames: "AssemblyNameHasUnderScore_")
}
}.RunAsync();
}
[Fact]
public async Task CA1707_ForAssembly_NoDiagnostics_VisualBasicAsync()
{
await new VerifyVB.Test
{
TestCode = @"
Public Class DoesNotMatter
End Class
",
SolutionTransforms =
{
(solution, projectId) =>
solution.WithProjectAssemblyName(projectId, "AssemblyNameHasNoUnderScore")
}
}.RunAsync();
}
[Fact]
public async Task CA1707_ForNamespace_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Namespace OuterNamespace
Namespace {|#0:HasUnderScore_|}
Public Class DoesNotMatter
End Class
End Namespace
End Namespace
Namespace HasNoUnderScore
Public Class DoesNotMatter
End Class
End Namespace",
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.NamespaceRule).WithLocation(0).WithArguments("OuterNamespace.HasUnderScore_"), @"
Namespace OuterNamespace
Namespace HasUnderScore
Public Class DoesNotMatter
End Class
End Namespace
End Namespace
Namespace HasNoUnderScore
Public Class DoesNotMatter
End Class
End Namespace");
}
[Fact]
public async Task CA1707_ForTypes_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class OuterType
Public Class {|#0:UnderScoreInName_|}
End Class
Private Class UnderScoreInNameButPrivate_
End Class
End Class",
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.TypeRule).WithLocation(0).WithArguments("OuterType.UnderScoreInName_"), @"
Public Class OuterType
Public Class UnderScoreInName
End Class
Private Class UnderScoreInNameButPrivate_
End Class
End Class");
}
[Fact]
public async Task CA1707_ForFields_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class DoesNotMatter
Public Const {|#0:ConstField_|} As Integer = 5
Public Shared ReadOnly {|#1:SharedReadOnlyField_|} As Integer = 5
' No diagnostics for the below
Private InstanceField_ As String
Private Shared StaticField_ As String
Public _field As String
Protected Another_field As String
End Class
Public Enum DoesNotMatterEnum
{|#2:_EnumWithUnderscore|}
End Enum", new[]
{
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatter.ConstField_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("DoesNotMatter.SharedReadOnlyField_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("DoesNotMatterEnum._EnumWithUnderscore")
}, @"
Public Class DoesNotMatter
Public Const ConstField As Integer = 5
Public Shared ReadOnly SharedReadOnlyField As Integer = 5
' No diagnostics for the below
Private InstanceField_ As String
Private Shared StaticField_ As String
Public _field As String
Protected Another_field As String
End Class
Public Enum DoesNotMatterEnum
EnumWithUnderscore
End Enum");
}
[Fact]
public async Task CA1707_ForMethods_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class DoesNotMatter
Public Sub {|#0:PublicM1_|}()
End Sub
' No diagnostic
Private Sub PrivateM2_()
End Sub
' No diagnostic
Friend Sub InternalM3_()
End Sub
Protected Sub {|#1:ProtectedM4_|}()
End Sub
End Class
Public Interface I1
Sub {|#2:M_|}()
End Interface
Public Class ImplementI1
Implements I1
Public Sub M_() Implements I1.M_
End Sub
' No diagnostic
Public Overridable Sub {|#3:M2_|}()
End Sub
End Class
Public Class Derives
Inherits ImplementI1
' No diagnostic
Public Overrides Sub M2_()
End Sub
End Class", new[]
{
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatter.PublicM1_()"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("DoesNotMatter.ProtectedM4_()"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("I1.M_()"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("ImplementI1.M2_()")
}, @"
Public Class DoesNotMatter
Public Sub PublicM1()
End Sub
' No diagnostic
Private Sub PrivateM2_()
End Sub
' No diagnostic
Friend Sub InternalM3_()
End Sub
Protected Sub ProtectedM4()
End Sub
End Class
Public Interface I1
Sub M()
End Interface
Public Class ImplementI1
Implements I1
Public Sub M() Implements I1.M
End Sub
' No diagnostic
Public Overridable Sub M2()
End Sub
End Class
Public Class Derives
Inherits ImplementI1
' No diagnostic
Public Overrides Sub M2()
End Sub
End Class");
}
[Fact]
public async Task CA1707_ForProperties_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class DoesNotMatter
Public Property {|#0:PublicP1_|}() As Integer
Get
Return 0
End Get
Set
End Set
End Property
' No diagnostic
Private Property PrivateP2_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
' No diagnostic
Friend Property InternalP3_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
Protected Property {|#1:ProtectedP4_|}() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Interface I1
Property {|#2:P_|}() As Integer
End Interface
Public Class ImplementI1
Implements I1
' No diagnostic
Public Property P_() As Integer Implements I1.P_
Get
Return 0
End Get
Set
End Set
End Property
Public Overridable Property {|#3:P2_|}() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class Derives
Inherits ImplementI1
' No diagnostic
Public Overrides Property P2_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class", new[]
{
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatter.PublicP1_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("DoesNotMatter.ProtectedP4_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("I1.P_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("ImplementI1.P2_")
}, @"
Public Class DoesNotMatter
Public Property PublicP1() As Integer
Get
Return 0
End Get
Set
End Set
End Property
' No diagnostic
Private Property PrivateP2_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
' No diagnostic
Friend Property InternalP3_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
Protected Property ProtectedP4() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Interface I1
Property P() As Integer
End Interface
Public Class ImplementI1
Implements I1
' No diagnostic
Public Property P() As Integer Implements I1.P
Get
Return 0
End Get
Set
End Set
End Property
Public Overridable Property P2() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class Derives
Inherits ImplementI1
' No diagnostic
Public Overrides Property P2() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class");
}
[Fact]
public async Task CA1707_ForEvents_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class DoesNotMatter
Public Event {|#0:PublicE1_|} As System.EventHandler
Private Event PrivateE2_ As System.EventHandler
' No diagnostic
Friend Event InternalE3_ As System.EventHandler
' No diagnostic
Protected Event {|#1:ProtectedE4_|} As System.EventHandler
End Class
Public Interface I1
Event {|#2:E_|} As System.EventHandler
End Interface
Public Class ImplementI1
Implements I1
' No diagnostic
Public Event E_ As System.EventHandler Implements I1.E_
Public Event {|#3:E2_|} As System.EventHandler
End Class
Public Class Derives
Inherits ImplementI1
'Public Shadows Event E2_ As System.EventHandler ' Currently not renamed due to https://github.com/dotnet/roslyn/issues/46663
End Class", new[]
{
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("DoesNotMatter.PublicE1_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("DoesNotMatter.ProtectedE4_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("I1.E_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("ImplementI1.E2_"),
}, @"
Public Class DoesNotMatter
Public Event PublicE1 As System.EventHandler
Private Event PrivateE2_ As System.EventHandler
' No diagnostic
Friend Event InternalE3_ As System.EventHandler
' No diagnostic
Protected Event ProtectedE4 As System.EventHandler
End Class
Public Interface I1
Event E As System.EventHandler
End Interface
Public Class ImplementI1
Implements I1
' No diagnostic
Public Event E As System.EventHandler Implements I1.E
Public Event E2 As System.EventHandler
End Class
Public Class Derives
Inherits ImplementI1
'Public Shadows Event E2_ As System.EventHandler ' Currently not renamed due to https://github.com/dotnet/roslyn/issues/46663
End Class");
}
[Fact]
public async Task CA1707_ForDelegates_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Delegate Sub Dele({|#0:intPublic_|} As Integer, {|#1:stringPublic_|} As String)
' No diagnostics
Friend Delegate Sub Dele2(intInternal_ As Integer, stringInternal_ As String)
Public Delegate Function Del(Of T)({|#2:t_|} As Integer) As T
", new[]
{
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.DelegateParameterRule).WithLocation(0).WithArguments("Dele", "intPublic_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.DelegateParameterRule).WithLocation(1).WithArguments("Dele", "stringPublic_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.DelegateParameterRule).WithLocation(2).WithArguments("Del(Of T)", "t_")
}, @"
Public Delegate Sub Dele(intPublic As Integer, stringPublic As String)
' No diagnostics
Friend Delegate Sub Dele2(intInternal_ As Integer, stringInternal_ As String)
Public Delegate Function Del(Of T)(t As Integer) As T
");
}
[Fact]
public async Task CA1707_ForMemberparameters_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class DoesNotMatter
Public Sub PublicM1({|#0:int_|} As Integer)
End Sub
Private Sub PrivateM2(int_ As Integer)
End Sub
' No diagnostic
Friend Sub InternalM3(int_ As Integer)
End Sub
' No diagnostic
Protected Sub ProtectedM4({|#1:int_|} As Integer)
End Sub
End Class
Public Interface I
Sub M({|#2:int_|} As Integer)
End Interface
Public Class implementI
Implements I
Private Sub I_M(int_ As Integer) Implements I.M
End Sub
End Class
Public MustInherit Class Base
Public Overridable Sub M1({|#3:int_|} As Integer)
End Sub
Public MustOverride Sub M2({|#4:int_|} As Integer)
End Class
Public Class Der
Inherits Base
Public Overrides Sub M2(int_ As Integer)
Throw New System.NotImplementedException()
End Sub
Public Overrides Sub M1(int_ As Integer)
MyBase.M1(int_)
End Sub
End Class", new[]
{
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(0).WithArguments("DoesNotMatter.PublicM1(Integer)", "int_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(1).WithArguments("DoesNotMatter.ProtectedM4(Integer)", "int_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(2).WithArguments("I.M(Integer)", "int_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(3).WithArguments("Base.M1(Integer)", "int_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule).WithLocation(4).WithArguments("Base.M2(Integer)", "int_")
}, @"
Public Class DoesNotMatter
Public Sub PublicM1(int As Integer)
End Sub
Private Sub PrivateM2(int_ As Integer)
End Sub
' No diagnostic
Friend Sub InternalM3(int_ As Integer)
End Sub
' No diagnostic
Protected Sub ProtectedM4(int As Integer)
End Sub
End Class
Public Interface I
Sub M(int As Integer)
End Interface
Public Class implementI
Implements I
Private Sub I_M(int_ As Integer) Implements I.M
End Sub
End Class
Public MustInherit Class Base
Public Overridable Sub M1(int As Integer)
End Sub
Public MustOverride Sub M2(int As Integer)
End Class
Public Class Der
Inherits Base
Public Overrides Sub M2(int_ As Integer)
Throw New System.NotImplementedException()
End Sub
Public Overrides Sub M1(int_ As Integer)
MyBase.M1(int_)
End Sub
End Class");
}
[Fact]
public async Task CA1707_ForTypeTypeParameters_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class DoesNotMatter(Of {|#0:T_|})
End Class
Class NoDiag(Of U_)
End Class",
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.TypeTypeParameterRule).WithLocation(0).WithArguments("DoesNotMatter(Of T_)", "T_"), @"
Public Class DoesNotMatter(Of T)
End Class
Class NoDiag(Of U_)
End Class");
}
[Fact]
public async Task CA1707_ForMemberTypeParameters_VisualBasicAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Public Class DoesNotMatter22
Public Sub PublicM1(Of {|#0:T1_|})()
End Sub
Private Sub PrivateM2(Of U_)()
End Sub
Friend Sub InternalM3(Of W_)()
End Sub
Protected Sub ProtectedM4(Of {|#1:D_|})()
End Sub
End Class
Public Interface I
Sub M(Of {|#2:T_|})()
End Interface
Public Class implementI
Implements I
Public Sub M(Of U_)() Implements I.M
Throw New System.NotImplementedException()
End Sub
End Class
Public MustInherit Class Base
Public Overridable Sub M1(Of {|#3:T_|})()
End Sub
Public MustOverride Sub M2(Of {|#4:U_|})()
End Class
Public Class Der
Inherits Base
Public Overrides Sub M2(Of U_)()
Throw New System.NotImplementedException()
End Sub
Public Overrides Sub M1(Of T_)()
MyBase.M1(Of T_)()
End Sub
End Class", new[]
{
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(0).WithArguments("DoesNotMatter22.PublicM1(Of T1_)()", "T1_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(1).WithArguments("DoesNotMatter22.ProtectedM4(Of D_)()", "D_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(2).WithArguments("I.M(Of T_)()", "T_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(3).WithArguments("Base.M1(Of T_)()", "T_"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule).WithLocation(4).WithArguments("Base.M2(Of U_)()", "U_")
}, @"
Public Class DoesNotMatter22
Public Sub PublicM1(Of T1)()
End Sub
Private Sub PrivateM2(Of U_)()
End Sub
Friend Sub InternalM3(Of W_)()
End Sub
Protected Sub ProtectedM4(Of D)()
End Sub
End Class
Public Interface I
Sub M(Of T)()
End Interface
Public Class implementI
Implements I
Public Sub M(Of U_)() Implements I.M
Throw New System.NotImplementedException()
End Sub
End Class
Public MustInherit Class Base
Public Overridable Sub M1(Of T)()
End Sub
Public MustOverride Sub M2(Of U)()
End Class
Public Class Der
Inherits Base
Public Overrides Sub M2(Of U_)()
Throw New System.NotImplementedException()
End Sub
Public Overrides Sub M1(Of T_)()
MyBase.M1(Of T_)()
End Sub
End Class");
}
[Fact, WorkItem(947, "https://github.com/dotnet/roslyn-analyzers/issues/947")]
public async Task CA1707_ForOperators_VisualBasicAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Structure S
Public Shared Operator =(left As S, right As S) As Boolean
Return left.Equals(right)
End Operator
Public Shared Operator <>(left As S, right As S) As Boolean
Return Not (left = right)
End Operator
End Structure
");
}
[Fact, WorkItem(1319, "https://github.com/dotnet/roslyn-analyzers/issues/1319")]
public async Task CA1707_CustomOperator_VisualBasicAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Span
Public Shared Narrowing Operator CType(ByVal text As String) As Span
Return New Span(text)
End Operator
Public Shared Widening Operator CType(ByVal span As Span) As String
Return span.GetText()
End Operator
Private _text As String
Public Sub New(ByVal text)
_text = text
End Sub
Public Function GetText() As String
Return _text
End Function
End Class
");
}
[Fact, WorkItem(3121, "https://github.com/dotnet/roslyn-analyzers/issues/3121")]
public async Task CA1707_VisualBasic_GlobalAsaxSpecialMethodsAsync()
{
await VerifyVB.VerifyCodeFixAsync(@"
Imports System
Namespace System.Web
Public Class HttpApplication
End Class
End Namespace
Public Class ValidContext
Inherits System.Web.HttpApplication
Protected Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_Init(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub
End Class
Public Class InvalidContext
Protected Sub {|#0:Application_AuthenticateRequest|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub {|#1:Application_BeginRequest|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub {|#2:Application_End|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub {|#3:Application_EndRequest|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub {|#4:Application_Error|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub {|#5:Application_Init|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub {|#6:Application_Start|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub {|#7:Session_End|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub {|#8:Session_Start|}(ByVal sender As Object, ByVal e As EventArgs)
End Sub
End Class", new[]
{
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(0).WithArguments("InvalidContext.Application_AuthenticateRequest(Object, System.EventArgs)"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(1).WithArguments("InvalidContext.Application_BeginRequest(Object, System.EventArgs)"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(2).WithArguments("InvalidContext.Application_End(Object, System.EventArgs)"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(3).WithArguments("InvalidContext.Application_EndRequest(Object, System.EventArgs)"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(4).WithArguments("InvalidContext.Application_Error(Object, System.EventArgs)"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(5).WithArguments("InvalidContext.Application_Init(Object, System.EventArgs)"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(6).WithArguments("InvalidContext.Application_Start(Object, System.EventArgs)"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(7).WithArguments("InvalidContext.Session_End(Object, System.EventArgs)"),
VerifyVB.Diagnostic(IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule).WithLocation(8).WithArguments("InvalidContext.Session_Start(Object, System.EventArgs)")
}, @"
Imports System
Namespace System.Web
Public Class HttpApplication
End Class
End Namespace
Public Class ValidContext
Inherits System.Web.HttpApplication
Protected Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_Init(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
End Sub
End Class
Public Class InvalidContext
Protected Sub ApplicationAuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub ApplicationBeginRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub ApplicationEnd(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub ApplicationEndRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub ApplicationError(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub ApplicationInit(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub ApplicationStart(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub SessionEnd(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub SessionStart(ByVal sender As Object, ByVal e As EventArgs)
End Sub
End Class");
}
#endregion
#region Helpers
private static DiagnosticResult GetCA1707CSharpResultAt(int line, int column, SymbolKind symbolKind, params string[] identifierNames)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(GetApproriateRule(symbolKind))
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(identifierNames);
private static DiagnosticResult GetCA1707BasicResultAt(int line, int column, SymbolKind symbolKind, params string[] identifierNames)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(GetApproriateRule(symbolKind))
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(identifierNames);
private static DiagnosticDescriptor GetApproriateRule(SymbolKind symbolKind)
{
return symbolKind switch
{
SymbolKind.Assembly => IdentifiersShouldNotContainUnderscoresAnalyzer.AssemblyRule,
SymbolKind.Namespace => IdentifiersShouldNotContainUnderscoresAnalyzer.NamespaceRule,
SymbolKind.NamedType => IdentifiersShouldNotContainUnderscoresAnalyzer.TypeRule,
SymbolKind.Member => IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule,
SymbolKind.DelegateParameter => IdentifiersShouldNotContainUnderscoresAnalyzer.DelegateParameterRule,
SymbolKind.MemberParameter => IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule,
SymbolKind.TypeTypeParameter => IdentifiersShouldNotContainUnderscoresAnalyzer.TypeTypeParameterRule,
SymbolKind.MethodTypeParameter => IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule,
_ => throw new NotSupportedException("Unknown Symbol Kind"),
};
}
private enum SymbolKind
{
Assembly,
Namespace,
NamedType,
Member,
DelegateParameter,
MemberParameter,
TypeTypeParameter,
MethodTypeParameter
}
#endregion
}
}
| |
using J2N.Numerics;
using System;
using System.Diagnostics;
namespace YAF.Lucene.Net.Util.Packed
{
/*
* 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.
*/
/// <summary>
/// A decoder for an <see cref="Packed.EliasFanoEncoder"/>.
/// <para/>
/// @lucene.internal
/// </summary>
public class EliasFanoDecoder
{
/// <summary>
/// NOTE: This was LOG2_LONG_SIZE in Lucene.
/// </summary>
private static readonly int LOG2_INT64_SIZE = (sizeof(long) * 8).TrailingZeroCount();
private readonly EliasFanoEncoder efEncoder;
private readonly long numEncoded;
private long efIndex = -1; // the decoding index.
private long setBitForIndex = -1; // the index of the high bit at the decoding index.
public const long NO_MORE_VALUES = -1L;
private readonly long numIndexEntries;
private readonly long indexMask;
/// <summary>
/// Construct a decoder for a given <see cref="Packed.EliasFanoEncoder"/>.
/// The decoding index is set to just before the first encoded value.
/// </summary>
public EliasFanoDecoder(EliasFanoEncoder efEncoder)
{
this.efEncoder = efEncoder;
this.numEncoded = efEncoder.numEncoded; // not final in EliasFanoEncoder
this.numIndexEntries = efEncoder.currentEntryIndex; // not final in EliasFanoEncoder
this.indexMask = (1L << efEncoder.nIndexEntryBits) - 1;
}
/// <returns> The Elias-Fano encoder that is decoded. </returns>
public virtual EliasFanoEncoder EliasFanoEncoder
{
get
{
return efEncoder;
}
}
/// <summary>
/// The number of values encoded by the encoder. </summary>
/// <returns> The number of values encoded by the encoder. </returns>
public virtual long NumEncoded
{
get { return numEncoded; }
}
/// <summary>
/// The current decoding index.
/// The first value encoded by <see cref="EliasFanoEncoder.EncodeNext(long)"/> has index 0.
/// Only valid directly after
/// <see cref="NextValue()"/>, <see cref="AdvanceToValue(long)"/>,
/// <see cref="PreviousValue()"/>, or <see cref="BackToValue(long)"/>
/// returned another value than <see cref="NO_MORE_VALUES"/>,
/// or <see cref="AdvanceToIndex(long)"/> returned <c>true</c>. </summary>
/// <returns> The decoding index of the last decoded value, or as last set by <see cref="AdvanceToIndex(long)"/>. </returns>
public virtual long CurrentIndex()
{
if (efIndex < 0)
{
throw new InvalidOperationException("index before sequence");
}
if (efIndex >= numEncoded)
{
throw new InvalidOperationException("index after sequence");
}
return efIndex;
}
/// <summary>
/// The value at the current decoding index.
/// Only valid when <see cref="CurrentIndex()"/> would return a valid result.
/// <para/>
/// This is only intended for use after <see cref="AdvanceToIndex(long)"/> returned <c>true</c>. </summary>
/// <returns> The value encoded at <see cref="CurrentIndex()"/>. </returns>
public virtual long CurrentValue()
{
return CombineHighLowValues(CurrentHighValue(), CurrentLowValue());
}
/// <returns> The high value for the current decoding index. </returns>
private long CurrentHighValue()
{
return setBitForIndex - efIndex; // sequence of unary gaps
}
/// <summary>
/// See also <see cref="EliasFanoEncoder.PackValue(long, long[], int, long)"/> </summary>
private static long UnPackValue(long[] longArray, int numBits, long packIndex, long bitsMask)
{
if (numBits == 0)
{
return 0;
}
long bitPos = packIndex * numBits;
int index = (int)((long)((ulong)bitPos >> LOG2_INT64_SIZE));
int bitPosAtIndex = (int)(bitPos & ((sizeof(long) * 8) - 1));
long value = (long)((ulong)longArray[index] >> bitPosAtIndex);
if ((bitPosAtIndex + numBits) > (sizeof(long) * 8))
{
value |= (longArray[index + 1] << ((sizeof(long) * 8) - bitPosAtIndex));
}
value &= bitsMask;
return value;
}
/// <returns> The low value for the current decoding index. </returns>
private long CurrentLowValue()
{
Debug.Assert(((efIndex >= 0) && (efIndex < numEncoded)), "efIndex " + efIndex);
return UnPackValue(efEncoder.lowerLongs, efEncoder.numLowBits, efIndex, efEncoder.lowerBitsMask);
}
/// <returns> The given <paramref name="highValue"/> shifted left by the number of low bits from by the EliasFanoSequence,
/// logically OR-ed with the given <paramref name="lowValue"/>. </returns>
private long CombineHighLowValues(long highValue, long lowValue)
{
return (highValue << efEncoder.numLowBits) | lowValue;
}
private long curHighLong;
/* The implementation of forward decoding and backward decoding is done by the following method pairs.
*
* toBeforeSequence - toAfterSequence
* getCurrentRightShift - getCurrentLeftShift
* toAfterCurrentHighBit - toBeforeCurrentHighBit
* toNextHighLong - toPreviousHighLong
* nextHighValue - previousHighValue
* nextValue - previousValue
* advanceToValue - backToValue
*
*/
/* Forward decoding section */
/// <summary>
/// Set the decoding index to just before the first encoded value.
/// </summary>
public virtual void ToBeforeSequence()
{
efIndex = -1;
setBitForIndex = -1;
}
/// <returns> The number of bits in a <see cref="long"/> after (<see cref="setBitForIndex"/> modulo <c>sizeof(long)</c>). </returns>
private int CurrentRightShift
{
get
{
int s = (int)(setBitForIndex & ((sizeof(long) * 8) - 1));
return s;
}
}
/// <summary>
/// Increment <see cref="efIndex"/> and <see cref="setBitForIndex"/> and
/// shift <see cref="curHighLong"/> so that it does not contain the high bits before <see cref="setBitForIndex"/>. </summary>
/// <returns> <c>true</c> if <see cref="efIndex"/> still smaller than <see cref="numEncoded"/>. </returns>
private bool ToAfterCurrentHighBit()
{
efIndex += 1;
if (efIndex >= numEncoded)
{
return false;
}
setBitForIndex += 1;
int highIndex = (int)((long)((ulong)setBitForIndex >> LOG2_INT64_SIZE));
curHighLong = (long)((ulong)efEncoder.upperLongs[highIndex] >> CurrentRightShift);
return true;
}
/// <summary>
/// The current high long has been determined to not contain the set bit that is needed.
/// Increment <see cref="setBitForIndex"/> to the next high long and set <see cref="curHighLong"/> accordingly.
/// <para/>
/// NOTE: this was toNextHighLong() in Lucene.
/// </summary>
private void ToNextHighInt64()
{
setBitForIndex += (sizeof(long) * 8) - (setBitForIndex & ((sizeof(long) * 8) - 1));
//assert getCurrentRightShift() == 0;
int highIndex = (int)((long)((ulong)setBitForIndex >> LOG2_INT64_SIZE));
curHighLong = efEncoder.upperLongs[highIndex];
}
/// <summary>
/// <see cref="setBitForIndex"/> and <see cref="efIndex"/> have just been incremented, scan to the next high set bit
/// by incrementing <see cref="setBitForIndex"/>, and by setting <see cref="curHighLong"/> accordingly.
/// </summary>
private void ToNextHighValue()
{
while (curHighLong == 0L)
{
ToNextHighInt64(); // inlining and unrolling would simplify somewhat
}
setBitForIndex += curHighLong.TrailingZeroCount();
}
/// <summary>
/// <see cref="setBitForIndex"/> and <see cref="efIndex"/> have just been incremented, scan to the next high set bit
/// by incrementing <see cref="setBitForIndex"/>, and by setting <see cref="curHighLong"/> accordingly. </summary>
/// <returns> The next encoded high value. </returns>
private long NextHighValue()
{
ToNextHighValue();
return CurrentHighValue();
}
/// <summary>
/// If another value is available after the current decoding index, return this value and
/// and increase the decoding index by 1. Otherwise return <see cref="NO_MORE_VALUES"/>.
/// </summary>
public virtual long NextValue()
{
if (!ToAfterCurrentHighBit())
{
return NO_MORE_VALUES;
}
long highValue = NextHighValue();
return CombineHighLowValues(highValue, CurrentLowValue());
}
/// <summary>
/// Advance the decoding index to a given <paramref name="index"/>.
/// and return <c>true</c> iff it is available.
/// <para/>See also <see cref="CurrentValue()"/>.
/// <para/>The current implementation does not use the index on the upper bit zero bit positions.
/// <para/>Note: there is currently no implementation of <c>BackToIndex()</c>.
/// </summary>
public virtual bool AdvanceToIndex(long index)
{
Debug.Assert(index > efIndex);
if (index >= numEncoded)
{
efIndex = numEncoded;
return false;
}
if (!ToAfterCurrentHighBit())
{
Debug.Assert(false);
}
/* CHECKME: Add a (binary) search in the upperZeroBitPositions here. */
int curSetBits = curHighLong.PopCount();
while ((efIndex + curSetBits) < index) // curHighLong has not enough set bits to reach index
{
efIndex += curSetBits;
ToNextHighInt64();
curSetBits = curHighLong.PopCount();
}
// curHighLong has enough set bits to reach index
while (efIndex < index)
{
/* CHECKME: Instead of the linear search here, use (forward) broadword selection from
* "Broadword Implementation of Rank/Select Queries", Sebastiano Vigna, January 30, 2012.
*/
if (!ToAfterCurrentHighBit())
{
Debug.Assert(false);
}
ToNextHighValue();
}
return true;
}
/// <summary>
/// Given a <paramref name="target"/> value, advance the decoding index to the first bigger or equal value
/// and return it if it is available. Otherwise return <see cref="NO_MORE_VALUES"/>.
/// <para/>
/// The current implementation uses the index on the upper zero bit positions.
/// </summary>
public virtual long AdvanceToValue(long target)
{
efIndex += 1;
if (efIndex >= numEncoded)
{
return NO_MORE_VALUES;
}
setBitForIndex += 1; // the high bit at setBitForIndex belongs to the unary code for efIndex
int highIndex = (int)((long)((ulong)setBitForIndex >> LOG2_INT64_SIZE));
long upperLong = efEncoder.upperLongs[highIndex];
curHighLong = (long)((ulong)upperLong >> ((int)(setBitForIndex & ((sizeof(long) * 8) - 1)))); // may contain the unary 1 bit for efIndex
// determine index entry to advance to
long highTarget = (long)((ulong)target >> efEncoder.numLowBits);
long indexEntryIndex = (highTarget / efEncoder.indexInterval) - 1;
if (indexEntryIndex >= 0) // not before first index entry
{
if (indexEntryIndex >= numIndexEntries)
{
indexEntryIndex = numIndexEntries - 1; // no further than last index entry
}
long indexHighValue = (indexEntryIndex + 1) * efEncoder.indexInterval;
Debug.Assert(indexHighValue <= highTarget);
if (indexHighValue > (setBitForIndex - efIndex)) // advance to just after zero bit position of index entry.
{
setBitForIndex = UnPackValue(efEncoder.upperZeroBitPositionIndex, efEncoder.nIndexEntryBits, indexEntryIndex, indexMask);
efIndex = setBitForIndex - indexHighValue; // the high bit at setBitForIndex belongs to the unary code for efIndex
highIndex = (int)(((ulong)setBitForIndex >> LOG2_INT64_SIZE));
upperLong = efEncoder.upperLongs[highIndex];
curHighLong = (long)((ulong)upperLong >> ((int)(setBitForIndex & ((sizeof(long) * 8) - 1)))); // may contain the unary 1 bit for efIndex
}
Debug.Assert(efIndex < numEncoded); // there is a high value to be found.
}
int curSetBits = curHighLong.PopCount(); // shifted right.
int curClearBits = (sizeof(long) * 8) - curSetBits - ((int)(setBitForIndex & ((sizeof(long) * 8) - 1))); // subtract right shift, may be more than encoded
while (((setBitForIndex - efIndex) + curClearBits) < highTarget)
{
// curHighLong has not enough clear bits to reach highTarget
efIndex += curSetBits;
if (efIndex >= numEncoded)
{
return NO_MORE_VALUES;
}
setBitForIndex += (sizeof(long) * 8) - (setBitForIndex & ((sizeof(long) * 8) - 1));
// highIndex = (int)(setBitForIndex >>> LOG2_LONG_SIZE);
Debug.Assert((highIndex + 1) == (int)((long)((ulong)setBitForIndex >> LOG2_INT64_SIZE)));
highIndex += 1;
upperLong = efEncoder.upperLongs[highIndex];
curHighLong = upperLong;
curSetBits = curHighLong.PopCount();
curClearBits = (sizeof(long) * 8) - curSetBits;
}
// curHighLong has enough clear bits to reach highTarget, and may not have enough set bits.
while (curHighLong == 0L)
{
setBitForIndex += (sizeof(long) * 8) - (setBitForIndex & ((sizeof(long) * 8) - 1));
Debug.Assert((highIndex + 1) == (int)((ulong)setBitForIndex >> LOG2_INT64_SIZE));
highIndex += 1;
upperLong = efEncoder.upperLongs[highIndex];
curHighLong = upperLong;
}
// curHighLong has enough clear bits to reach highTarget, has at least 1 set bit, and may not have enough set bits.
int rank = (int)(highTarget - (setBitForIndex - efIndex)); // the rank of the zero bit for highValue.
Debug.Assert((rank <= (sizeof(long) * 8)), ("rank " + rank));
if (rank >= 1)
{
long invCurHighLong = ~curHighLong;
int clearBitForValue = (rank <= 8) ? BroadWord.SelectNaive(invCurHighLong, rank) : BroadWord.Select(invCurHighLong, rank);
Debug.Assert(clearBitForValue <= ((sizeof(long) * 8) - 1));
setBitForIndex += clearBitForValue + 1; // the high bit just before setBitForIndex is zero
int oneBitsBeforeClearBit = clearBitForValue - rank + 1;
efIndex += oneBitsBeforeClearBit; // the high bit at setBitForIndex and belongs to the unary code for efIndex
if (efIndex >= numEncoded)
{
return NO_MORE_VALUES;
}
if ((setBitForIndex & ((sizeof(long) * 8) - 1)) == 0L) // exhausted curHighLong
{
Debug.Assert((highIndex + 1) == (int)((ulong)setBitForIndex >> LOG2_INT64_SIZE));
highIndex += 1;
upperLong = efEncoder.upperLongs[highIndex];
curHighLong = upperLong;
}
else
{
Debug.Assert(highIndex == (int)((ulong)setBitForIndex >> LOG2_INT64_SIZE));
curHighLong = (long)((ulong)upperLong >> ((int)(setBitForIndex & ((sizeof(long) * 8) - 1))));
}
// curHighLong has enough clear bits to reach highTarget, and may not have enough set bits.
while (curHighLong == 0L)
{
setBitForIndex += (sizeof(long) * 8) - (setBitForIndex & ((sizeof(long) * 8) - 1));
Debug.Assert((highIndex + 1) == (int)((ulong)setBitForIndex >> LOG2_INT64_SIZE));
highIndex += 1;
upperLong = efEncoder.upperLongs[highIndex];
curHighLong = upperLong;
}
}
setBitForIndex += curHighLong.TrailingZeroCount();
Debug.Assert((setBitForIndex - efIndex) >= highTarget); // highTarget reached
// Linear search also with low values
long currentValue = CombineHighLowValues((setBitForIndex - efIndex), CurrentLowValue());
while (currentValue < target)
{
currentValue = NextValue();
if (currentValue == NO_MORE_VALUES)
{
return NO_MORE_VALUES;
}
}
return currentValue;
}
/* Backward decoding section */
/// <summary>
/// Set the decoding index to just after the last encoded value.
/// </summary>
public virtual void ToAfterSequence()
{
efIndex = numEncoded; // just after last index
setBitForIndex = ((long)((ulong)efEncoder.lastEncoded >> efEncoder.numLowBits)) + numEncoded;
}
/// <returns> the number of bits in a long before (<see cref="setBitForIndex"/> modulo <c>sizeof(long)</c>) </returns>
private int CurrentLeftShift
{
get
{
int s = (sizeof(long) * 8) - 1 - (int)(setBitForIndex & ((sizeof(long) * 8) - 1));
return s;
}
}
/// <summary>
/// Decrement <see cref="efIndex"/> and <see cref="setBitForIndex"/> and
/// shift <see cref="curHighLong"/> so that it does not contain the high bits after <see cref="setBitForIndex"/>. </summary>
/// <returns> <c>true</c> if <see cref="efIndex"/> still >= 0. </returns>
private bool ToBeforeCurrentHighBit()
{
efIndex -= 1;
if (efIndex < 0)
{
return false;
}
setBitForIndex -= 1;
int highIndex = (int)((ulong)setBitForIndex >> LOG2_INT64_SIZE);
curHighLong = efEncoder.upperLongs[highIndex] << CurrentLeftShift;
return true;
}
/// <summary>
/// The current high long has been determined to not contain the set bit that is needed.
/// Decrement <see cref="setBitForIndex"/> to the previous high long and set <see cref="curHighLong"/> accordingly.
/// <para/>
/// NOTE: this was toPreviousHighLong() in Lucene.
/// </summary>
private void ToPreviousHighInt64()
{
setBitForIndex -= (setBitForIndex & ((sizeof(long) * 8) - 1)) + 1;
//assert getCurrentLeftShift() == 0;
int highIndex = (int)((ulong)setBitForIndex >> LOG2_INT64_SIZE);
curHighLong = efEncoder.upperLongs[highIndex];
}
/// <summary>
/// <see cref="setBitForIndex"/> and <see cref="efIndex"/> have just been decremented, scan to the previous high set bit
/// by decrementing <see cref="setBitForIndex"/> and by setting <see cref="curHighLong"/> accordingly. </summary>
/// <returns> The previous encoded high value. </returns>
private long PreviousHighValue()
{
while (curHighLong == 0L)
{
ToPreviousHighInt64(); // inlining and unrolling would simplify somewhat
}
setBitForIndex -= curHighLong.LeadingZeroCount();
return CurrentHighValue();
}
/// <summary>
/// If another value is available before the current decoding index, return this value
/// and decrease the decoding index by 1. Otherwise return <see cref="NO_MORE_VALUES"/>.
/// </summary>
public virtual long PreviousValue()
{
if (!ToBeforeCurrentHighBit())
{
return NO_MORE_VALUES;
}
long highValue = PreviousHighValue();
return CombineHighLowValues(highValue, CurrentLowValue());
}
/// <summary>
/// <see cref="setBitForIndex"/> and <see cref="efIndex"/> have just been decremented, scan backward to the high set bit
/// of at most a given high value
/// by decrementing <see cref="setBitForIndex"/> and by setting <see cref="curHighLong"/> accordingly.
/// <para/>
/// The current implementation does not use the index on the upper zero bit positions.
/// </summary>
/// <returns> The largest encoded high value that is at most the given one. </returns>
private long BackToHighValue(long highTarget)
{
/* CHECKME: Add using the index as in advanceToHighValue */
int curSetBits = curHighLong.PopCount(); // is shifted by getCurrentLeftShift()
int curClearBits = (sizeof(long) * 8) - curSetBits - CurrentLeftShift;
while ((CurrentHighValue() - curClearBits) > highTarget)
{
// curHighLong has not enough clear bits to reach highTarget
efIndex -= curSetBits;
if (efIndex < 0)
{
return NO_MORE_VALUES;
}
ToPreviousHighInt64();
//assert getCurrentLeftShift() == 0;
curSetBits = curHighLong.PopCount();
curClearBits = (sizeof(long) * 8) - curSetBits;
}
// curHighLong has enough clear bits to reach highTarget, but may not have enough set bits.
long highValue = PreviousHighValue();
while (highValue > highTarget)
{
/* CHECKME: See at advanceToHighValue on using broadword bit selection. */
if (!ToBeforeCurrentHighBit())
{
return NO_MORE_VALUES;
}
highValue = PreviousHighValue();
}
return highValue;
}
/// <summary>
/// Given a target value, go back to the first smaller or equal value
/// and return it if it is available. Otherwise return <see cref="NO_MORE_VALUES"/>.
/// <para/>
/// The current implementation does not use the index on the upper zero bit positions.
/// </summary>
public virtual long BackToValue(long target)
{
if (!ToBeforeCurrentHighBit())
{
return NO_MORE_VALUES;
}
long highTarget = (long)((ulong)target >> efEncoder.numLowBits);
long highValue = BackToHighValue(highTarget);
if (highValue == NO_MORE_VALUES)
{
return NO_MORE_VALUES;
}
// Linear search with low values:
long currentValue = CombineHighLowValues(highValue, CurrentLowValue());
while (currentValue > target)
{
currentValue = PreviousValue();
if (currentValue == NO_MORE_VALUES)
{
return NO_MORE_VALUES;
}
}
return currentValue;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Text
{
// Copied from https://github.com/dotnet/runtime/blob/a9c5eadd951dcba73167f72cc624eb790573663a/src/libraries/Common/src/System/Text/ValueStringBuilder.cs
internal ref partial struct ValueStringBuilder
{
private char[]? _arrayToReturnToPool;
private Span<char> _chars;
private int _pos;
public ValueStringBuilder(Span<char> initialBuffer)
{
_arrayToReturnToPool = null;
_chars = initialBuffer;
_pos = 0;
}
public ValueStringBuilder(int initialCapacity)
{
_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
_chars = _arrayToReturnToPool;
_pos = 0;
}
public int Length
{
get => _pos;
set
{
Debug.Assert(value >= 0);
Debug.Assert(value <= _chars.Length);
_pos = value;
}
}
public int Capacity => _chars.Length;
public void EnsureCapacity(int capacity)
{
// This is not expected to be called this with negative capacity
Debug.Assert(capacity >= 0);
// If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.
if ((uint)capacity > (uint)_chars.Length)
Grow(capacity - _pos);
}
/// <summary>
/// Get a pinnable reference to the builder.
/// Does not ensure there is a null char after <see cref="Length"/>
/// This overload is pattern matched in the C# 7.3+ compiler so you can omit
/// the explicit method call, and write eg "fixed (char* c = builder)"
/// </summary>
public ref char GetPinnableReference()
{
return ref MemoryMarshal.GetReference(_chars);
}
/// <summary>
/// Get a pinnable reference to the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ref char GetPinnableReference(bool terminate)
{
if (terminate)
{
EnsureCapacity(Length + 1);
_chars[Length] = '\0';
}
return ref MemoryMarshal.GetReference(_chars);
}
public ref char this[int index]
{
get
{
Debug.Assert(index < _pos);
return ref _chars[index];
}
}
public override string ToString()
{
string s = _chars.Slice(0, _pos).ToString();
Dispose();
return s;
}
/// <summary>Returns the underlying storage of the builder.</summary>
public Span<char> RawChars => _chars;
/// <summary>
/// Returns a span around the contents of the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ReadOnlySpan<char> AsSpan(bool terminate)
{
if (terminate)
{
EnsureCapacity(Length + 1);
_chars[Length] = '\0';
}
return _chars.Slice(0, _pos);
}
public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos);
public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start);
public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
public bool TryCopyTo(Span<char> destination, out int charsWritten)
{
if (_chars.Slice(0, _pos).TryCopyTo(destination))
{
charsWritten = _pos;
Dispose();
return true;
}
else
{
charsWritten = 0;
Dispose();
return false;
}
}
public void Insert(int index, char value, int count)
{
if (_pos > _chars.Length - count)
{
Grow(count);
}
int remaining = _pos - index;
_chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
_chars.Slice(index, count).Fill(value);
_pos += count;
}
public void Insert(int index, string? s)
{
if (s == null)
{
return;
}
int count = s.Length;
if (_pos > (_chars.Length - count))
{
Grow(count);
}
int remaining = _pos - index;
_chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));
s.AsSpan().CopyTo(_chars.Slice(index));
_pos += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(char c)
{
int pos = _pos;
if ((uint)pos < (uint)_chars.Length)
{
_chars[pos] = c;
_pos = pos + 1;
}
else
{
GrowAndAppend(c);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(string? s)
{
if (s == null)
{
return;
}
int pos = _pos;
if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
{
_chars[pos] = s[0];
_pos = pos + 1;
}
else
{
AppendSlow(s);
}
}
private void AppendSlow(string s)
{
int pos = _pos;
if (pos > _chars.Length - s.Length)
{
Grow(s.Length);
}
s.AsSpan().CopyTo(_chars.Slice(pos));
_pos += s.Length;
}
public void Append(char c, int count)
{
if (_pos > _chars.Length - count)
{
Grow(count);
}
Span<char> dst = _chars.Slice(_pos, count);
for (int i = 0; i < dst.Length; i++)
{
dst[i] = c;
}
_pos += count;
}
public unsafe void Append(char* value, int length)
{
int pos = _pos;
if (pos > _chars.Length - length)
{
Grow(length);
}
Span<char> dst = _chars.Slice(_pos, length);
for (int i = 0; i < dst.Length; i++)
{
dst[i] = *value++;
}
_pos += length;
}
public void Append(ReadOnlySpan<char> value)
{
int pos = _pos;
if (pos > _chars.Length - value.Length)
{
Grow(value.Length);
}
value.CopyTo(_chars.Slice(_pos));
_pos += value.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<char> AppendSpan(int length)
{
int origPos = _pos;
if (origPos > _chars.Length - length)
{
Grow(length);
}
_pos = origPos + length;
return _chars.Slice(origPos, length);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void GrowAndAppend(char c)
{
Grow(1);
Append(c);
}
/// <summary>
/// Resize the internal buffer either by doubling current buffer size or
/// by adding <paramref name="additionalCapacityBeyondPos"/> to
/// <see cref="_pos"/> whichever is greater.
/// </summary>
/// <param name="additionalCapacityBeyondPos">
/// Number of chars requested beyond current position.
/// </param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void Grow(int additionalCapacityBeyondPos)
{
Debug.Assert(additionalCapacityBeyondPos > 0);
Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
// Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative
char[] poolArray = ArrayPool<char>.Shared.Rent((int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), (uint)_chars.Length * 2));
_chars.Slice(0, _pos).CopyTo(poolArray);
char[]? toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = poolArray;
if (toReturn != null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
char[]? toReturn = _arrayToReturnToPool;
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
if (toReturn != null)
{
ArrayPool<char>.Shared.Return(toReturn);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Semantics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder
{
internal readonly struct RuntimeBinder
{
private static readonly object s_bindLock = new object();
private readonly ExpressionBinder _binder;
internal bool IsChecked => _binder.Context.Checked;
public RuntimeBinder(Type contextType, bool isChecked = false)
{
AggregateSymbol context;
if (contextType != null)
{
lock (s_bindLock)
{
context = ((AggregateType)SymbolTable.GetCTypeFromType(contextType)).OwningAggregate;
}
}
else
{
context = null;
}
_binder = new ExpressionBinder(new BindingContext(context, isChecked));
}
public Expression Bind(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding)
{
// The lock is here to protect this instance of the binder from itself
// when called on multiple threads. The cost in time of a single lock
// on a single thread appears to be negligible and dominated by the cost
// of the bind itself. My timing of 4000 consecutive dynamic calls with
// bind, where the body of the called method is empty, are as follows
// (five samples):
//
// Without lock() With lock()
// = 00:00:10.7597696 = 00:00:10.7222606
// = 00:00:10.0711116 = 00:00:10.1818496
// = 00:00:09.9905507 = 00:00:10.1628693
// = 00:00:09.9892183 = 00:00:10.0750007
// = 00:00:09.9253234 = 00:00:10.0340266
//
// ...subsequent calls that were cache hits, i.e., already bound, took less
// than 1/1000 sec for the whole 4000 of them.
lock (s_bindLock)
{
return BindCore(payload, parameters, args, out deferredBinding);
}
}
private Expression BindCore(
ICSharpBinder payload,
Expression[] parameters,
DynamicMetaObject[] args,
out DynamicMetaObject deferredBinding)
{
Debug.Assert(args.Length >= 1);
ArgumentObject[] arguments = CreateArgumentArray(payload, parameters, args);
// On any given bind call, we populate the symbol table with any new
// conversions that we find for any of the types specified. We keep a
// running SymbolTable so that we don't have to reflect over types if
// we've seen them already in the table.
//
// Once we've loaded all the standard conversions into the symbol table,
// we can call into the binder to bind the actual call.
payload.PopulateSymbolTableWithName(arguments[0].Type, arguments);
AddConversionsForArguments(arguments);
// When we do any bind, we perform the following steps:
//
// 1) Create a local variable scope which contains local variable symbols
// for each of the parameters, and the instance argument.
// 2) If we have operators, then we don't need to do lookup. Otherwise,
// look for the name and switch on the result - dispatch according to
// the symbol kind. This results in an Expr being bound that is the expression.
// 3) Create the EXPRRETURN which returns the call and wrap it in
// an EXPRBOUNDLAMBDA which uses the local variable scope
// created in step (1) as its local scope.
// 4) Call the ExpressionTreeRewriter to generate a set of EXPRCALLs
// that call the static ExpressionTree factory methods.
// 5) Call the EXPRTreeToExpressionTreeVisitor to generate the actual
// Linq expression tree for the whole thing and return it.
// (1) - Create the locals
Scope pScope = SymFactory.CreateScope();
LocalVariableSymbol[] locals = PopulateLocalScope(payload, pScope, arguments, parameters);
// (1.5) - Check to see if we need to defer.
if (DeferBinding(payload, arguments, args, locals, out deferredBinding))
{
return null;
}
// (2) - look the thing up and dispatch.
Expr pResult = payload.DispatchPayload(this, arguments, locals);
Debug.Assert(pResult != null);
return CreateExpressionTreeFromResult(parameters, pScope, pResult);
}
#region Helpers
[ConditionalAttribute("DEBUG")]
internal static void EnsureLockIsTaken()
{
// Make sure that the binder lock is taken
Debug.Assert(System.Threading.Monitor.IsEntered(s_bindLock));
}
private bool DeferBinding(
ICSharpBinder payload,
ArgumentObject[] arguments,
DynamicMetaObject[] args,
LocalVariableSymbol[] locals,
out DynamicMetaObject deferredBinding)
{
// This method deals with any deferrals we need to do. We check deferrals up front
// and bail early if we need to do them.
// (1) InvokeMember deferral.
//
// This is the deferral for the d.Foo() scenario where Foo actually binds to a
// field or property, and not a method group that is invocable. We defer to
// the standard GetMember/Invoke pattern.
CSharpInvokeMemberBinder callPayload = payload as CSharpInvokeMemberBinder;
if (callPayload != null)
{
int arity = callPayload.TypeArguments?.Length ?? 0;
MemberLookup mem = new MemberLookup();
Expr callingObject = CreateCallingObjectForCall(callPayload, arguments, locals);
SymWithType swt = SymbolTable.LookupMember(
callPayload.Name,
callingObject,
_binder.Context.ContextForMemberLookup,
arity,
mem,
(callPayload.Flags & CSharpCallFlags.EventHookup) != 0,
true);
if (swt != null && swt.Sym.getKind() != SYMKIND.SK_MethodSymbol)
{
// The GetMember only has one argument, and we need to just take the first arg info.
CSharpGetMemberBinder getMember = new CSharpGetMemberBinder(callPayload.Name, false, callPayload.CallingContext, new CSharpArgumentInfo[] { callPayload.GetArgumentInfo(0) }).TryGetExisting();
// The Invoke has the remaining argument infos. However, we need to redo the first one
// to correspond to the GetMember result.
CSharpArgumentInfo[] argInfos = callPayload.ArgumentInfoArray();
argInfos[0] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
CSharpInvokeBinder invoke = new CSharpInvokeBinder(callPayload.Flags, callPayload.CallingContext, argInfos).TryGetExisting();
DynamicMetaObject[] newArgs = new DynamicMetaObject[args.Length - 1];
Array.Copy(args, 1, newArgs, 0, args.Length - 1);
deferredBinding = invoke.Defer(getMember.Defer(args[0]), newArgs);
return true;
}
}
deferredBinding = null;
return false;
}
private static Expression CreateExpressionTreeFromResult(Expression[] parameters, Scope pScope, Expr pResult)
{
// (3) - Place the result in a return statement and create the ExprBoundLambda.
ExprBoundLambda boundLambda = GenerateBoundLambda(pScope, pResult);
// (4) - Rewrite the ExprBoundLambda into an expression tree.
ExprBinOp exprTree = ExpressionTreeRewriter.Rewrite(boundLambda);
// (5) - Create the actual Expression Tree
Expression e = ExpressionTreeCallRewriter.Rewrite(exprTree, parameters);
return e;
}
private Type GetArgumentType(ICSharpBinder p, CSharpArgumentInfo argInfo, Expression param, DynamicMetaObject arg, int index)
{
Type t = argInfo.UseCompileTimeType ? param.Type : arg.LimitType;
Debug.Assert(t != null);
if (argInfo.IsByRefOrOut)
{
// If we have a ref our an out parameter, make the byref type.
// If we have the receiver of a call or invoke that is ref, it must be because of
// a struct caller. Don't persist the ref for that.
if (!(index == 0 && p.IsBinderThatCanHaveRefReceiver))
{
t = t.MakeByRefType();
}
}
else if (!argInfo.UseCompileTimeType)
{
// If we don't have ref or out, then pick the best type to represent this value.
// If the runtime value has a type that is not accessible, then we pick an
// accessible type that is "closest" in some sense, where we recursively widen
// components of type that can validly vary covariantly.
// This ensures that the type we pick is something that the user could have written.
// Since the actual type of these arguments are never going to be pointer
// types or ref/out types (they are in fact boxed into an object), we have
// a guarantee that we will always be able to find a best accessible type
// (which, in the worst case, may be object).
CType actualType = SymbolTable.GetCTypeFromType(t);
CType bestType = TypeManager.GetBestAccessibleType(_binder.Context.ContextForMemberLookup, actualType);
t = bestType.AssociatedSystemType;
}
return t;
}
/////////////////////////////////////////////////////////////////////////////////
private ArgumentObject[] CreateArgumentArray(
ICSharpBinder payload,
Expression[] parameters,
DynamicMetaObject[] args)
{
// Check the payloads to see whether or not we need to get the runtime types for
// these arguments.
ArgumentObject[] array = new ArgumentObject[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
CSharpArgumentInfo info = payload.GetArgumentInfo(i);
array[i] = new ArgumentObject(args[i].Value, info, GetArgumentType(payload, info, parameters[i], args[i], i));
Debug.Assert(array[i].Type != null);
}
return array;
}
/////////////////////////////////////////////////////////////////////////////////
internal static void PopulateSymbolTableWithPayloadInformation(
ICSharpInvokeOrInvokeMemberBinder callOrInvoke, Type callingType, ArgumentObject[] arguments)
{
Type type;
if (callOrInvoke.StaticCall)
{
type = arguments[0].Value as Type;
if (type == null)
{
throw Error.BindStaticRequiresType(arguments[0].Info.Name);
}
}
else
{
type = callingType;
}
SymbolTable.PopulateSymbolTableWithName(
callOrInvoke.Name,
callOrInvoke.TypeArguments,
type);
// If it looks like we're invoking a get_ or a set_, load the property as well.
// This is because we need COM indexed properties called via method calls to
// work the same as it used to.
if (callOrInvoke.Name.StartsWith("set_", StringComparison.Ordinal) ||
callOrInvoke.Name.StartsWith("get_", StringComparison.Ordinal))
{
SymbolTable.PopulateSymbolTableWithName(
callOrInvoke.Name.Substring(4), //remove prefix
callOrInvoke.TypeArguments,
type);
}
}
/////////////////////////////////////////////////////////////////////////////////
private static void AddConversionsForArguments(ArgumentObject[] arguments)
{
foreach (ArgumentObject arg in arguments)
{
SymbolTable.AddConversionsForType(arg.Type);
}
}
/////////////////////////////////////////////////////////////////////////////////
internal ExprWithArgs DispatchPayload(ICSharpInvokeOrInvokeMemberBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) =>
BindCall(payload, CreateCallingObjectForCall(payload, arguments, locals), arguments, locals);
/////////////////////////////////////////////////////////////////////////////////
// We take the ArgumentObjects to verify - if the parameter expression tells us
// we have a ref parameter, but the argument object tells us we're not passed by ref,
// then it means it was a ref that the compiler had to insert. This is used when
// we have a call off of a struct for example. If thats the case, don't treat the
// local as a ref type.
private static LocalVariableSymbol[] PopulateLocalScope(
ICSharpBinder payload,
Scope pScope,
ArgumentObject[] arguments,
Expression[] parameterExpressions)
{
// We use the compile time types for the local variables, and then
// cast them to the runtime types for the expression tree.
LocalVariableSymbol[] locals = new LocalVariableSymbol[parameterExpressions.Length];
for (int i = 0; i < parameterExpressions.Length; i++)
{
Expression parameter = parameterExpressions[i];
CType type = SymbolTable.GetCTypeFromType(parameter.Type);
// Make sure we're not setting ref for the receiver of a call - the argument
// will be marked as ref if we're calling off a struct, but we don't want
// to persist that in our system.
// If we're the first param of a call or invoke, and we're ref, it must be
// because of structs. Don't persist the parameter modifier type.
if (i != 0 || !payload.IsBinderThatCanHaveRefReceiver)
{
// If we have a ref or out, get the parameter modifier type.
ParameterExpression paramExp = parameter as ParameterExpression;
if (paramExp != null && paramExp.IsByRef)
{
CSharpArgumentInfo info = arguments[i].Info;
if (info.IsByRefOrOut)
{
type = TypeManager.GetParameterModifier(type, info.IsOut);
}
}
}
LocalVariableSymbol local =
SymFactory.CreateLocalVar(NameManager.Add("p" + i), pScope, type);
locals[i] = local;
}
return locals;
}
/////////////////////////////////////////////////////////////////////////////////
private static ExprBoundLambda GenerateBoundLambda(Scope pScope, Expr call)
{
// We don't actually need the real delegate type here - we just need SOME delegate type.
// This is because we never attempt any conversions on the lambda itself.
AggregateType delegateType = SymbolLoader.GetPredefindType(PredefinedType.PT_FUNC);
return ExprFactory.CreateAnonymousMethod(delegateType, pScope, call);
}
#region ExprCreation
/////////////////////////////////////////////////////////////////////////////////
private Expr CreateLocal(Type type, bool isOut, LocalVariableSymbol local)
{
CType ctype;
if (isOut)
{
// We need to record the out state, but GetCTypeFromType will only determine that
// it should be some sort of ParameterType but not be able to deduce that it needs
// IsOut to be true. So do that logic here rather than create a ref type to then
// throw away.
Debug.Assert(type.IsByRef);
ctype = TypeManager.GetParameterModifier(SymbolTable.GetCTypeFromType(type.GetElementType()), true);
}
else
{
ctype = SymbolTable.GetCTypeFromType(type);
}
// If we can convert, do that. If not, cast it.
ExprLocal exprLocal = ExprFactory.CreateLocal(local);
Expr result = _binder.tryConvert(exprLocal, ctype) ?? _binder.mustCast(exprLocal, ctype);
result.Flags |= EXPRFLAG.EXF_LVALUE;
return result;
}
/////////////////////////////////////////////////////////////////////////////////
internal Expr CreateArgumentListEXPR(
ArgumentObject[] arguments,
LocalVariableSymbol[] locals,
int startIndex,
int endIndex)
{
Expr args = null;
Expr last = null;
if (arguments != null)
{
for (int i = startIndex; i < endIndex; i++)
{
ArgumentObject argument = arguments[i];
Expr arg = CreateArgumentEXPR(argument, locals[i]);
if (args == null)
{
args = arg;
last = args;
}
else
{
// Lists are right-heavy.
ExprFactory.AppendItemToList(arg, ref args, ref last);
}
}
}
return args;
}
/////////////////////////////////////////////////////////////////////////////////
private Expr CreateArgumentEXPR(ArgumentObject argument, LocalVariableSymbol local)
{
Expr arg;
if (argument.Info.LiteralConstant)
{
if (argument.Value == null)
{
if (argument.Info.UseCompileTimeType)
{
arg = ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), default(ConstVal));
}
else
{
arg = ExprFactory.CreateNull();
}
}
else
{
arg = ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), ConstVal.Get(argument.Value));
}
}
else
{
// If we have a dynamic argument and it was null, the type is going to be Object.
// But we want it to be typed NullType so we can have null conversions.
if (!argument.Info.UseCompileTimeType && argument.Value == null)
{
arg = ExprFactory.CreateNull();
}
else
{
arg = CreateLocal(argument.Type, argument.Info.IsOut, local);
}
}
// Now check if we have a named thing. If so, wrap this thing in a named argument.
if (argument.Info.NamedArgument)
{
Debug.Assert(argument.Info.Name != null);
arg = ExprFactory.CreateNamedArgumentSpecification(NameManager.Add(argument.Info.Name), arg);
}
// If we have an object that was "dynamic" at compile time, we need
// to be able to convert it to every interface that the actual value
// implements. This allows conversion binders and overload resolution
// to behave as though type information is available for these Exprs,
// even though it may be the case that the actual runtime type is
// inaccessible and therefore unused.
// This comes in handy for, e.g., iterators (they are nested private
// classes), and COM RCWs without type information (they do not expose
// their interfaces in a usual way).
// It is critical that arg.RuntimeObject is non-null only when the
// compile time type of the argument is dynamic, otherwise normal C#
// semantics on typed arguments will be broken.
if (!argument.Info.UseCompileTimeType && argument.Value != null)
{
arg.RuntimeObject = argument.Value;
arg.RuntimeObjectActualType = SymbolTable.GetCTypeFromType(argument.Value.GetType());
}
return arg;
}
/////////////////////////////////////////////////////////////////////////////////
private static ExprMemberGroup CreateMemberGroupExpr(
string Name,
Type[] typeArguments,
Expr callingObject,
SYMKIND kind)
{
Name name = NameManager.Add(Name);
AggregateType callingType;
CType callingObjectType = callingObject.Type;
if (callingObjectType is ArrayType)
{
callingType = SymbolLoader.GetPredefindType(PredefinedType.PT_ARRAY);
}
else if (callingObjectType is NullableType callingNub)
{
callingType = callingNub.GetAts();
}
else
{
callingType = (AggregateType)callingObjectType;
}
// The C# binder expects that only the base virtual method is inserted
// into the list of candidates, and only the type containing the base
// virtual method is inserted into the list of types. However, since we
// don't want to do all the logic, we're just going to insert every type
// that has a member of the given name, and allow the C# binder to filter
// out all overrides.
// CONSIDER: using a hashset to filter out duplicate interface types.
// Adopt a smarter algorithm to filter types before creating the exception.
HashSet<CType> distinctCallingTypes = new HashSet<CType>();
List<CType> callingTypes = new List<CType>();
// Find that set of types now.
symbmask_t mask = symbmask_t.MASK_MethodSymbol;
switch (kind)
{
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_IndexerSymbol:
mask = symbmask_t.MASK_PropertySymbol;
break;
case SYMKIND.SK_MethodSymbol:
mask = symbmask_t.MASK_MethodSymbol;
break;
default:
Debug.Fail("Unhandled kind");
break;
}
// If we have a constructor, only find its type.
bool bIsConstructor = name == NameManager.GetPredefinedName(PredefinedName.PN_CTOR);
foreach(AggregateType t in callingType.TypeHierarchy)
{
if (SymbolTable.AggregateContainsMethod(t.OwningAggregate, Name, mask) && distinctCallingTypes.Add(t))
{
callingTypes.Add(t);
}
// If we have a constructor, run the loop once for the constructor's type, and thats it.
if (bIsConstructor)
{
break;
}
}
// If this is a WinRT type we have to add all collection interfaces that have this method
// as well so that overload resolution can find them.
if (callingType.IsWindowsRuntimeType)
{
foreach (AggregateType t in callingType.WinRTCollectionIfacesAll.Items)
{
if (SymbolTable.AggregateContainsMethod(t.OwningAggregate, Name, mask) && distinctCallingTypes.Add(t))
{
callingTypes.Add(t);
}
}
}
EXPRFLAG flags = EXPRFLAG.EXF_USERCALLABLE;
// If its a delegate, mark that on the memgroup.
if (Name == SpecialNames.Invoke && callingObject.Type.IsDelegateType)
{
flags |= EXPRFLAG.EXF_DELEGATE;
}
// For a constructor, we need to seed the memgroup with the constructor flag.
if (Name == SpecialNames.Constructor)
{
flags |= EXPRFLAG.EXF_CTOR;
}
// If we have an indexer, mark that.
if (Name == SpecialNames.Indexer)
{
flags |= EXPRFLAG.EXF_INDEXER;
}
TypeArray typeArgumentsAsTypeArray = typeArguments?.Length > 0
? TypeArray.Allocate(SymbolTable.GetCTypeArrayFromTypes(typeArguments))
: TypeArray.Empty;
ExprMemberGroup memgroup = ExprFactory.CreateMemGroup( // Tree
flags, name, typeArgumentsAsTypeArray, kind, callingType, null,
new CMemberLookupResults(TypeArray.Allocate(callingTypes.ToArray()), name));
if (!(callingObject is ExprClass))
{
memgroup.OptionalObject = callingObject;
}
return memgroup;
}
/////////////////////////////////////////////////////////////////////////////////
private Expr CreateProperty(
SymWithType swt,
Expr callingObject,
BindingFlag flags)
{
// For a property, we simply create the EXPRPROP for the thing, call the
// expression tree rewriter, rewrite it, and send it on its way.
PropertySymbol property = swt.Prop();
AggregateType propertyType = swt.GetType();
PropWithType pwt = new PropWithType(property, propertyType);
ExprMemberGroup pMemGroup = CreateMemberGroupExpr(property.name.Text, null, callingObject, SYMKIND.SK_PropertySymbol);
return _binder.BindToProperty(// For a static property instance, don't set the object.
callingObject is ExprClass ? null : callingObject, pwt, flags, null, pMemGroup);
}
/////////////////////////////////////////////////////////////////////////////////
private ExprWithArgs CreateIndexer(SymWithType swt, Expr callingObject, Expr arguments, BindingFlag bindFlags)
{
IndexerSymbol index = swt.Sym as IndexerSymbol;
ExprMemberGroup memgroup = CreateMemberGroupExpr(index.name.Text, null, callingObject, SYMKIND.SK_PropertySymbol);
ExprWithArgs result = _binder.BindMethodGroupToArguments(bindFlags, memgroup, arguments);
ReorderArgumentsForNamedAndOptional(callingObject, result);
return result;
}
/////////////////////////////////////////////////////////////////////////////////
private Expr CreateArray(Expr callingObject, Expr optionalIndexerArguments)
{
return _binder.BindArrayIndexCore(callingObject, optionalIndexerArguments);
}
/////////////////////////////////////////////////////////////////////////////////
private Expr CreateField(
SymWithType swt,
Expr callingObject)
{
// For a field, simply create the EXPRFIELD and our caller takes care of the rest.
FieldSymbol fieldSymbol = swt.Field();
AggregateType fieldType = swt.GetType();
FieldWithType fwt = new FieldWithType(fieldSymbol, fieldType);
Expr field = _binder.BindToField(callingObject is ExprClass ? null : callingObject, fwt, 0);
return field;
}
/////////////////////////////////////////////////////////////////////////////////
#endregion
#endregion
#region Calls
/////////////////////////////////////////////////////////////////////////////////
private Expr CreateCallingObjectForCall(
ICSharpInvokeOrInvokeMemberBinder payload,
ArgumentObject[] arguments,
LocalVariableSymbol[] locals)
{
// Here we have a regular call, so create the calling object off of the first
// parameter and pass it through.
Expr callingObject;
if (payload.StaticCall)
{
Type t = arguments[0].Value as Type;
Debug.Assert(t != null); // Would have thrown in PopulateSymbolTableWithPayloadInformation already
callingObject = ExprFactory.CreateClass(SymbolTable.GetCTypeFromType(t));
}
else
{
// If we have a null argument, just bail and throw.
if (!arguments[0].Info.UseCompileTimeType && arguments[0].Value == null)
{
throw Error.NullReferenceOnMemberException();
}
callingObject = _binder.mustConvert(
CreateArgumentEXPR(arguments[0], locals[0]),
SymbolTable.GetCTypeFromType(arguments[0].Type));
if (arguments[0].Type.IsValueType && callingObject is ExprCast)
{
// If we have a struct type, unbox it.
callingObject.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME;
}
}
return callingObject;
}
/////////////////////////////////////////////////////////////////////////////////
private ExprWithArgs BindCall(
ICSharpInvokeOrInvokeMemberBinder payload,
Expr callingObject,
ArgumentObject[] arguments,
LocalVariableSymbol[] locals)
{
if (payload is InvokeBinder && !callingObject.Type.IsDelegateType)
{
throw Error.BindInvokeFailedNonDelegate();
}
int arity = payload.TypeArguments?.Length ?? 0;
MemberLookup mem = new MemberLookup();
SymWithType swt = SymbolTable.LookupMember(
payload.Name,
callingObject,
_binder.Context.ContextForMemberLookup,
arity,
mem,
(payload.Flags & CSharpCallFlags.EventHookup) != 0,
true);
if (swt == null)
{
throw mem.ReportErrors();
}
if (swt.Sym.getKind() != SYMKIND.SK_MethodSymbol)
{
Debug.Fail("Unexpected type returned from lookup");
throw Error.InternalCompilerError();
}
// At this point, we're set up to do binding. We need to do the following:
//
// 1) Create the EXPRLOCALs for the arguments, linking them to the local
// variable symbols defined above.
// 2) Create the EXPRMEMGRP for the call and the EXPRLOCAL for the object
// of the call, and link the correct local variable symbol as above.
// 3) Do overload resolution to get back an EXPRCALL.
//
// Our caller takes care of the rest.
// First we need to check the sym that we got back. If we got back a static
// method, then we may be in the situation where the user called the method
// via a simple name call through the phantom overload. If thats the case,
// then we want to sub in a type instead of the object.
ExprMemberGroup memGroup = CreateMemberGroupExpr(payload.Name, payload.TypeArguments, callingObject, swt.Sym.getKind());
if ((payload.Flags & CSharpCallFlags.SimpleNameCall) != 0)
{
callingObject.Flags |= EXPRFLAG.EXF_SIMPLENAME;
}
if ((payload.Flags & CSharpCallFlags.EventHookup) != 0)
{
mem = new MemberLookup();
SymWithType swtEvent = SymbolTable.LookupMember(
payload.Name.Split('_')[1],
callingObject,
_binder.Context.ContextForMemberLookup,
arity,
mem,
(payload.Flags & CSharpCallFlags.EventHookup) != 0,
true);
if (swtEvent == null)
{
throw mem.ReportErrors();
}
CType eventCType = null;
if (swtEvent.Sym.getKind() == SYMKIND.SK_FieldSymbol)
{
eventCType = swtEvent.Field().GetType();
}
else if (swtEvent.Sym.getKind() == SYMKIND.SK_EventSymbol)
{
eventCType = swtEvent.Event().type;
}
Type eventType = TypeManager.SubstType(eventCType, swtEvent.Ats).AssociatedSystemType;
if (eventType != null)
{
// If we have an event hookup, first find the event itself.
BindImplicitConversion(new ArgumentObject[] { arguments[1] }, eventType, locals, false);
}
memGroup.Flags &= ~EXPRFLAG.EXF_USERCALLABLE;
if (swtEvent.Sym.getKind() == SYMKIND.SK_EventSymbol && swtEvent.Event().IsWindowsRuntimeEvent)
{
return BindWinRTEventAccessor(
new EventWithType(swtEvent.Event(), swtEvent.Ats),
callingObject,
arguments,
locals,
payload.Name.StartsWith("add_", StringComparison.Ordinal)); //isAddAccessor?
}
}
// Check if we have a potential call to an indexed property accessor.
// If so, we'll flag overload resolution to let us call non-callables.
if ((payload.Name.StartsWith("set_", StringComparison.Ordinal) && ((MethodSymbol)swt.Sym).Params.Count > 1) ||
(payload.Name.StartsWith("get_", StringComparison.Ordinal) && ((MethodSymbol)swt.Sym).Params.Count > 0))
{
memGroup.Flags &= ~EXPRFLAG.EXF_USERCALLABLE;
}
ExprCall result = _binder.BindMethodGroupToArguments(// Tree
BindingFlag.BIND_RVALUEREQUIRED | BindingFlag.BIND_STMTEXPRONLY, memGroup, CreateArgumentListEXPR(arguments, locals, 1, arguments.Length)) as ExprCall;
Debug.Assert(result != null);
CheckForConditionalMethodError(result);
ReorderArgumentsForNamedAndOptional(callingObject, result);
return result;
}
private ExprWithArgs BindWinRTEventAccessor(EventWithType ewt, Expr callingObject, ArgumentObject[] arguments, LocalVariableSymbol[] locals, bool isAddAccessor)
{
// We want to generate either:
// WindowsRuntimeMarshal.AddEventHandler<delegType>(new Func<delegType, EventRegistrationToken>(x.add_foo), new Action<EventRegistrationToken>(x.remove_foo), value)
// or
// WindowsRuntimeMarshal.RemoveEventHandler<delegType>(new Action<EventRegistrationToken>(x.remove_foo), value)
Type evtType = ewt.Event().type.AssociatedSystemType;
// Get new Action<EventRegistrationToken>(x.remove_foo)
MethPropWithInst removemwi = new MethPropWithInst(ewt.Event().methRemove, ewt.Ats);
ExprMemberGroup removeMethGrp = ExprFactory.CreateMemGroup(callingObject, removemwi);
removeMethGrp.Flags &= ~EXPRFLAG.EXF_USERCALLABLE;
Type eventRegistrationTokenType = SymbolTable.EventRegistrationTokenType;
Type actionType = Expression.GetActionType(eventRegistrationTokenType);
Expr removeMethArg = _binder.mustConvert(removeMethGrp, SymbolTable.GetCTypeFromType(actionType));
// The value
Expr delegateVal = CreateArgumentEXPR(arguments[1], locals[1]);
ExprList args;
string methodName;
if (isAddAccessor)
{
// Get new Func<delegType, EventRegistrationToken>(x.add_foo)
MethPropWithInst addmwi = new MethPropWithInst(ewt.Event().methAdd, ewt.Ats);
ExprMemberGroup addMethGrp = ExprFactory.CreateMemGroup(callingObject, addmwi);
addMethGrp.Flags &= ~EXPRFLAG.EXF_USERCALLABLE;
Type funcType = Expression.GetFuncType(evtType, eventRegistrationTokenType);
Expr addMethArg = _binder.mustConvert(addMethGrp, SymbolTable.GetCTypeFromType(funcType));
args = ExprFactory.CreateList(addMethArg, removeMethArg, delegateVal);
methodName = NameManager.GetPredefinedName(PredefinedName.PN_ADDEVENTHANDLER).Text;
}
else
{
args = ExprFactory.CreateList(removeMethArg, delegateVal);
methodName = NameManager.GetPredefinedName(PredefinedName.PN_REMOVEEVENTHANDLER).Text;
}
// WindowsRuntimeMarshal.Add\RemoveEventHandler(...)
Type windowsRuntimeMarshalType = SymbolTable.WindowsRuntimeMarshalType;
SymbolTable.PopulateSymbolTableWithName(methodName, new List<Type> { evtType }, windowsRuntimeMarshalType);
ExprClass marshalClass = ExprFactory.CreateClass(SymbolTable.GetCTypeFromType(windowsRuntimeMarshalType));
ExprMemberGroup addEventGrp = CreateMemberGroupExpr(methodName, new [] { evtType }, marshalClass, SYMKIND.SK_MethodSymbol);
return _binder.BindMethodGroupToArguments(
BindingFlag.BIND_RVALUEREQUIRED | BindingFlag.BIND_STMTEXPRONLY,
addEventGrp,
args);
}
private static void CheckForConditionalMethodError(ExprCall call)
{
MethodSymbol method = call.MethWithInst.Meth();
object[] conditions = method.AssociatedMemberInfo.GetCustomAttributes(typeof(ConditionalAttribute), true);
if (conditions.Length > 0)
{
throw Error.BindCallToConditionalMethod(method.name);
}
}
private void ReorderArgumentsForNamedAndOptional(Expr callingObject, ExprWithArgs result)
{
Expr arguments = result.OptionalArguments;
AggregateType type;
MethodOrPropertySymbol methprop;
ExprMemberGroup memgroup;
TypeArray typeArgs;
if (result is ExprCall call)
{
type = call.MethWithInst.Ats;
methprop = call.MethWithInst.Meth();
memgroup = call.MemberGroup;
typeArgs = call.MethWithInst.TypeArgs;
}
else
{
ExprProperty prop = result as ExprProperty;
Debug.Assert(prop != null);
type = prop.PropWithTypeSlot.Ats;
methprop = prop.PropWithTypeSlot.Prop();
memgroup = prop.MemberGroup;
typeArgs = null;
}
ArgInfos argInfo = new ArgInfos
{
carg = ExpressionBinder.CountArguments(arguments)
};
ExpressionBinder.FillInArgInfoFromArgList(argInfo, arguments);
// We need to substitute type parameters BEFORE getting the most derived one because
// we're binding against the base method, and the derived method may change the
// generic arguments.
TypeArray parameters = TypeManager.SubstTypeArray(methprop.Params, type, typeArgs);
methprop = ExpressionBinder.GroupToArgsBinder.FindMostDerivedMethod(methprop, callingObject.Type);
ExpressionBinder.GroupToArgsBinder.ReOrderArgsForNamedArguments(
methprop, parameters, type, memgroup, argInfo);
Expr pList = null;
// We reordered, so make a new list of them and set them on the constructor.
// Go backwards cause lists are right-flushed.
// Also perform the conversions to the right types.
for (int i = argInfo.carg - 1; i >= 0; i--)
{
Expr pArg = argInfo.prgexpr[i];
// Strip the name-ness away, since we don't need it.
pArg = StripNamedArgument(pArg);
// Perform the correct conversion.
pArg = _binder.tryConvert(pArg, parameters[i]);
pList = pList == null ? pArg : ExprFactory.CreateList(pArg, pList);
}
result.OptionalArguments = pList;
}
private Expr StripNamedArgument(Expr pArg)
{
if (pArg is ExprNamedArgumentSpecification named)
{
pArg = named.Value;
}
else if (pArg is ExprArrayInit init)
{
init.OptionalArguments = StripNamedArguments(init.OptionalArguments);
}
return pArg;
}
private Expr StripNamedArguments(Expr pArg)
{
if (pArg is ExprList list)
{
for(;;)
{
list.OptionalElement = StripNamedArgument(list.OptionalElement);
if (list.OptionalNextListNode is ExprList next)
{
list = next;
}
else
{
list.OptionalNextListNode = StripNamedArgument(list.OptionalNextListNode);
break;
}
}
}
return StripNamedArgument(pArg);
}
#endregion
#region Operators
#region UnaryOperators
/////////////////////////////////////////////////////////////////////////////////
internal Expr BindUnaryOperation(
CSharpUnaryOperationBinder payload,
ArgumentObject[] arguments,
LocalVariableSymbol[] locals)
{
Debug.Assert(arguments.Length == 1);
OperatorKind op = GetOperatorKind(payload.Operation);
Expr arg1 = CreateArgumentEXPR(arguments[0], locals[0]);
arg1.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation));
if (op == OperatorKind.OP_TRUE || op == OperatorKind.OP_FALSE)
{
// For true and false, we try to convert to bool first. If that
// doesn't work, then we look for user defined operators.
Expr result = _binder.tryConvert(arg1, SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL));
if (result != null && op == OperatorKind.OP_FALSE)
{
// If we can convert to bool, we need to negate the thing if we're looking for false.
result = _binder.BindStandardUnaryOperator(OperatorKind.OP_LOGNOT, result);
}
return result
?? _binder.bindUDUnop(op == OperatorKind.OP_TRUE ? ExpressionKind.True : ExpressionKind.False, arg1)
// If the result is STILL null, then that means theres no implicit conversion to bool,
// and no user-defined operators for true and false. Just do a must convert to report
// the error.
?? _binder.mustConvert(arg1, SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL));
}
return _binder.BindStandardUnaryOperator(op, arg1);
}
#endregion
#region BinaryOperators
/////////////////////////////////////////////////////////////////////////////////
internal Expr BindBinaryOperation(
CSharpBinaryOperationBinder payload,
ArgumentObject[] arguments,
LocalVariableSymbol[] locals)
{
Debug.Assert(arguments.Length == 2);
ExpressionKind ek = Operators.GetExpressionKind(GetOperatorKind(payload.Operation, payload.IsLogicalOperation));
Expr arg1 = CreateArgumentEXPR(arguments[0], locals[0]);
Expr arg2 = CreateArgumentEXPR(arguments[1], locals[1]);
arg1.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation, payload.IsLogicalOperation));
arg2.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation, payload.IsLogicalOperation));
if (ek > ExpressionKind.MultiOffset)
{
ek = (ExpressionKind)(ek - ExpressionKind.MultiOffset);
}
return _binder.BindStandardBinop(ek, arg1, arg2);
}
#endregion
/////////////////////////////////////////////////////////////////////////////////
private static OperatorKind GetOperatorKind(ExpressionType p)
{
return GetOperatorKind(p, false);
}
private static OperatorKind GetOperatorKind(ExpressionType p, bool bIsLogical)
{
switch (p)
{
default:
Debug.Fail("Unknown operator: " + p);
throw Error.InternalCompilerError();
// Binary Operators
case ExpressionType.Add:
return OperatorKind.OP_ADD;
case ExpressionType.Subtract:
return OperatorKind.OP_SUB;
case ExpressionType.Multiply:
return OperatorKind.OP_MUL;
case ExpressionType.Divide:
return OperatorKind.OP_DIV;
case ExpressionType.Modulo:
return OperatorKind.OP_MOD;
case ExpressionType.LeftShift:
return OperatorKind.OP_LSHIFT;
case ExpressionType.RightShift:
return OperatorKind.OP_RSHIFT;
case ExpressionType.LessThan:
return OperatorKind.OP_LT;
case ExpressionType.GreaterThan:
return OperatorKind.OP_GT;
case ExpressionType.LessThanOrEqual:
return OperatorKind.OP_LE;
case ExpressionType.GreaterThanOrEqual:
return OperatorKind.OP_GE;
case ExpressionType.Equal:
return OperatorKind.OP_EQ;
case ExpressionType.NotEqual:
return OperatorKind.OP_NEQ;
case ExpressionType.And:
return bIsLogical ? OperatorKind.OP_LOGAND : OperatorKind.OP_BITAND;
case ExpressionType.ExclusiveOr:
return OperatorKind.OP_BITXOR;
case ExpressionType.Or:
return bIsLogical ? OperatorKind.OP_LOGOR : OperatorKind.OP_BITOR;
// Binary in place operators.
case ExpressionType.AddAssign:
return OperatorKind.OP_ADDEQ;
case ExpressionType.SubtractAssign:
return OperatorKind.OP_SUBEQ;
case ExpressionType.MultiplyAssign:
return OperatorKind.OP_MULEQ;
case ExpressionType.DivideAssign:
return OperatorKind.OP_DIVEQ;
case ExpressionType.ModuloAssign:
return OperatorKind.OP_MODEQ;
case ExpressionType.AndAssign:
return OperatorKind.OP_ANDEQ;
case ExpressionType.ExclusiveOrAssign:
return OperatorKind.OP_XOREQ;
case ExpressionType.OrAssign:
return OperatorKind.OP_OREQ;
case ExpressionType.LeftShiftAssign:
return OperatorKind.OP_LSHIFTEQ;
case ExpressionType.RightShiftAssign:
return OperatorKind.OP_RSHIFTEQ;
// Unary Operators
case ExpressionType.Negate:
return OperatorKind.OP_NEG;
case ExpressionType.UnaryPlus:
return OperatorKind.OP_UPLUS;
case ExpressionType.Not:
return OperatorKind.OP_LOGNOT;
case ExpressionType.OnesComplement:
return OperatorKind.OP_BITNOT;
case ExpressionType.IsTrue:
return OperatorKind.OP_TRUE;
case ExpressionType.IsFalse:
return OperatorKind.OP_FALSE;
// Increment/Decrement.
case ExpressionType.Increment:
return OperatorKind.OP_PREINC;
case ExpressionType.Decrement:
return OperatorKind.OP_PREDEC;
}
}
/////////////////////////////////////////////////////////////////////////////////
#endregion
#region Properties
/////////////////////////////////////////////////////////////////////////////////
internal Expr BindProperty(
ICSharpBinder payload,
ArgumentObject argument,
LocalVariableSymbol local,
Expr optionalIndexerArguments)
{
// If our argument is a static type, then we're calling a static property.
Expr callingObject = argument.Info.IsStaticType ?
ExprFactory.CreateClass(SymbolTable.GetCTypeFromType(argument.Value as Type)) :
CreateLocal(argument.Type, argument.Info.IsOut, local);
if (!argument.Info.UseCompileTimeType && argument.Value == null)
{
throw Error.NullReferenceOnMemberException();
}
// If our argument is a struct type, unbox it.
if (argument.Type.IsValueType && callingObject is ExprCast)
{
// If we have a struct type, unbox it.
callingObject.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME;
}
string name = payload.Name;
BindingFlag bindFlags = payload.BindingFlags;
MemberLookup mem = new MemberLookup();
SymWithType swt = SymbolTable.LookupMember(name, callingObject, _binder.Context.ContextForMemberLookup, 0, mem, false, false);
if (swt == null)
{
if (optionalIndexerArguments != null)
{
int numIndexArguments = ExpressionIterator.Count(optionalIndexerArguments);
// We could have an array access here. See if its just an array.
Type type = argument.Type;
Debug.Assert(type != typeof(string));
if (type.IsArray)
{
if (type.IsArray && type.GetArrayRank() != numIndexArguments)
{
throw ErrorHandling.Error(ErrorCode.ERR_BadIndexCount, type.GetArrayRank());
}
Debug.Assert(callingObject.Type is ArrayType);
return CreateArray(callingObject, optionalIndexerArguments);
}
}
throw mem.ReportErrors();
}
switch (swt.Sym.getKind())
{
case SYMKIND.SK_MethodSymbol:
throw Error.BindPropertyFailedMethodGroup(name);
case SYMKIND.SK_PropertySymbol:
if (swt.Sym is IndexerSymbol)
{
return CreateIndexer(swt, callingObject, optionalIndexerArguments, bindFlags);
}
else
{
// Properties can be LValues.
callingObject.Flags |= EXPRFLAG.EXF_LVALUE;
return CreateProperty(swt, callingObject, payload.BindingFlags);
}
case SYMKIND.SK_FieldSymbol:
return CreateField(swt, callingObject);
case SYMKIND.SK_EventSymbol:
throw Error.BindPropertyFailedEvent(name);
default:
Debug.Fail("Unexpected type returned from lookup");
throw Error.InternalCompilerError();
}
}
#endregion
#region Casts
/////////////////////////////////////////////////////////////////////////////////
internal Expr BindImplicitConversion(
ArgumentObject[] arguments,
Type returnType,
LocalVariableSymbol[] locals,
bool bIsArrayCreationConversion)
{
Debug.Assert(arguments.Length == 1);
// Load the conversions on the target.
SymbolTable.AddConversionsForType(returnType);
Expr argument = CreateArgumentEXPR(arguments[0], locals[0]);
CType destinationType = SymbolTable.GetCTypeFromType(returnType);
if (bIsArrayCreationConversion)
{
// If we are converting for an array index, we want to convert to int, uint,
// long, or ulong, depending on what the argument will allow. However, since
// the compiler had to pick a particular type for the return value when it
// made the callsite, we need to make sure that we ultimately return a type
// of that value. So we "mustConvert" to the best type that chooseArrayIndexType
// can find, and then we cast the result of that to the returnType, which is
// incidentally Int32 in the existing compiler. For that cast, we do not consider
// user defined conversions (since the convert is guaranteed to return one of
// the primitive types), and we check for overflow since we don't want truncation.
CType pDestType = _binder.ChooseArrayIndexType(argument);
return _binder.mustCast(
_binder.mustConvert(argument, pDestType),
destinationType,
CONVERTTYPE.CHECKOVERFLOW | CONVERTTYPE.NOUDC);
}
return _binder.mustConvert(argument, destinationType);
}
/////////////////////////////////////////////////////////////////////////////////
internal Expr BindExplicitConversion(ArgumentObject[] arguments, Type returnType, LocalVariableSymbol[] locals)
{
Debug.Assert(arguments.Length == 1);
// Load the conversions on the target.
SymbolTable.AddConversionsForType(returnType);
Expr argument = CreateArgumentEXPR(arguments[0], locals[0]);
CType destinationType = SymbolTable.GetCTypeFromType(returnType);
return _binder.mustCast(argument, destinationType);
}
#endregion
#region Assignments
/////////////////////////////////////////////////////////////////////////////////
internal Expr BindAssignment(
ICSharpBinder payload,
ArgumentObject[] arguments,
LocalVariableSymbol[] locals)
{
Debug.Assert(arguments.Length >= 2);
Debug.Assert(arguments.All(a => a.Type != null));
string name = payload.Name;
// Find the lhs and rhs.
Expr indexerArguments;
bool bIsCompound;
CSharpSetIndexBinder setIndexBinder = payload as CSharpSetIndexBinder;
if (setIndexBinder != null)
{
// Get the list of indexer arguments - this is the list of arguments minus the last one.
indexerArguments = CreateArgumentListEXPR(arguments, locals, 1, arguments.Length - 1);
bIsCompound = setIndexBinder.IsCompoundAssignment;
}
else
{
indexerArguments = null;
bIsCompound = (payload as CSharpSetMemberBinder).IsCompoundAssignment;
}
SymbolTable.PopulateSymbolTableWithName(name, null, arguments[0].Type);
Expr lhs = BindProperty(payload, arguments[0], locals[0], indexerArguments);
int indexOfLast = arguments.Length - 1;
Expr rhs = CreateArgumentEXPR(arguments[indexOfLast], locals[indexOfLast]);
return _binder.BindAssignment(lhs, rhs, bIsCompound);
}
#endregion
#region Events
/////////////////////////////////////////////////////////////////////////////////
internal Expr BindIsEvent(
CSharpIsEventBinder binder,
ArgumentObject[] arguments,
LocalVariableSymbol[] locals)
{
// The IsEvent binder will never be called without an instance object. This
// is because the compiler only gen's this code for dynamic dots.
Expr callingObject = CreateLocal(arguments[0].Type, false, locals[0]);
MemberLookup mem = new MemberLookup();
CType boolType = SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL);
bool result = false;
if (arguments[0].Value == null)
{
throw Error.NullReferenceOnMemberException();
}
SymWithType swt = SymbolTable.LookupMember(
binder.Name,
callingObject,
_binder.Context.ContextForMemberLookup,
0,
mem,
false,
false);
if (swt != null)
{
// If lookup returns an actual event, then this is an event.
if (swt.Sym.getKind() == SYMKIND.SK_EventSymbol)
{
result = true;
}
// If lookup returns the backing field of a field-like event, then
// this is an event. This is due to the Dev10 design change around
// the binding of +=, and the fact that the "IsEvent" binding question
// is only ever asked about the LHS of a += or -=.
else if (swt.Sym is FieldSymbol field && field.isEvent)
{
result = true;
}
}
return ExprFactory.CreateConstant(boolType, ConstVal.Get(result));
}
#endregion
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
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 License
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using JsonFx.IO;
using JsonFx.Markup;
using JsonFx.Serialization;
using JsonFx.Utils;
#if SILVERLIGHT
using CanonicalList=System.Collections.Generic.Dictionary<JsonFx.Serialization.DataName, JsonFx.Serialization.Token<JsonFx.Markup.MarkupTokenType>>;
#else
using CanonicalList=System.Collections.Generic.SortedList<JsonFx.Serialization.DataName, JsonFx.Serialization.Token<JsonFx.Markup.MarkupTokenType>>;
#endif
namespace JsonFx.Html
{
/// <summary>
/// Outputs markup text from an input stream of tokens
/// </summary>
public class HtmlFormatter : ITextFormatter<MarkupTokenType>
{
#region EmptyAttributeType
public enum EmptyAttributeType
{
/// <summary>
/// HTML-style empty attributes do not emit a quoted string
/// </summary>
/// <remarks>
/// http://www.w3.org/TR/html5/syntax.html#attributes-0
/// </remarks>
Html,
/// <summary>
/// XHTML-style empty attributes repeat the attribute name as its value
/// </summary>
/// <remarks>
/// http://www.w3.org/TR/xhtml-media-types/#C_10
/// http://www.w3.org/TR/xhtml1/#C_10
/// http://www.w3.org/TR/html5/the-xhtml-syntax.html
/// </remarks>
Xhtml,
/// <summary>
/// XML-style empty attributes emit an empty quoted string
/// </summary>
/// <remarks>
/// http://www.w3.org/TR/xml/#sec-starttags
/// </remarks>
Xml
}
#endregion EmptyAttributeType
#region Constants
private const string ErrorUnexpectedToken = "Unexpected token ({0})";
#endregion Constants
#region Fields
private readonly DataWriterSettings Settings;
private readonly PrefixScopeChain ScopeChain = new PrefixScopeChain();
private bool canonicalForm;
private EmptyAttributeType emptyAttributes;
private bool encodeNonAscii;
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="settings"></param>
public HtmlFormatter(DataWriterSettings settings)
{
if (settings == null)
{
throw new ArgumentNullException("settings");
}
this.Settings = settings;
}
#endregion Init
#region Properties
/// <summary>
/// Gets and sets a value indicating if should emit canonical form
/// </summary>
/// <remarks>
/// http://www.w3.org/TR/xml-c14n
/// </remarks>
public bool CanonicalForm
{
get { return this.canonicalForm; }
set { this.canonicalForm = value; }
}
/// <summary>
/// Gets and sets a value indicating how should emit empty attributes
/// </summary>
public EmptyAttributeType EmptyAttributes
{
get { return this.emptyAttributes; }
set { this.emptyAttributes = value; }
}
/// <summary>
/// Gets and sets a value indicating if should encode text chars above the ASCII range
/// </summary>
/// <remarks>
/// This option can help when the output is being embedded within an unknown encoding
/// </remarks>
public bool EncodeNonAscii
{
get { return this.encodeNonAscii; }
set { this.encodeNonAscii = value; }
}
#endregion Properties
#region Scope Methods
/// <summary>
/// Resets the internal stack of elements
/// </summary>
public void ResetScopeChain()
{
this.ScopeChain.Clear();
}
#endregion Scope Methods
#region ITextFormatter<T> Methods
/// <summary>
/// Formats the token sequence as a string
/// </summary>
/// <param name="tokens"></param>
public string Format(IEnumerable<Token<MarkupTokenType>> tokens)
{
using (StringWriter writer = new StringWriter())
{
this.Format(tokens, writer);
return writer.GetStringBuilder().ToString();
}
}
/// <summary>
/// Formats the token sequence to the writer
/// </summary>
/// <param name="writer"></param>
/// <param name="tokens"></param>
public void Format(IEnumerable<Token<MarkupTokenType>> tokens, TextWriter writer)
{
if (tokens == null)
{
throw new ArgumentNullException("tokens");
}
IStream<Token<MarkupTokenType>> stream = Stream<Token<MarkupTokenType>>.Create(tokens);
PrefixScopeChain.Scope scope = null;
while (!stream.IsCompleted)
{
Token<MarkupTokenType> token = stream.Peek();
switch (token.TokenType)
{
case MarkupTokenType.ElementBegin:
case MarkupTokenType.ElementVoid:
{
DataName tagName = token.Name;
MarkupTokenType tagType = token.TokenType;
stream.Pop();
token = stream.Peek();
scope = new PrefixScopeChain.Scope();
if (this.ScopeChain.ContainsNamespace(tagName.NamespaceUri) ||
(String.IsNullOrEmpty(tagName.NamespaceUri) && !this.ScopeChain.ContainsPrefix(String.Empty)))
{
string prefix = this.ScopeChain.GetPrefix(tagName.NamespaceUri, false);
scope.TagName = new DataName(tagName.LocalName, prefix, tagName.NamespaceUri);
}
else
{
scope[tagName.Prefix] = tagName.NamespaceUri;
scope.TagName = tagName;
}
this.ScopeChain.Push(scope);
IDictionary<DataName, Token<MarkupTokenType>> attributes = null;
while (!stream.IsCompleted && token.TokenType == MarkupTokenType.Attribute)
{
if (attributes == null)
{
attributes = this.canonicalForm ?
(IDictionary<DataName, Token<MarkupTokenType>>)new CanonicalList() :
(IDictionary<DataName, Token<MarkupTokenType>>)new Dictionary<DataName, Token<MarkupTokenType>>();
}
DataName attrName = token.Name;
string prefix = this.ScopeChain.EnsurePrefix(attrName.Prefix, attrName.NamespaceUri);
if (prefix != null)
{
if (prefix != attrName.Prefix)
{
attrName = new DataName(attrName.LocalName, prefix, attrName.NamespaceUri, true);
}
if (!this.ScopeChain.ContainsNamespace(attrName.NamespaceUri) &&
(!String.IsNullOrEmpty(attrName.NamespaceUri) || this.ScopeChain.ContainsPrefix(String.Empty)))
{
scope[prefix] = attrName.NamespaceUri;
}
}
stream.Pop();
token = stream.Peek();
attributes[attrName] = token ?? MarkupGrammar.TokenNone;
stream.Pop();
token = stream.Peek();
}
this.WriteTag(writer, tagType, tagName, attributes, scope);
scope = null;
break;
}
case MarkupTokenType.ElementEnd:
{
if (this.ScopeChain.HasScope)
{
this.WriteTag(writer, MarkupTokenType.ElementEnd, this.ScopeChain.Peek().TagName, null, null);
this.ScopeChain.Pop();
}
else
{
// TODO: decide if this is should throw an exception
}
stream.Pop();
token = stream.Peek();
break;
}
case MarkupTokenType.Primitive:
{
ITextFormattable<MarkupTokenType> formattable = token.Value as ITextFormattable<MarkupTokenType>;
if (formattable != null)
{
formattable.Format(this, writer);
}
else
{
HtmlFormatter.HtmlEncode(writer, token.ValueAsString(), this.encodeNonAscii, this.canonicalForm);
}
stream.Pop();
token = stream.Peek();
break;
}
default:
{
throw new TokenException<MarkupTokenType>(
token,
String.Format(ErrorUnexpectedToken, token.TokenType));
}
}
}
}
#endregion ITextFormatter<T> Methods
#region Write Methods
private void WriteTag(
TextWriter writer,
MarkupTokenType type,
DataName tagName,
IDictionary<DataName, Token<MarkupTokenType>> attributes,
PrefixScopeChain.Scope prefixDeclarations)
{
if (String.IsNullOrEmpty(tagName.LocalName))
{
// represents a document fragment
return;
}
string tagPrefix = this.ScopeChain.EnsurePrefix(tagName.Prefix, tagName.NamespaceUri) ?? tagName.Prefix;
// "<"
writer.Write(MarkupGrammar.OperatorElementBegin);
if (type == MarkupTokenType.ElementEnd)
{
// "/"
writer.Write(MarkupGrammar.OperatorElementClose);
}
if (!String.IsNullOrEmpty(tagPrefix))
{
// "prefix:"
this.WriteLocalName(writer, tagPrefix);
writer.Write(MarkupGrammar.OperatorPrefixDelim);
}
// "local-name"
this.WriteLocalName(writer, tagName.LocalName);
// emit all namespaces first, sorted by prefix
if (prefixDeclarations != null)
{
foreach (var declaration in prefixDeclarations)
{
this.WriteXmlns(writer, declaration.Key, declaration.Value);
}
}
if (attributes != null)
{
foreach (var attribute in attributes)
{
// Not sure if this is correct: http://stackoverflow.com/questions/3312390
// "The namespace name for an unprefixed attribute name always has no value"
// "The attribute value in a default namespace declaration MAY be empty.
// This has the same effect, within the scope of the declaration, of there being no default namespace."
// http://www.w3.org/TR/xml-names/#defaulting
string attrPrefix = this.ScopeChain.EnsurePrefix(attribute.Key.Prefix, attribute.Key.NamespaceUri) ?? attribute.Key.Prefix;
this.WriteAttribute(writer, attrPrefix, attribute.Key.LocalName, attribute.Value);
}
}
if (!this.canonicalForm &&
type == MarkupTokenType.ElementVoid)
{
// " /"
writer.Write(MarkupGrammar.OperatorValueDelim);
writer.Write(MarkupGrammar.OperatorElementClose);
}
// ">"
writer.Write(MarkupGrammar.OperatorElementEnd);
if (this.canonicalForm &&
type == MarkupTokenType.ElementVoid)
{
// http://www.w3.org/TR/xml-c14n#Terminology
this.WriteTag(writer, MarkupTokenType.ElementEnd, tagName, null, null);
}
}
private void WriteXmlns(TextWriter writer, string prefix, string namespaceUri)
{
// " xmlns"
writer.Write(MarkupGrammar.OperatorValueDelim);
this.WriteLocalName(writer, "xmlns");
if (!String.IsNullOrEmpty(prefix))
{
// ":prefix"
writer.Write(MarkupGrammar.OperatorPrefixDelim);
this.WriteLocalName(writer, prefix);
}
// ="value"
writer.Write(MarkupGrammar.OperatorPairDelim);
writer.Write(MarkupGrammar.OperatorStringDelim);
HtmlFormatter.HtmlAttributeEncode(writer, namespaceUri, this.encodeNonAscii, this.canonicalForm);
writer.Write(MarkupGrammar.OperatorStringDelim);
}
private void WriteAttribute(TextWriter writer, string prefix, string localName, Token<MarkupTokenType> value)
{
// " "
writer.Write(MarkupGrammar.OperatorValueDelim);
if (!String.IsNullOrEmpty(prefix))
{
// "prefix:"
this.WriteLocalName(writer, prefix);
writer.Write(MarkupGrammar.OperatorPrefixDelim);
}
// local-name
this.WriteLocalName(writer, localName);
ITextFormattable<MarkupTokenType> formattable = value.Value as ITextFormattable<MarkupTokenType>;
string attrValue = (formattable == null) ? value.ValueAsString() : null;
if ((formattable == null) &&
String.IsNullOrEmpty(attrValue))
{
switch (this.EmptyAttributes)
{
case EmptyAttributeType.Html:
{
return;
}
case EmptyAttributeType.Xhtml:
{
attrValue = localName;
break;
}
case EmptyAttributeType.Xml:
{
break;
}
}
}
// ="value"
writer.Write(MarkupGrammar.OperatorPairDelim);
writer.Write(MarkupGrammar.OperatorStringDelim);
switch (value.TokenType)
{
case MarkupTokenType.Primitive:
{
if (formattable != null)
{
formattable.Format(this, writer);
}
else
{
HtmlFormatter.HtmlAttributeEncode(writer, attrValue, this.encodeNonAscii, this.canonicalForm);
}
break;
}
default:
{
throw new TokenException<MarkupTokenType>(
value,
String.Format(HtmlFormatter.ErrorUnexpectedToken, value));
}
}
writer.Write(MarkupGrammar.OperatorStringDelim);
}
/// <summary>
/// Emits a valid XML local-name (i.e. encodes invalid chars including ':')
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <remarks>
/// Explicitly escaping ':' to maintain compatibility with XML Namespaces.
/// From XML 1.0, 5th ed. http://www.w3.org/TR/xml/#sec-common-syn
/// Name = NameStartChar (NameChar)*
/// NameStartChar = ":"
/// | [A-Z]
/// | "_"
/// | [a-z]
/// | [#xC0-#xD6]
/// | [#xD8-#xF6]
/// | [#xF8-#x2FF]
/// | [#x370-#x37D]
/// | [#x37F-#x1FFF]
/// | [#x200C-#x200D]
/// | [#x2070-#x218F]
/// | [#x2C00-#x2FEF]
/// | [#x3001-#xD7FF]
/// | [#xF900-#xFDCF]
/// | [#xFDF0-#xFFFD]
/// | [#x10000-#xEFFFF]
/// NameChar = NameStartChar
/// | "-"
/// | "."
/// | [0-9]
/// | #xB7
/// | [#x0300-#x036F]
/// | [#x203F-#x2040]
/// </remarks>
private void WriteLocalName(TextWriter writer, string value)
{
int start = 0,
length = value.Length;
for (int i=start; i<length; i++)
{
char ch = value[i];
if ((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch == '_') ||
(ch >= '\u00C0' && ch <= '\u00D6') ||
(ch >= '\u00D8' && ch <= '\u00F6') ||
(ch >= '\u00F8' && ch <= '\u02FF') ||
(ch >= '\u0370' && ch <= '\u037D') ||
(ch >= '\u037F' && ch <= '\u1FFF') ||
(ch >= '\u200C' && ch <= '\u200D') ||
(ch >= '\u2070' && ch <= '\u218F') ||
(ch >= '\u2C00' && ch <= '\u2FEF') ||
(ch >= '\u3001' && ch <= '\uD7FF') ||
(ch >= '\uF900' && ch <= '\uFDCF') ||
(ch >= '\uFDF0' && ch <= '\uFFFD'))
{
// purposefully leaving out ':' to implement namespace prefixes
// and cannot represent [#x10000-#xEFFFF] as single char so this will incorrectly escape
continue;
}
if ((i > 0) &&
((ch >= '0' && ch <= '9') ||
(ch == '-') ||
(ch == '.') ||
(ch == '\u00B7') ||
(ch >= '\u0300' && ch <= '\u036F') ||
(ch >= '\u203F' && ch <= '\u2040')))
{
// these chars are only valid after initial char
continue;
}
if (i > start)
{
// copy any leading unescaped chunk
writer.Write(value.Substring(start, i-start));
}
start = i+1;
// use XmlSerializer-hex-style encoding of UTF-16
writer.Write("_x");
writer.Write(CharUtility.ConvertToUtf32(value, i).ToString("X4"));
writer.Write("_");
}
if (length > start)
{
// copy any trailing unescaped chunk
writer.Write(value.Substring(start, length-start));
}
}
/// <summary>
/// Emits valid XML character data
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <remarks>
/// From XML 1.0, 5th ed. http://www.w3.org/TR/xml/#syntax
/// CharData is defined as all chars except less-than ('<'), ampersand ('&'), the sequence "]]>", optionally encoding greater-than ('>').
///
/// Rather than detect "]]>", this simply encodes all '>'.
/// From XML 1.0, 5th ed. http://www.w3.org/TR/xml/#sec-line-ends
/// "the XML processor must behave as if it normalized all line breaks in external parsed entities (including the document entity) on input, before parsing"
/// Therefore, this encodes all CR ('\r') chars to preserve them in the final output.
/// </remarks>
public static void HtmlEncode(TextWriter writer, string value)
{
HtmlFormatter.HtmlEncode(writer, value, false, false);
}
/// <summary>
/// Emits valid XML character data
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="encodeNonAscii">encodes all non-ASCII chars</param>
public static void HtmlEncode(TextWriter writer, string value, bool encodeNonAscii)
{
HtmlFormatter.HtmlEncode(writer, value, encodeNonAscii, false);
}
private static void HtmlEncode(TextWriter writer, string value, bool encodeNonAscii, bool canonicalForm)
{
int start = 0,
length = value.Length;
for (int i=start; i<length; i++)
{
char ch = value[i];
string entity;
switch (ch)
{
case '<':
{
entity = "<";
break;
}
case '>':
{
entity = ">";
break;
}
case '&':
{
entity = "&";
break;
}
case '\r':
{
if (!canonicalForm)
{
continue;
}
// Line breaks normalized to '\n'
// http://www.w3.org/TR/xml-c14n#Terminology
entity = String.Empty;
break;
}
default:
{
if (((ch < ' ') && (ch != '\n') && (ch != '\t')) ||
(encodeNonAscii && (ch >= 0x7F)) ||
((ch >= 0x7F) && (ch <= 0x84)) ||
((ch >= 0x86) && (ch <= 0x9F)) ||
((ch >= 0xFDD0) && (ch <= 0xFDEF)))
{
// encode all control chars except CRLF/Tab: http://www.w3.org/TR/xml/#charsets
int utf16 = CharUtility.ConvertToUtf32(value, i);
entity = String.Concat("&#x", utf16.ToString("X", CultureInfo.InvariantCulture), ';');
break;
}
continue;
}
}
if (i > start)
{
// copy any leading unescaped chunk
writer.Write(value.Substring(start, i-start));
}
start = i+1;
// emit XML entity
writer.Write(entity);
}
if (length > start)
{
// copy any trailing unescaped chunk
writer.Write(value.Substring(start, length-start));
}
}
/// <summary>
/// Emits valid XML attribute character data
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <remarks>
/// From XML 1.0, 5th ed. http://www.w3.org/TR/xml/#syntax
/// CharData is defined as all chars except less-than ('<'), ampersand ('&'), the sequence "]]>", optionally encoding greater-than ('>').
/// Attributes should additionally encode double-quote ('"') and single-quote ('\'')
/// Rather than detect "]]>", this simply encodes all '>'.
/// </remarks>
public static void HtmlAttributeEncode(TextWriter writer, string value)
{
HtmlFormatter.HtmlAttributeEncode(writer, value, false, false);
}
/// <summary>
/// Emits valid XML attribute character data
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="encodeNonAscii">encodes all non-ASCII chars</param>
public static void HtmlAttributeEncode(TextWriter writer, string value, bool encodeNonAscii)
{
HtmlFormatter.HtmlAttributeEncode(writer, value, encodeNonAscii, false);
}
private static void HtmlAttributeEncode(TextWriter writer, string value, bool encodeNonAscii, bool canonicalForm)
{
if (String.IsNullOrEmpty(value))
{
return;
}
int start = 0,
length = value.Length;
for (int i=start; i<length; i++)
{
char ch = value[i];
string entity;
switch (ch)
{
case '<':
{
entity = "<";
break;
}
case '>':
{
if (canonicalForm)
{
// http://www.w3.org/TR/xml-c14n#ProcessingModel
continue;
}
entity = ">";
break;
}
case '&':
{
entity = "&";
break;
}
case '"':
{
entity = """;
break;
}
case '\'':
{
if (!canonicalForm)
{
continue;
}
// http://www.w3.org/TR/xml-c14n#ProcessingModel
entity = "'";
break;
}
default:
{
if ((ch < ' ') ||
(encodeNonAscii && (ch >= 0x7F)) ||
((ch >= 0x7F) && (ch <= 0x84)) ||
((ch >= 0x86) && (ch <= 0x9F)) ||
((ch >= 0xFDD0) && (ch <= 0xFDEF)))
{
// encode all control chars: http://www.w3.org/TR/xml/#charsets
int utf16 = CharUtility.ConvertToUtf32(value, i);
entity = String.Concat("&#x", utf16.ToString("X", CultureInfo.InvariantCulture), ';');
break;
}
continue;
}
}
if (i > start)
{
// copy any leading unescaped chunk
writer.Write(value.Substring(start, i-start));
}
start = i+1;
// use XML named entity
writer.Write(entity);
}
if (length > start)
{
// copy any trailing unescaped chunk
writer.Write(value.Substring(start, length-start));
}
}
#endregion Write Methods
}
}
| |
#region License
/*
* Copyright 2002-2010 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.
*/
#endregion
#if NET_2_0
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing.Printing;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Configuration;
namespace Spring
{
/// <summary>
/// Allows to invoke parts of your code within the context of a certain PermissionSet.
/// </summary>
/// <remarks>
/// <para>
/// You may also use the static method <see cref="LoadDomainPolicyFromAppConfig"/> and
/// <see cref="LoadDomainPolicyFromUri"/> to load a <see cref="PolicyLevel"/> instance
/// yourself and apply it on your application domain using <see cref="AppDomain.SetAppDomainPolicy"/>. Note,
/// that you must set the policy *before* an assembly gets loaded to apply that policy on that assembly!
/// </para>
/// <para>
/// The policy file format is the one used by <see cref="SecurityManager.LoadPolicyLevelFromString"/>.
/// You get good examples from your %FrameworkDir%/CONFIG/ directory (e.g. 'web_mediumtrust.config').
/// </para>
/// </remarks>
/// <author>Erich Eichinger</author>
public class SecurityTemplate
{
/// <summary>
/// The default full trust permission set name ("FullTrust")
/// </summary>
public static readonly string PERMISSIONSET_FULLTRUST = "FullTrust";
/// <summary>
/// The default no trust permission set name ("Nothing")
/// </summary>
public static readonly string PERMISSIONSET_NOTHING = "Nothing";
/// <summary>
/// The default medium trust permission set name ("MediumTrust")
/// </summary>
public static readonly string PERMISSIONSET_MEDIUMTRUST = "MediumTrust";
/// <summary>
/// The default low trust permission set name ("LowTrust")
/// </summary>
public static readonly string PERMISSIONSET_LOWTRUST = "LowTrust";
/// <summary>
/// The default asp.net permission set name ("ASP.NET")
/// </summary>
public static readonly string PERMISSIONSET_ASPNET = "ASP.Net";
private readonly PolicyLevel _domainPolicy;
// private readonly Dictionary<string, SecurityContext> securityContextCache = new Dictionary<string, SecurityContext>();
private bool throwOnUnknownPermissionSet = true;
/// <summary>
/// Avoid beforeFieldInit
/// </summary>
static SecurityTemplate()
{}
/// <summary>
/// Invoke the specified callback in a medium trusted context
/// </summary>
public static void MediumTrustInvoke( ThreadStart callback )
{
SecurityTemplate template = new SecurityTemplate(true);
template.PartialTrustInvoke(PERMISSIONSET_MEDIUMTRUST, callback);
}
/// <summary>
/// Access the domain <see cref="PolicyLevel"/> of this <see cref="SecurityTemplate"/> instance.
/// </summary>
public PolicyLevel DomainPolicy
{
get { return _domainPolicy; }
}
/// <summary>
/// Whether to throw an <see cref="ArgumentOutOfRangeException"/> in case
/// the permission set name is not found when invoking <see cref="PartialTrustInvoke(string,ThreadStart)"/>.
/// Defaults to <c>true</c>.
/// </summary>
public bool ThrowOnUnknownPermissionSet
{
get { return throwOnUnknownPermissionSet; }
set
{
throwOnUnknownPermissionSet = value;
// securityContextCache.Clear(); // clear cache
}
}
/// <summary>
/// Creates a new instance providing default "FullTrust", "Nothing", "MediumTrust" and "LowTrust" permissionsets
/// </summary>
/// <param name="allowUnmanagedCode">NCover requires unmangaged code permissions, set this flag <c>true</c> in this case.</param>
public SecurityTemplate(bool allowUnmanagedCode)
{
PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();
// NOTHING permissionset
if (null == pLevel.GetNamedPermissionSet(PERMISSIONSET_NOTHING) )
{
NamedPermissionSet noPermissionSet = new NamedPermissionSet(PERMISSIONSET_NOTHING, PermissionState.None);
noPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.NoFlags));
pLevel.AddNamedPermissionSet(noPermissionSet);
}
// FULLTRUST permissionset
if (null == pLevel.GetNamedPermissionSet(PERMISSIONSET_FULLTRUST))
{
NamedPermissionSet fulltrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_FULLTRUST, PermissionState.Unrestricted);
pLevel.AddNamedPermissionSet(fulltrustPermissionSet);
}
// MEDIUMTRUST permissionset (corresponds to ASP.Net permission set in web_mediumtrust.config)
NamedPermissionSet mediumTrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_MEDIUMTRUST, PermissionState.None);
mediumTrustPermissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium));
mediumTrustPermissionSet.AddPermission(new DnsPermission(PermissionState.Unrestricted));
mediumTrustPermissionSet.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read,
"TEMP;TMP;USERNAME;OS;COMPUTERNAME"));
mediumTrustPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess,
AppDomain.CurrentDomain.BaseDirectory));
IsolatedStorageFilePermission isolatedStorageFilePermission = new IsolatedStorageFilePermission(PermissionState.None);
isolatedStorageFilePermission.UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser;
isolatedStorageFilePermission.UserQuota = 9223372036854775807;
mediumTrustPermissionSet.AddPermission(isolatedStorageFilePermission);
mediumTrustPermissionSet.AddPermission(new PrintingPermission(PrintingPermissionLevel.DefaultPrinting));
SecurityPermissionFlag securityPermissionFlag = SecurityPermissionFlag.Assertion | SecurityPermissionFlag.Execution |
SecurityPermissionFlag.ControlThread | SecurityPermissionFlag.ControlPrincipal |
SecurityPermissionFlag.RemotingConfiguration;
if (allowUnmanagedCode)
{
securityPermissionFlag |= SecurityPermissionFlag.UnmanagedCode;
}
mediumTrustPermissionSet.AddPermission(new SecurityPermission(securityPermissionFlag));
#if NET_2_0
mediumTrustPermissionSet.AddPermission(new System.Net.Mail.SmtpPermission(System.Net.Mail.SmtpAccess.Connect));
#endif
mediumTrustPermissionSet.AddPermission(new SqlClientPermission(PermissionState.Unrestricted));
mediumTrustPermissionSet.AddPermission(new WebPermission());
pLevel.AddNamedPermissionSet(mediumTrustPermissionSet);
// LOWTRUST permissionset (corresponds to ASP.Net permission set in web_mediumtrust.config)
NamedPermissionSet lowTrustPermissionSet = new NamedPermissionSet(PERMISSIONSET_LOWTRUST, PermissionState.None);
lowTrustPermissionSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Low));
lowTrustPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read|FileIOPermissionAccess.PathDiscovery,
AppDomain.CurrentDomain.BaseDirectory));
IsolatedStorageFilePermission isolatedStorageFilePermissionLow = new IsolatedStorageFilePermission(PermissionState.None);
isolatedStorageFilePermissionLow.UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser;
isolatedStorageFilePermissionLow.UserQuota = 1048576;
lowTrustPermissionSet.AddPermission(isolatedStorageFilePermissionLow);
SecurityPermissionFlag securityPermissionFlagLow = SecurityPermissionFlag.Execution;
if (allowUnmanagedCode)
{
securityPermissionFlagLow |= SecurityPermissionFlag.UnmanagedCode;
}
lowTrustPermissionSet.AddPermission(new SecurityPermission(securityPermissionFlagLow));
pLevel.AddNamedPermissionSet(lowTrustPermissionSet);
// UnionCodeGroup rootCodeGroup = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(noPermissionSet, PolicyStatementAttribute.Nothing));
// pLevel.RootCodeGroup = rootCodeGroup;
_domainPolicy = pLevel;
}
/// <summary>
/// Loads domain policy from specified file
/// </summary>
/// <param name="securityConfigurationFile"></param>
public SecurityTemplate(FileInfo securityConfigurationFile)
{
string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
_domainPolicy = LoadDomainPolicyFromUri(new Uri(securityConfigurationFile.FullName), appDirectory, string.Empty);
}
/// <summary>
/// Create a security tool from the specified domainPolicy
/// </summary>
public SecurityTemplate(PolicyLevel domainPolicy)
{
this._domainPolicy = domainPolicy;
}
/// <summary>
/// Invokes the given callback using the policy's default
/// partial trust permissionset ("ASP.Net" <see cref="PERMISSIONSET_ASPNET"/>).
/// </summary>
// [SecurityTreatAsSafe, SecurityCritical]
public void PartialTrustInvoke(ThreadStart callback)
{
string defaultPermissionSetName = PERMISSIONSET_MEDIUMTRUST;
if (null != GetNamedPermissionSet(PERMISSIONSET_ASPNET))
{
defaultPermissionSetName = PERMISSIONSET_ASPNET;
}
PartialTrustInvoke(defaultPermissionSetName, callback);
}
/// <summary>
/// Invokes the given callback using the specified permissionset.
/// </summary>
// [SecurityTreatAsSafe, SecurityCritical]
public void PartialTrustInvoke(string permissionSetName, ThreadStart callback)
{
PermissionSet ps = null;
ps = GetNamedPermissionSet(permissionSetName);
if (ps == null && throwOnUnknownPermissionSet)
{
throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
string.Format("unknown PermissionSet name '{0}'",
permissionSetName));
}
if (!IsFullTrust(ps))
{
ps.PermitOnly();
callback();
CodeAccessPermission.RevertPermitOnly();
}
else
{
callback();
}
}
private PermissionSet GetNamedPermissionSet(string name)
{
if (_domainPolicy != null)
{
return _domainPolicy.GetNamedPermissionSet(name);
}
return null;
}
#if !MONO
/// <summary>
/// Loads the policy configuration from app.config configuration section
/// </summary>
/// <example>
/// Configuration is identical to web.config:
/// <code>
/// <configuration>
/// <system.web>
/// <securityPolicy>
/// <trustLevel name="Full" policyFile="internal"/>
/// <trustLevel name="High" policyFile="web_hightrust.config"/>
/// <trustLevel name="Medium" policyFile="web_mediumtrust.config"/>
/// <trustLevel name="Low" policyFile="web_lowtrust.config"/>
/// <trustLevel name="Minimal" policyFile="web_minimaltrust.config"/>
/// </securityPolicy>
/// <trust level="Medium" originUrl=""/>
/// </system.web>
/// </configuration>
/// </code>
/// </example>
/// <param name="throwOnError"></param>
/// <returns></returns>
public static PolicyLevel LoadDomainPolicyFromAppConfig(bool throwOnError)
{
TrustSection trustSection = (TrustSection)ConfigurationManager.GetSection("system.web/trust");
SecurityPolicySection securityPolicySection = (SecurityPolicySection)ConfigurationManager.GetSection("system.web/securityPolicy");
if ((trustSection == null) || string.IsNullOrEmpty(trustSection.Level))
{
if (!throwOnError) return null;
throw new ConfigurationErrorsException("Configuration section <system.web/trust> not found ");
}
if (trustSection.Level == "Full")
{
return null;
}
if ((securityPolicySection == null) || (securityPolicySection.TrustLevels[trustSection.Level] == null))
{
if (!throwOnError) return null;
throw new ConfigurationErrorsException(string.Format("configuration <system.web/securityPolicy/trustLevel@name='{0}'> not found", trustSection.Level));
}
string policyFileExpanded = GetPolicyFilenameExpanded(securityPolicySection.TrustLevels[trustSection.Level]);
string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
PolicyLevel domainPolicy = LoadDomainPolicyFromUri(new Uri(policyFileExpanded), appDirectory, trustSection.OriginUrl);
return domainPolicy;
}
#endif
/// <summary>
/// Loads a policy from a file (<see cref="SecurityManager.LoadPolicyLevelFromFile"/>),
/// replacing placeholders
/// <list>
/// <item>$AppDir$, $AppDirUrl$ => <paramref name="appDirectory"/></item>
/// <item>$CodeGen$ => (TODO)</item>
/// <item>$OriginHost$ => <paramref name="originUrl"/></item>
/// <item>$Gac$ => the current machine's GAC path</item>
/// </list>
/// </summary>
/// <param name="policyFileLocation"></param>
/// <param name="originUrl"></param>
/// <param name="appDirectory"></param>
/// <returns></returns>
public static PolicyLevel LoadDomainPolicyFromUri(Uri policyFileLocation, string appDirectory, string originUrl)
{
bool foundGacToken = false;
PolicyLevel domainPolicy = CreatePolicyLevel(policyFileLocation, appDirectory, appDirectory, originUrl, out foundGacToken);
if (foundGacToken)
{
CodeGroup rootCodeGroup = domainPolicy.RootCodeGroup;
bool hasGacMembershipCondition = false;
foreach (CodeGroup childCodeGroup in rootCodeGroup.Children)
{
if (childCodeGroup.MembershipCondition is GacMembershipCondition)
{
hasGacMembershipCondition = true;
break;
}
}
if (!hasGacMembershipCondition && (rootCodeGroup is FirstMatchCodeGroup))
{
FirstMatchCodeGroup firstMatchCodeGroup = (FirstMatchCodeGroup)rootCodeGroup;
if ((firstMatchCodeGroup.MembershipCondition is AllMembershipCondition) && (firstMatchCodeGroup.PermissionSetName == PERMISSIONSET_NOTHING))
{
PermissionSet unrestrictedPermissionSet = new PermissionSet(PermissionState.Unrestricted);
CodeGroup gacGroup = new UnionCodeGroup(new GacMembershipCondition(), new PolicyStatement(unrestrictedPermissionSet));
CodeGroup rootGroup = new FirstMatchCodeGroup(rootCodeGroup.MembershipCondition, rootCodeGroup.PolicyStatement);
foreach (CodeGroup childGroup in rootCodeGroup.Children)
{
if (((childGroup is UnionCodeGroup) && (childGroup.MembershipCondition is UrlMembershipCondition)) && (childGroup.PolicyStatement.PermissionSet.IsUnrestricted() && (gacGroup != null)))
{
rootGroup.AddChild(gacGroup);
gacGroup = null;
}
rootGroup.AddChild(childGroup);
}
domainPolicy.RootCodeGroup = rootGroup;
}
}
}
return domainPolicy;
}
private static PolicyLevel CreatePolicyLevel(Uri configFile, string appDir, string binDir, string strOriginUrl, out bool foundGacToken)
{
WebClient webClient = new WebClient();
string strXmlPolicy = webClient.DownloadString(configFile);
appDir = FileUtil.RemoveTrailingDirectoryBackSlash(appDir);
binDir = FileUtil.RemoveTrailingDirectoryBackSlash(binDir);
strXmlPolicy = strXmlPolicy.Replace("$AppDir$", appDir).Replace("$AppDirUrl$", MakeFileUrl(appDir)).Replace("$CodeGen$", MakeFileUrl(binDir));
if (strOriginUrl == null)
{
strOriginUrl = string.Empty;
}
strXmlPolicy = strXmlPolicy.Replace("$OriginHost$", strOriginUrl);
if (strXmlPolicy.IndexOf("$Gac$", StringComparison.Ordinal) != -1)
{
string gacLocation = GetGacLocation();
if (gacLocation != null)
{
gacLocation = MakeFileUrl(gacLocation);
}
if (gacLocation == null)
{
gacLocation = string.Empty;
}
strXmlPolicy = strXmlPolicy.Replace("$Gac$", gacLocation);
foundGacToken = true;
}
else
{
foundGacToken = false;
}
return SecurityManager.LoadPolicyLevelFromString(strXmlPolicy, PolicyLevelType.AppDomain);
}
#if !MONO
private static string GetPolicyFilenameExpanded(TrustLevel trustLevel)
{
bool isRelative = true;
if (trustLevel.PolicyFile.Length > 1)
{
char ch = trustLevel.PolicyFile[1];
char ch2 = trustLevel.PolicyFile[0];
if (ch == ':')
{
isRelative = false;
}
else if ((ch2 == '\\') && (ch == '\\'))
{
isRelative = false;
}
}
if (isRelative)
{
string configurationElementFileSource = trustLevel.ElementInformation.Properties["policyFile"].Source;
string path = configurationElementFileSource.Substring(0, configurationElementFileSource.LastIndexOf('\\') + 1);
return path + trustLevel.PolicyFile;
}
return trustLevel.PolicyFile;
}
#endif
[DllImport("mscorwks.dll", CharSet = CharSet.Unicode)]
private static extern int GetCachePath(int dwCacheFlags, StringBuilder pwzCachePath, ref int pcchPath);
private static string GetGacLocation()
{
int capacity = 0x106;
StringBuilder pwzCachePath = new StringBuilder(capacity);
int pcchPath = capacity - 2;
int hRes = GetCachePath(2, pwzCachePath, ref pcchPath);
if (hRes < 0)
{
throw new HttpException("failed obtaining GAC path", hRes);
}
return pwzCachePath.ToString();
}
private static string MakeFileUrl(string path)
{
Uri uri = new Uri(path);
return uri.ToString();
}
private class FileUtil
{
internal static string RemoveTrailingDirectoryBackSlash(string path)
{
if (path == null)
{
return null;
}
int length = path.Length;
if ((length > 3) && (path[length - 1] == '\\'))
{
path = path.Substring(0, length - 1);
}
return path;
}
}
private static bool IsFullTrust(PermissionSet perms)
{
if (perms != null)
{
return perms.IsUnrestricted();
}
return true;
}
// [SecurityTreatAsSafe, SecurityCritical]
// private bool NeedPartialTrustInvoke(string permissionSetName)
// {
// if (_domainPolicy == null) return false;
//
// SecurityContext securityContext = null;
// if (!securityContextCache.ContainsKey(permissionSetName))
// {
// NamedPermissionSet permissionSet = _domainPolicy.GetNamedPermissionSet(permissionSetName);
// if (permissionSet == null && throwOnUnknownPermissionSet)
// {
// throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName, "Undefined permission set");
// }
// if (!IsFullTrust(permissionSet))
// {
// try
// {
// permissionSet.PermitOnly();
// securityContext = CaptureSecurityContextNoIdentityFlow();
// }
// finally
// {
// CodeAccessPermission.RevertPermitOnly();
// }
// }
// securityContextCache[permissionSetName] = securityContext;
// }
// else
// {
// securityContext = securityContextCache[permissionSetName];
// }
// return (securityContext != null);
// }
// [SecurityCritical]
// private static SecurityContext CaptureSecurityContextNoIdentityFlow()
// {
// if (SecurityContext.IsWindowsIdentityFlowSuppressed())
// {
// return SecurityContext.Capture();
// }
// using (SecurityContext.SuppressFlowWindowsIdentity())
// {
// return SecurityContext.Capture();
// }
// }
}
}
#endif
| |
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Breeze.Core {
public class EntityQuery {
private String _resourceName;
private BasePredicate _wherePredicate;
private OrderByClause _orderByClause;
private ExpandClause _expandClause;
private SelectClause _selectClause;
private int? _skipCount;
private int? _takeCount;
private bool? _inlineCountEnabled;
private Dictionary<String, Object> _parameters;
private Type _entityType;
static EntityQuery() {
// default implementations of pluggable static extension methods
EntityQuery.NeedsExecution = (qs, iq) => (qs != null && iq != null);
EntityQuery.ApplyCustomLogic = (eq, iq, type) => iq;
EntityQuery.ApplyExpand = (eq, iq, type) => iq;
EntityQuery.AfterExecution = (eq, iq, list) => list;
}
public EntityQuery() {
}
/**
* Materializes the serialized json representation of an EntityQuery.
* @param json The serialized json version of the EntityQuery.
*/
public EntityQuery(String json) {
if (json == null || json.Length == 0) {
return;
}
Dictionary<string, object> qmap;
try {
var dmap = JsonHelper.Deserialize(json);
qmap = (Dictionary<string, object>)dmap;
} catch (Exception) {
throw new Exception(
"This EntityQuery ctor requires a valid json string. The following is not json: "
+ json);
}
this._resourceName = GetMapValue<string>(qmap, "resourceName");
this._skipCount = GetMapInt(qmap, "skip");
this._takeCount = GetMapInt(qmap, "take");
this._wherePredicate = BasePredicate.PredicateFromMap(GetMapValue<Dictionary<string, object>>(qmap, "where"));
this._orderByClause = OrderByClause.From(GetMapValue<List<Object>>(qmap, "orderBy"));
this._selectClause = SelectClause.From(GetMapValue<List<Object>>(qmap, "select"));
this._expandClause = ExpandClause.From(GetMapValue<List<Object>>(qmap, "expand"));
this._parameters = GetMapValue<Dictionary<string, object>>(qmap, "parameters");
this._inlineCountEnabled = GetMapValue<bool?>(qmap, "inlineCount");
}
/**
* Copy constructor
* @param query
*/
public EntityQuery(EntityQuery query) {
this._resourceName = query._resourceName;
this._skipCount = query._skipCount;
this._takeCount = query._takeCount;
this._wherePredicate = query._wherePredicate;
this._orderByClause = query._orderByClause;
this._selectClause = query._selectClause;
this._expandClause = query._expandClause;
this._inlineCountEnabled = query._inlineCountEnabled;
this._parameters = query._parameters;
}
/**
* Return a new query based on this query with an additional where clause added.
* @param json Json representation of the where clause.
* @return A new EntityQuery.
*/
public EntityQuery Where(String json) {
var qmap = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
var pred = BasePredicate.PredicateFromMap(qmap);
return this.Where(pred);
}
private T GetMapValue<T>(IDictionary<string, object> map, string key) {
if (map.ContainsKey(key)) {
return (T)map[key];
} else {
return default(T);
}
}
private int? GetMapInt(IDictionary<string, object> map, string key) {
if (map.ContainsKey(key)) {
return Convert.ToInt32(map[key]);
} else {
return null;
}
}
/**
* Return a new query based on this query with an additional where clause added.
* @param predicate A Predicate representing the where clause to add.
* @return A new EntityQuery.
*/
public EntityQuery Where(BasePredicate predicate) {
EntityQuery eq = new EntityQuery(this);
if (eq._wherePredicate == null) {
eq._wherePredicate = predicate;
} else if (eq._wherePredicate.Operator == Operator.And) {
AndOrPredicate andOrPred = (AndOrPredicate)eq._wherePredicate;
var preds = new List<BasePredicate>(andOrPred.Predicates);
preds.Add(predicate);
eq._wherePredicate = new AndOrPredicate(Operator.And, preds);
} else {
eq._wherePredicate = new AndOrPredicate(Operator.And,
eq._wherePredicate, predicate);
}
return eq;
}
/**
* Return a new query based on this query with the specified orderBy clauses added.
* @param propertyPaths A varargs array of orderBy clauses ( each consisting of a property path and an optional sort direction).
* @return A new EntityQuery.
*/
public EntityQuery OrderBy(params String[] propertyPaths) {
return OrderBy(propertyPaths.ToList());
}
/**
* Return a new query based on this query with the specified orderBy clauses added.
* @param propertyPaths An List of orderBy clauses ( each consisting of a property path and an optional sort direction).
* @return A new EntityQuery.
*/
public EntityQuery OrderBy(List<String> propertyPaths) {
EntityQuery eq = new EntityQuery(this);
if (this._orderByClause == null) {
eq._orderByClause = new OrderByClause(propertyPaths);
} else {
var propPaths = this._orderByClause.PropertyPaths.ToList();
propPaths.AddRange(propertyPaths);
eq._orderByClause = new OrderByClause(propPaths);
}
return eq;
}
/**
* Return a new query based on this query with the specified expand clauses added.
* @param propertyPaths A varargs array of expand clauses ( each a dot delimited property path).
* @return A new EntityQuery.
*/
public EntityQuery Expand(params String[] propertyPaths) {
return Expand(propertyPaths.ToList());
}
/**
* Return a new query based on this query with the specified expand clauses added.
* @param propertyPaths A list of expand clauses (each a dot delimited property path).
* @return A new EntityQuery.
*/
public EntityQuery Expand(List<String> propertyPaths) {
EntityQuery eq = new EntityQuery(this);
if (this._expandClause == null) {
eq._expandClause = new ExpandClause(propertyPaths);
} else {
// think about checking if any prop paths are duped.
var propPaths = this._expandClause.PropertyPaths.ToList();
propPaths.AddRange(propertyPaths);
eq._expandClause = new ExpandClause(propPaths);
}
return eq;
}
// Impl of following functions is deferred to whatever Persistence framework is being used, i.e. EF vs NHibernate
/// <summary> Whether query string needs execution </summary>
public static Func<string, IQueryable, bool> NeedsExecution {
get;
set;
}
/// <summary> Apply logic to the IQueryable after the Where clause is applied, but before Order/Skip/Take/Select </summary>
public static Func<EntityQuery, IQueryable, Type, IQueryable> ApplyCustomLogic {
get;
set;
}
/// <summary> Apply expand clauses to the IQueryable after Order/Skip/Take/Select, but before execution </summary>
public static Func<EntityQuery, IQueryable, Type, IQueryable> ApplyExpand {
get;
set;
}
/// <summary> After the query was executed, post-process the resulting list and return the list </summary>
public static Func<EntityQuery, IQueryable, IList, IList> AfterExecution {
get;
set;
}
/**
* Return a new query based on this query with the specified select (projection) clauses added.
* @param propertyPaths A varargs array of select clauses (each a dot delimited property path).
* @return A new EntityQuery.
*/
public EntityQuery Select(params String[] propertyPaths) {
return Select(propertyPaths.ToList());
}
/**
* Return a new query based on this query with the specified select (projection) clauses added.
* @param propertyPaths A list of select clauses (each a dot delimited property path).
* @return A new EntityQuery.
*/
public EntityQuery Select(IEnumerable<String> propertyPaths) {
EntityQuery eq = new EntityQuery(this);
if (this._selectClause == null) {
eq._selectClause = new SelectClause(propertyPaths);
} else {
// think about checking if any prop paths are duped.
var propPaths = this._selectClause.PropertyPaths.ToList();
propPaths.AddRange(propertyPaths);
eq._selectClause = new SelectClause(propPaths);
}
return eq;
}
/**
* Return a new query based on this query that limits the results to the first n records.
* @param takeCount The number of records to take.
* @return A new EntityQuery
*/
public EntityQuery Take(int takeCount) {
EntityQuery eq = new EntityQuery(this);
eq._takeCount = takeCount;
return eq;
}
/**
* Return a new query based on this query that skips the first n records.
* @param skipCount The number of records to skip.
* @return A new EntityQuery
*/
public EntityQuery Skip(int skipCount) {
EntityQuery eq = new EntityQuery(this);
eq._skipCount = skipCount;
return eq;
}
/**
* Return a new query based on this query that either adds or removes the inline count capability.
* @param inlineCountEnabled Whether to enable inlineCount.
* @return A new EntityQuery
*/
public EntityQuery EnableInlineCount(bool inlineCountEnabled) {
EntityQuery eq = new EntityQuery(this);
eq._inlineCountEnabled = inlineCountEnabled;
return eq;
}
/**
* Return a new query based on this query with the specified resourceName
* @param resourceName The name of the url resource.
* @return A new EntityQuery
*/
public EntityQuery WithResourceName(String resourceName) {
EntityQuery eq = new EntityQuery(this);
eq._resourceName = resourceName;
return eq;
}
private List<String> ToStringList(Object src) {
if (src == null)
return null;
if (src is List<String>) {
return (List<String>)src;
} else if (src is String) {
var list = new List<String>();
list.Add(src as String);
return list;
}
throw new Exception("Unable to convert to a List<String>");
}
/**
* Validates that all of the clauses that make up this query are consistent with the
* specified EntityType.
* @param entityType A EntityType
*/
public void Validate(Type entityType) {
_entityType = entityType;
if (_wherePredicate != null) {
_wherePredicate.Validate(entityType);
}
if (_orderByClause != null) {
_orderByClause.Validate(entityType);
}
if (_selectClause != null) {
_selectClause.Validate(entityType);
}
}
/**
* Returns the EntityType that this query has been validated against. Not that this property
* will return null until the validate method has been called.
* @return The EntityType that this query has been validated against.
*/
public Type EntityType {
get { return _entityType; }
}
public String ResourceName {
get { return _resourceName; }
}
public BasePredicate WherePredicate {
get { return _wherePredicate; }
}
public OrderByClause OrderByClause {
get { return _orderByClause; }
}
public ExpandClause ExpandClause {
get { return _expandClause; }
}
public SelectClause SelectClause {
get { return _selectClause; }
}
public int? SkipCount {
get { return _skipCount; }
}
public int? TakeCount {
get { return _takeCount; }
}
public bool IsInlineCountEnabled {
get { return _inlineCountEnabled.HasValue && _inlineCountEnabled.Value; }
}
public IDictionary<string, object> GetParameters() {
return _parameters;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Evaluation;
using System.Linq;
using Microsoft.Build.Construction;
using System.Text;
using System.Xml;
namespace Microsoft.DotNet.Build.Tasks
{
public class UpdateVSConfigurations : BuildTask
{
public ITaskItem[] ProjectsToUpdate { get; set; }
public ITaskItem[] SolutionsToUpdate { get; set; }
private const string ConfigurationPropsFilename = "Configurations.props";
private static Regex s_configurationConditionRegex = new Regex(@"'\$\(Configuration\)\|\$\(Platform\)' ?== ?'(?<config>.*)'");
private static string[] s_configurationSuffixes = new [] { "Debug|AnyCPU", "Release|AnyCPU" };
public override bool Execute()
{
if (ProjectsToUpdate == null) ProjectsToUpdate = new ITaskItem[0];
if (SolutionsToUpdate == null) SolutionsToUpdate = new ITaskItem[0];
foreach (var item in ProjectsToUpdate)
{
string projectFile = item.ItemSpec;
string projectConfigurationPropsFile = Path.Combine(Path.GetDirectoryName(projectFile), ConfigurationPropsFilename);
string[] expectedConfigurations = s_configurationSuffixes;
if (File.Exists(projectConfigurationPropsFile))
{
expectedConfigurations = GetConfigurationStrings(projectConfigurationPropsFile);
}
Log.LogMessage($"Updating {projectFile}");
var project = ProjectRootElement.Open(projectFile);
ICollection<ProjectPropertyGroupElement> propertyGroups;
var actualConfigurations = GetConfigurationFromPropertyGroups(project, out propertyGroups);
bool addedGuid = EnsureProjectGuid(project);
if (!actualConfigurations.SequenceEqual(expectedConfigurations))
{
ReplaceConfigurationPropertyGroups(project, propertyGroups, expectedConfigurations);
}
if (addedGuid || !actualConfigurations.SequenceEqual(expectedConfigurations))
{
project.Save();
}
}
foreach (var solutionRoot in SolutionsToUpdate)
{
UpdateSolution(solutionRoot);
}
return !Log.HasLoggedErrors;
}
/// <summary>
/// Gets a sorted list of configuration strings from a Configurations.props file
/// </summary>
/// <param name="configurationProjectFile">Path to Configuration.props file</param>
/// <returns>Sorted list of configuration strings</returns>
private static string[] GetConfigurationStrings(string configurationProjectFile, bool addSuffixes = true)
{
var configurationProject = new Project(configurationProjectFile);
var buildConfigurations = configurationProject.GetPropertyValue("BuildConfigurations");
ProjectCollection.GlobalProjectCollection.UnloadProject(configurationProject);
var configurations = buildConfigurations.Trim()
.Split(';')
.Select(c => c.Trim())
.Where(c => !String.IsNullOrEmpty(c));
if (addSuffixes)
{
configurations = configurations.SelectMany(c => s_configurationSuffixes.Select(s => c + "-" + s));
}
return configurations.OrderBy(c => c, StringComparer.OrdinalIgnoreCase).ToArray();
}
/// <summary>
/// Gets a sorted list of configuration strings from a project file's PropertyGroups
/// </summary>
/// <param name="project">Project</param>
/// <param name="propertyGroups">collection that accepts the list of property groups representing configuration strings</param>
/// <returns>Sorted list of configuration strings</returns>
private static string[] GetConfigurationFromPropertyGroups(ProjectRootElement project, out ICollection<ProjectPropertyGroupElement> propertyGroups)
{
propertyGroups = new List<ProjectPropertyGroupElement>();
var configurations = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var propertyGroup in project.PropertyGroups)
{
var match = s_configurationConditionRegex.Match(propertyGroup.Condition);
if (match.Success)
{
configurations.Add(match.Groups["config"].Value);
propertyGroups.Add(propertyGroup);
}
}
return configurations.ToArray();
}
/// <summary>
/// Replaces all configuration propertygroups with empty property groups corresponding to the expected configurations.
/// Doesn't attempt to preserve any content since it can all be regenerated.
/// Does attempt to preserve the ordering in the project file.
/// </summary>
/// <param name="project">Project</param>
/// <param name="oldPropertyGroups">PropertyGroups to remove</param>
/// <param name="newConfigurations"></param>
private static void ReplaceConfigurationPropertyGroups(ProjectRootElement project, IEnumerable<ProjectPropertyGroupElement> oldPropertyGroups, IEnumerable<string> newConfigurations)
{
ProjectElement insertAfter = null, insertBefore = null;
foreach (var oldPropertyGroup in oldPropertyGroups)
{
insertBefore = oldPropertyGroup.NextSibling;
project.RemoveChild(oldPropertyGroup);
}
if (insertBefore == null)
{
// find first itemgroup after imports
var insertAt = project.Imports.FirstOrDefault()?.NextSibling;
while (insertAt != null)
{
if (insertAt is ProjectItemGroupElement)
{
insertBefore = insertAt;
break;
}
insertAt = insertAt.NextSibling;
}
}
if (insertBefore == null)
{
// find last propertygroup after imports, defaulting to after imports
insertAfter = project.Imports.FirstOrDefault();
while (insertAfter?.NextSibling != null && insertAfter.NextSibling is ProjectPropertyGroupElement)
{
insertAfter = insertAfter.NextSibling;
}
}
foreach (var newConfiguration in newConfigurations)
{
var newPropertyGroup = project.CreatePropertyGroupElement();
newPropertyGroup.Condition = $"'$(Configuration)|$(Platform)' == '{newConfiguration}'";
if (insertBefore != null)
{
project.InsertBeforeChild(newPropertyGroup, insertBefore);
}
else if (insertAfter != null)
{
project.InsertAfterChild(newPropertyGroup, insertAfter);
}
else
{
project.AppendChild(newPropertyGroup);
}
insertBefore = null;
insertAfter = newPropertyGroup;
}
}
private static Dictionary<string, string> _guidMap = new Dictionary<string, string>();
private bool EnsureProjectGuid(ProjectRootElement project)
{
ProjectPropertyElement projectGuid = project.Properties.FirstOrDefault(p => p.Name == "ProjectGuid");
string guid = string.Empty;
if (projectGuid != null)
{
guid = projectGuid.Value;
string projectName;
if (_guidMap.TryGetValue(guid, out projectName))
{
Log.LogMessage($"The ProjectGuid='{guid}' is duplicated across projects '{projectName}' and '{project.FullPath}', so creating a new one for project '{project.FullPath}'");
guid = Guid.NewGuid().ToString("B").ToUpper();
_guidMap.Add(guid, project.FullPath);
projectGuid.Value = guid;
return true;
}
else
{
_guidMap.Add(guid, project.FullPath);
}
}
if (projectGuid == null)
{
guid = Guid.NewGuid().ToString("B").ToUpper();
var propertyGroup = project.Imports.FirstOrDefault()?.NextSibling as ProjectPropertyGroupElement;
if (propertyGroup == null || !string.IsNullOrEmpty(propertyGroup.Condition))
{
propertyGroup = project.CreatePropertyGroupElement();
ProjectElement insertAfter = project.Imports.FirstOrDefault();
if (insertAfter == null)
{
insertAfter = project.Children.FirstOrDefault();
}
if (insertAfter != null)
{
project.InsertAfterChild(propertyGroup, insertAfter);
}
else
{
project.AppendChild(propertyGroup);
}
}
propertyGroup.AddProperty("ProjectGuid", guid);
return true;
}
return false;
}
private void UpdateSolution(ITaskItem solutionRootItem)
{
string solutionRootPath = Path.GetFullPath(solutionRootItem.ItemSpec);
string projectExclude = solutionRootItem.GetMetadata("ExcludePattern");
List<ProjectFolder> projectFolders = new List<ProjectFolder>();
if (!solutionRootPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
solutionRootPath += Path.DirectorySeparatorChar;
}
ProjectFolder testFolder = new ProjectFolder(solutionRootPath, "tests", "{1A2F9F4A-A032-433E-B914-ADD5992BB178}", projectExclude, true);
if (testFolder.FolderExists)
{
projectFolders.Add(testFolder);
}
ProjectFolder srcFolder = new ProjectFolder(solutionRootPath, "src", "{E107E9C1-E893-4E87-987E-04EF0DCEAEFD}", projectExclude);
if (srcFolder.FolderExists)
{
testFolder.DependsOn.Add(srcFolder);
projectFolders.Add(srcFolder);
};
ProjectFolder refFolder = new ProjectFolder(solutionRootPath, "ref", "{2E666815-2EDB-464B-9DF6-380BF4789AD4}", projectExclude);
if (refFolder.FolderExists)
{
srcFolder.DependsOn.Add(refFolder);
projectFolders.Add(refFolder);
}
if (projectFolders.Count == 0)
{
Log.LogMessage($"Directory '{solutionRootPath}' does not contain a 'src', 'tests', or 'ref' directory so skipping solution generation.");
return;
}
Log.LogMessage($"Generating solution for '{solutionRootPath}'...");
StringBuilder slnBuilder = new StringBuilder();
slnBuilder.AppendLine("Microsoft Visual Studio Solution File, Format Version 12.00");
slnBuilder.AppendLine("# Visual Studio 14");
slnBuilder.AppendLine("VisualStudioVersion = 14.0.25420.1");
slnBuilder.AppendLine("MinimumVisualStudioVersion = 10.0.40219.1");
// Output project items
foreach (var projectFolder in projectFolders)
{
foreach (var slnProject in projectFolder.Projects)
{
string projectName = Path.GetFileNameWithoutExtension(slnProject.ProjectPath);
// Normalize the directory separators to the windows version given these are projects for VS and only work on windows.
string relativePathFromCurrentDirectory = slnProject.ProjectPath.Replace(solutionRootPath, "").Replace("/", "\\");
slnBuilder.AppendLine($"Project(\"{slnProject.SolutionGuid}\") = \"{projectName}\", \"{relativePathFromCurrentDirectory}\", \"{slnProject.ProjectGuid}\"");
bool writeEndProjectSection = false;
foreach (var dependentFolder in projectFolder.DependsOn)
{
foreach (var depProject in dependentFolder.Projects)
{
string depProjectId = depProject.ProjectGuid;
slnBuilder.AppendLine(
$"\tProjectSection(ProjectDependencies) = postProject\r\n\t\t{depProjectId} = {depProjectId}");
writeEndProjectSection = true;
}
}
if (writeEndProjectSection)
{
slnBuilder.AppendLine("\tEndProjectSection");
}
slnBuilder.AppendLine("EndProject");
}
}
// Output the solution folder items
foreach (var projectFolder in projectFolders)
{
slnBuilder.AppendLine($"Project(\"{projectFolder.SolutionGuid}\") = \"{projectFolder.Name}\", \"{projectFolder.Name}\", \"{projectFolder.ProjectGuid}\"\r\nEndProject");
}
string anyCPU = "Any CPU";
string slnDebug = "Debug|" + anyCPU;
string slnRelease = "Release|" + anyCPU;
// Output the solution configurations
slnBuilder.AppendLine("Global");
slnBuilder.AppendLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
slnBuilder.AppendLine($"\t\t{slnDebug} = {slnDebug}");
slnBuilder.AppendLine($"\t\t{slnRelease} = {slnRelease}");
slnBuilder.AppendLine("\tEndGlobalSection");
slnBuilder.AppendLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
// Output the solution to project configuration mappings
foreach (var projectFolder in projectFolders)
{
foreach (var slnProject in projectFolder.Projects)
{
string projectConfig = slnProject.GetBestConfiguration("netcoreapp-Windows_NT");
if (!string.IsNullOrEmpty(projectConfig))
{
projectConfig += "-";
}
string[] slnConfigs = new string[] { slnDebug, slnRelease };
string[] markers = new string[] { "ActiveCfg", "Build.0" };
foreach (string slnConfig in slnConfigs)
{
foreach (string marker in markers)
{
slnBuilder.AppendLine($"\t\t{slnProject.ProjectGuid}.{slnConfig}.{marker} = {projectConfig}{slnConfig}");
}
}
}
}
slnBuilder.AppendLine("\tEndGlobalSection");
slnBuilder.AppendLine("\tGlobalSection(SolutionProperties) = preSolution");
slnBuilder.AppendLine("\t\tHideSolutionNode = FALSE");
slnBuilder.AppendLine("\tEndGlobalSection");
// Output the project to solution folder mappings
slnBuilder.AppendLine("\tGlobalSection(NestedProjects) = preSolution");
foreach (var projectFolder in projectFolders)
{
foreach (var slnProject in projectFolder.Projects)
{
slnBuilder.AppendLine($"\t\t{slnProject.ProjectGuid} = {projectFolder.ProjectGuid}");
}
}
slnBuilder.AppendLine("\tEndGlobalSection");
slnBuilder.AppendLine("EndGlobal");
string solutionName = GetNameForSolution(solutionRootPath);
string slnFile = Path.Combine(solutionRootPath, solutionName + ".sln");
File.WriteAllText(slnFile, slnBuilder.ToString());
}
private static string GetNameForSolution(string path)
{
if (path.Length < 0)
throw new ArgumentException("Invalid base bath for solution", nameof(path));
if (path[path.Length - 1] == Path.DirectorySeparatorChar || path[path.Length - 1] == Path.AltDirectorySeparatorChar)
{
return GetNameForSolution(path.Substring(0, path.Length - 1));
}
return Path.GetFileName(path);
}
internal class ProjectFolder
{
public string Name { get; }
public string ProjectGuid { get; }
public string SolutionGuid { get { return "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"; } }
public string ProjectFolderPath { get; }
public bool InUse { get; set; }
public List<ProjectFolder> DependsOn { get; set; } = new List<ProjectFolder>();
public bool FolderExists { get; }
public List<SolutionProject> Projects { get; }
public ProjectFolder(string basePath, string relPath, string projectId, string projectExcludePattern, bool searchRecursively = false)
{
Name = relPath;
ProjectGuid = projectId;
ProjectFolderPath = Path.Combine(basePath, relPath);
FolderExists = Directory.Exists(ProjectFolderPath);
Projects = new List<SolutionProject>();
if (FolderExists)
{
SearchOption searchOption = searchRecursively ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
Regex excludePattern = string.IsNullOrEmpty(projectExcludePattern) ? null : new Regex(projectExcludePattern);
string primaryProjectPrefix = Path.Combine(ProjectFolderPath, GetNameForSolution(basePath) + "." + relPath);
foreach (string proj in Directory.EnumerateFiles(ProjectFolderPath, "*proj", searchOption).OrderBy(p => p))
{
if (excludePattern == null || !excludePattern.IsMatch(proj))
{
if (proj.StartsWith(primaryProjectPrefix, StringComparison.OrdinalIgnoreCase))
{
// Always put the primary project first in the list
Projects.Insert(0, new SolutionProject(proj));
}
else
{
Projects.Add(new SolutionProject(proj));
}
}
}
}
}
}
internal class SolutionProject
{
public string ProjectPath { get; }
public string ProjectGuid { get; }
public string[] Configurations { get; set; }
public SolutionProject(string projectPath)
{
ProjectPath = projectPath;
ProjectGuid = ReadProjectGuid(projectPath);
string configurationProps = Path.Combine(Path.GetDirectoryName(projectPath), "Configurations.props");
if (File.Exists(configurationProps))
{
Configurations = GetConfigurationStrings(configurationProps, addSuffixes:false);
}
else
{
Configurations = new string[0];
}
}
public string GetBestConfiguration(string buildConfiguration)
{
//TODO: We should use the FindBestConfigutation logic from the build tasks
var match = Configurations.FirstOrDefault(c => c == buildConfiguration);
if (match != null)
return match;
match = Configurations.FirstOrDefault(c => buildConfiguration.StartsWith(c));
if (match != null)
return match;
// Try again with netstandard if we didn't find the specific build match.
buildConfiguration = "netstandard-Windows_NT";
match = Configurations.FirstOrDefault(c => c == buildConfiguration);
if (match != null)
return match;
match = Configurations.FirstOrDefault(c => buildConfiguration.StartsWith(c));
if (match != null)
return match;
if (Configurations.Length > 0)
return Configurations[0];
return string.Empty;
}
private static string ReadProjectGuid(string projectFile)
{
var project = ProjectRootElement.Open(projectFile);
ProjectPropertyElement projectGuid = project.Properties.FirstOrDefault(p => p.Name == "ProjectGuid");
if (projectGuid == null)
{
return Guid.NewGuid().ToString("B").ToUpper();
}
return projectGuid.Value;
}
public string SolutionGuid
{
get
{
//ProjectTypeGuids for different projects, pulled from the Visual Studio regkeys
//TODO: Clean up or map these to actual projects, this is fragile
string slnGuid = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"; // Windows (C#)
if (ProjectPath.Contains("VisualBasic.vbproj"))
{
slnGuid = "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}"; //Windows (VB.NET)
}
if (ProjectPath.Contains("TestNativeService")) //Windows (Visual C++)
{
slnGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
}
if (ProjectPath.Contains("WebServer.csproj")) //Web Application
{
slnGuid = "{349C5851-65DF-11DA-9384-00065B846F21}";
}
return slnGuid;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.JSInterop;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Components.Server.Circuits
{
public class CircuitHostTest
{
[Fact]
public async Task DisposeAsync_DisposesResources()
{
// Arrange
var serviceScope = new Mock<IServiceScope>();
var remoteRenderer = GetRemoteRenderer();
var circuitHost = TestCircuitHost.Create(
serviceScope: new AsyncServiceScope(serviceScope.Object),
remoteRenderer: remoteRenderer);
// Act
await circuitHost.DisposeAsync();
// Assert
serviceScope.Verify(s => s.Dispose(), Times.Once());
Assert.True(remoteRenderer.Disposed);
Assert.Null(circuitHost.Handle.CircuitHost);
}
[Fact]
public async Task DisposeAsync_DisposesScopeAsynchronouslyIfPossible()
{
// Arrange
var serviceScope = new Mock<IServiceScope>();
serviceScope
.As<IAsyncDisposable>()
.Setup(f => f.DisposeAsync())
.Returns(new ValueTask(Task.CompletedTask))
.Verifiable();
var remoteRenderer = GetRemoteRenderer();
var circuitHost = TestCircuitHost.Create(
serviceScope: new AsyncServiceScope(serviceScope.Object),
remoteRenderer: remoteRenderer);
// Act
await circuitHost.DisposeAsync();
// Assert
serviceScope.Verify(s => s.Dispose(), Times.Never());
serviceScope.As<IAsyncDisposable>().Verify(s => s.DisposeAsync(), Times.Once());
Assert.True(remoteRenderer.Disposed);
Assert.Null(circuitHost.Handle.CircuitHost);
}
[Fact]
public async Task DisposeAsync_DisposesResourcesAndSilencesException()
{
// Arrange
var serviceScope = new Mock<IServiceScope>();
var handler = new Mock<CircuitHandler>();
handler
.Setup(h => h.OnCircuitClosedAsync(It.IsAny<Circuit>(), It.IsAny<CancellationToken>()))
.Throws<InvalidTimeZoneException>();
var remoteRenderer = GetRemoteRenderer();
var circuitHost = TestCircuitHost.Create(
serviceScope: new AsyncServiceScope(serviceScope.Object),
remoteRenderer: remoteRenderer,
handlers: new[] { handler.Object });
var throwOnDisposeComponent = new ThrowOnDisposeComponent();
circuitHost.Renderer.AssignRootComponentId(throwOnDisposeComponent);
// Act
await circuitHost.DisposeAsync(); // Does not throw
// Assert
Assert.True(throwOnDisposeComponent.DidCallDispose);
serviceScope.Verify(scope => scope.Dispose(), Times.Once());
Assert.True(remoteRenderer.Disposed);
}
[Fact]
public async Task DisposeAsync_DisposesRendererWithinSynchronizationContext()
{
// Arrange
var serviceScope = new Mock<IServiceScope>();
var remoteRenderer = GetRemoteRenderer();
var circuitHost = TestCircuitHost.Create(
serviceScope: new AsyncServiceScope(serviceScope.Object),
remoteRenderer: remoteRenderer);
var component = new DispatcherComponent(circuitHost.Renderer.Dispatcher);
circuitHost.Renderer.AssignRootComponentId(component);
var original = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(null);
// Act & Assert
try
{
Assert.Null(SynchronizationContext.Current);
await circuitHost.DisposeAsync();
Assert.True(component.Called);
Assert.Null(SynchronizationContext.Current);
}
finally
{
// Not sure if the line above messes up the xunit sync context, so just being cautious here.
SynchronizationContext.SetSynchronizationContext(original);
}
}
[Fact]
public async Task DisposeAsync_MarksJSRuntimeAsDisconnectedBeforeDisposingRenderer()
{
// Arrange
var serviceScope = new Mock<IServiceScope>();
var remoteRenderer = GetRemoteRenderer();
var circuitHost = TestCircuitHost.Create(
serviceScope: new AsyncServiceScope(serviceScope.Object),
remoteRenderer: remoteRenderer);
var component = new PerformJSInteropOnDisposeComponent(circuitHost.JSRuntime);
circuitHost.Renderer.AssignRootComponentId(component);
var circuitUnhandledExceptions = new List<UnhandledExceptionEventArgs>();
circuitHost.UnhandledException += (sender, eventArgs) =>
{
circuitUnhandledExceptions.Add(eventArgs);
};
// Act
await circuitHost.DisposeAsync();
// Assert: Component disposal logic sees the exception
var componentException = Assert.IsType<JSDisconnectedException>(component.ExceptionDuringDisposeAsync);
// Assert: Circuit host notifies about the exception
Assert.Collection(circuitUnhandledExceptions, eventArgs =>
{
Assert.Same(componentException, eventArgs.ExceptionObject);
});
}
[Fact]
public async Task InitializeAsync_InvokesHandlers()
{
// Arrange
var cancellationToken = new CancellationToken();
var handler1 = new Mock<CircuitHandler>(MockBehavior.Strict);
var handler2 = new Mock<CircuitHandler>(MockBehavior.Strict);
var sequence = new MockSequence();
handler1
.InSequence(sequence)
.Setup(h => h.OnCircuitOpenedAsync(It.IsAny<Circuit>(), cancellationToken))
.Returns(Task.CompletedTask)
.Verifiable();
handler2
.InSequence(sequence)
.Setup(h => h.OnCircuitOpenedAsync(It.IsAny<Circuit>(), cancellationToken))
.Returns(Task.CompletedTask)
.Verifiable();
handler1
.InSequence(sequence)
.Setup(h => h.OnConnectionUpAsync(It.IsAny<Circuit>(), cancellationToken))
.Returns(Task.CompletedTask)
.Verifiable();
handler2
.InSequence(sequence)
.Setup(h => h.OnConnectionUpAsync(It.IsAny<Circuit>(), cancellationToken))
.Returns(Task.CompletedTask)
.Verifiable();
var circuitHost = TestCircuitHost.Create(handlers: new[] { handler1.Object, handler2.Object });
// Act
await circuitHost.InitializeAsync(new ProtectedPrerenderComponentApplicationStore(Mock.Of<IDataProtectionProvider>()), cancellationToken);
// Assert
handler1.VerifyAll();
handler2.VerifyAll();
}
[Fact]
public async Task InitializeAsync_RendersRootComponentsInParallel()
{
// To test that root components are run in parallel, we ensure that each root component
// finishes rendering (i.e. returns from SetParametersAsync()) only after all other
// root components have started rendering. If the root components were rendered
// sequentially, the 1st component would get stuck rendering forever because the
// 2nd component had not yet started rendering. We call RenderInParallelComponent.Setup()
// to configure how many components will be rendered in advance so that each component
// can be assigned a TaskCompletionSource and await the same array of tasks. A timeout
// is configured for circuitHost.InitializeAsync() so that the test can fail rather than
// hang forever.
// Arrange
var componentCount = 3;
var initializeTimeout = TimeSpan.FromMilliseconds(5000);
var cancellationToken = new CancellationToken();
var serviceScope = new Mock<IServiceScope>();
var descriptors = new List<ComponentDescriptor>();
RenderInParallelComponent.Setup(componentCount);
for (var i = 0; i < componentCount; i++)
{
descriptors.Add(new()
{
ComponentType = typeof(RenderInParallelComponent),
Parameters = ParameterView.Empty,
Sequence = 0
});
}
var circuitHost = TestCircuitHost.Create(
serviceScope: new AsyncServiceScope(serviceScope.Object),
descriptors: descriptors);
// Act
object initializeException = null;
circuitHost.UnhandledException += (sender, eventArgs) => initializeException = eventArgs.ExceptionObject;
var initializeTask = circuitHost.InitializeAsync(new ProtectedPrerenderComponentApplicationStore(Mock.Of<IDataProtectionProvider>()), cancellationToken);
await initializeTask.WaitAsync(initializeTimeout);
// Assert: This was not reached only because an exception was thrown in InitializeAsync()
Assert.True(initializeException is null, $"An exception was thrown in {nameof(TestCircuitHost.InitializeAsync)}(): {initializeException}");
}
[Fact]
public async Task InitializeAsync_ReportsOwnAsyncExceptions()
{
// Arrange
var handler = new Mock<CircuitHandler>(MockBehavior.Strict);
var tcs = new TaskCompletionSource<object>();
var reportedErrors = new List<UnhandledExceptionEventArgs>();
handler
.Setup(h => h.OnCircuitOpenedAsync(It.IsAny<Circuit>(), It.IsAny<CancellationToken>()))
.Returns(tcs.Task)
.Verifiable();
var circuitHost = TestCircuitHost.Create(handlers: new[] { handler.Object });
circuitHost.UnhandledException += (sender, errorInfo) =>
{
Assert.Same(circuitHost, sender);
reportedErrors.Add(errorInfo);
};
// Act
var initializeAsyncTask = circuitHost.InitializeAsync(new ProtectedPrerenderComponentApplicationStore(Mock.Of<IDataProtectionProvider>()), new CancellationToken());
// Assert: No synchronous exceptions
handler.VerifyAll();
Assert.Empty(reportedErrors);
// Act: Trigger async exception
var ex = new InvalidTimeZoneException();
tcs.SetException(ex);
// Assert: The top-level task still succeeds, because the intended usage
// pattern is fire-and-forget.
await initializeAsyncTask;
// Assert: The async exception was reported via the side-channel
var aex = Assert.IsType<AggregateException>(reportedErrors.Single().ExceptionObject);
Assert.Same(ex, aex.InnerExceptions.Single());
Assert.False(reportedErrors.Single().IsTerminating);
}
[Fact]
public async Task DisposeAsync_InvokesCircuitHandler()
{
// Arrange
var cancellationToken = new CancellationToken();
var handler1 = new Mock<CircuitHandler>(MockBehavior.Strict);
var handler2 = new Mock<CircuitHandler>(MockBehavior.Strict);
var sequence = new MockSequence();
handler1
.InSequence(sequence)
.Setup(h => h.OnConnectionDownAsync(It.IsAny<Circuit>(), cancellationToken))
.Returns(Task.CompletedTask)
.Verifiable();
handler2
.InSequence(sequence)
.Setup(h => h.OnConnectionDownAsync(It.IsAny<Circuit>(), cancellationToken))
.Returns(Task.CompletedTask)
.Verifiable();
handler1
.InSequence(sequence)
.Setup(h => h.OnCircuitClosedAsync(It.IsAny<Circuit>(), cancellationToken))
.Returns(Task.CompletedTask)
.Verifiable();
handler2
.InSequence(sequence)
.Setup(h => h.OnCircuitClosedAsync(It.IsAny<Circuit>(), cancellationToken))
.Returns(Task.CompletedTask)
.Verifiable();
var circuitHost = TestCircuitHost.Create(handlers: new[] { handler1.Object, handler2.Object });
// Act
await circuitHost.DisposeAsync();
// Assert
handler1.VerifyAll();
handler2.VerifyAll();
}
private static TestRemoteRenderer GetRemoteRenderer()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(new Mock<IJSRuntime>().Object);
return new TestRemoteRenderer(
serviceCollection.BuildServiceProvider(),
Mock.Of<IClientProxy>());
}
private class TestRemoteRenderer : RemoteRenderer
{
public TestRemoteRenderer(IServiceProvider serviceProvider, IClientProxy client)
: base(
serviceProvider,
NullLoggerFactory.Instance,
new CircuitOptions(),
new CircuitClientProxy(client, "connection"),
NullLogger.Instance,
CreateJSRuntime(new CircuitOptions()),
new CircuitJSComponentInterop(new CircuitOptions()))
{
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
private static RemoteJSRuntime CreateJSRuntime(CircuitOptions options)
=> new RemoteJSRuntime(Options.Create(options), Options.Create(new HubOptions()), null);
}
private class DispatcherComponent : ComponentBase, IDisposable
{
public DispatcherComponent(Dispatcher dispatcher)
{
Dispatcher = dispatcher;
}
public Dispatcher Dispatcher { get; }
public bool Called { get; private set; }
public void Dispose()
{
Called = true;
Assert.Same(Dispatcher, SynchronizationContext.Current);
}
}
private class ThrowOnDisposeComponent : IComponent, IDisposable
{
public bool DidCallDispose { get; private set; }
public void Attach(RenderHandle renderHandle) { }
public Task SetParametersAsync(ParameterView parameters)
=> Task.CompletedTask;
public void Dispose()
{
DidCallDispose = true;
throw new InvalidFilterCriteriaException();
}
}
private class RenderInParallelComponent : IComponent, IDisposable
{
private static TaskCompletionSource[] _renderTcsArray;
private static int _instanceCount = 0;
private readonly int _id;
public static void Setup(int numComponents)
{
if (_instanceCount > 0)
{
throw new InvalidOperationException(
$"Cannot call '{nameof(Setup)}' when there are still " +
$"{nameof(RenderInParallelComponent)} instances active.");
}
_renderTcsArray = new TaskCompletionSource[numComponents];
for (int i = 0; i < _renderTcsArray.Length; i++)
{
_renderTcsArray[i] = new(TaskCreationOptions.RunContinuationsAsynchronously);
}
}
public RenderInParallelComponent()
{
if (_instanceCount >= _renderTcsArray.Length)
{
throw new InvalidOperationException("Created more test component instances than expected.");
}
_id = _instanceCount++;
}
public void Attach(RenderHandle renderHandle)
{
}
public async Task SetParametersAsync(ParameterView parameters)
{
_renderTcsArray[_id].SetResult();
await Task.WhenAll(_renderTcsArray.Select(tcs => tcs.Task));
}
public void Dispose()
{
_instanceCount--;
}
}
private class PerformJSInteropOnDisposeComponent : IComponent, IAsyncDisposable
{
private readonly IJSRuntime _js;
public PerformJSInteropOnDisposeComponent(IJSRuntime jsRuntime)
{
_js = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime));
}
public Exception ExceptionDuringDisposeAsync { get; private set; }
public void Attach(RenderHandle renderHandle)
{
}
public Task SetParametersAsync(ParameterView parameters)
=> Task.CompletedTask;
public async ValueTask DisposeAsync()
{
try
{
await _js.InvokeVoidAsync("SomeJsCleanupCode");
}
catch (Exception ex)
{
ExceptionDuringDisposeAsync = ex;
throw;
}
}
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Net.Sockets;
using System.Threading;
using Orleans.Runtime;
namespace Orleans.Messaging
{
/// <summary>
/// The GatewayConnection class does double duty as both the manager of the connection itself (the socket) and the sender of messages
/// to the gateway. It uses a single instance of the Receiver class to handle messages from the gateway.
///
/// Note that both sends and receives are synchronous.
/// </summary>
internal class GatewayConnection : OutgoingMessageSender
{
internal bool IsLive { get; private set; }
internal ProxiedMessageCenter MsgCenter { get; private set; }
private Uri addr;
internal Uri Address
{
get { return addr; }
private set
{
addr = value;
Silo = addr.ToSiloAddress();
}
}
internal SiloAddress Silo { get; private set; }
private readonly GatewayClientReceiver receiver;
internal Socket Socket { get; private set; } // Shared by the receiver
private DateTime lastConnect;
internal GatewayConnection(Uri address, ProxiedMessageCenter mc)
: base("GatewayClientSender_" + address, mc.MessagingConfiguration)
{
Address = address;
MsgCenter = mc;
receiver = new GatewayClientReceiver(this);
lastConnect = new DateTime();
IsLive = true;
}
public override void Start()
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_GatewayConnStarted, "Starting gateway connection for gateway {0}", Address);
lock (Lockable)
{
if (State == ThreadState.Running)
{
return;
}
Connect();
if (!IsLive) return;
// If the Connect succeeded
receiver.Start();
base.Start();
}
}
public override void Stop()
{
IsLive = false;
receiver.Stop();
base.Stop();
Socket s;
lock (Lockable)
{
s = Socket;
Socket = null;
}
if (s == null) return;
SocketManager.CloseSocket(s);
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
// passed the exact same socket on which it got SocketException. This way we prevent races between connect and disconnect.
public void MarkAsDisconnected(Socket socket2Disconnect)
{
Socket s = null;
lock (Lockable)
{
if (socket2Disconnect == null || Socket == null) return;
if (Socket == socket2Disconnect) // handles races between connect and disconnect, since sometimes we grab the socket outside lock.
{
s = Socket;
Socket = null;
Log.Warn(ErrorCode.ProxyClient_MarkGatewayDisconnected, String.Format("Marking gateway at address {0} as Disconnected", Address));
if ( MsgCenter != null && MsgCenter.GatewayManager != null)
// We need a refresh...
MsgCenter.GatewayManager.ExpediteUpdateLiveGatewaysSnapshot();
}
}
if (s != null)
{
SocketManager.CloseSocket(s);
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
if (socket2Disconnect == s) return;
SocketManager.CloseSocket(socket2Disconnect);
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
public void MarkAsDead()
{
Log.Warn(ErrorCode.ProxyClient_MarkGatewayDead, String.Format("Marking gateway at address {0} as Dead in my client local gateway list.", Address));
MsgCenter.GatewayManager.MarkAsDead(Address);
Stop();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Connect()
{
if (!MsgCenter.Running)
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_MsgCtrNotRunning, "Ignoring connection attempt to gateway {0} because the proxy message center is not running", Address);
return;
}
// Yes, we take the lock around a Sleep. The point is to ensure that no more than one thread can try this at a time.
// There's still a minor problem as written -- if the sending thread and receiving thread both get here, the first one
// will try to reconnect. eventually do so, and then the other will try to reconnect even though it doesn't have to...
// Hopefully the initial "if" statement will prevent that.
lock (Lockable)
{
if (!IsLive)
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_DeadGateway, "Ignoring connection attempt to gateway {0} because this gateway connection is already marked as non live", Address);
return; // if the connection is already marked as dead, don't try to reconnect. It has been doomed.
}
for (var i = 0; i < ProxiedMessageCenter.CONNECT_RETRY_COUNT; i++)
{
try
{
if (Socket != null)
{
if (Socket.Connected)
return;
MarkAsDisconnected(Socket); // clean up the socket before reconnecting.
}
if (lastConnect != new DateTime())
{
var millisecondsSinceLastAttempt = DateTime.UtcNow - lastConnect;
if (millisecondsSinceLastAttempt < ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY)
{
var wait = ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY - millisecondsSinceLastAttempt;
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_PauseBeforeRetry, "Pausing for {0} before trying to connect to gateway {1} on trial {2}", wait, Address, i);
Thread.Sleep(wait);
}
}
lastConnect = DateTime.UtcNow;
Socket = new Socket(Silo.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Socket.Connect(Silo.Endpoint);
NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket();
SocketManager.WriteConnectionPreemble(Socket, MsgCenter.ClientId); // Identifies this client
Log.Info(ErrorCode.ProxyClient_Connected, "Connected to gateway at address {0} on trial {1}.", Address, i);
return;
}
catch (Exception)
{
Log.Warn(ErrorCode.ProxyClient_CannotConnect, "Unable to connect to gateway at address {0} on trial {1}.", Address, i);
MarkAsDisconnected(Socket);
}
}
// Failed too many times -- give up
MarkAsDead();
}
}
protected override SocketDirection GetSocketDirection() { return SocketDirection.ClientToGateway; }
protected override bool PrepareMessageForSend(Message msg)
{
// Check to make sure we're not stopped
if (Cts.IsCancellationRequested)
{
// Recycle the message we've dequeued. Note that this will recycle messages that were queued up to be sent when the gateway connection is declared dead
MsgCenter.SendMessage(msg);
return false;
}
if (msg.TargetSilo != null) return true;
msg.TargetSilo = Silo;
if (msg.TargetGrain.IsSystemTarget)
msg.TargetActivation = ActivationId.GetSystemActivation(msg.TargetGrain, msg.TargetSilo);
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override bool GetSendingSocket(Message msg, out Socket socketCapture, out SiloAddress targetSilo, out string error)
{
error = null;
targetSilo = Silo;
socketCapture = null;
try
{
if (Socket == null || !Socket.Connected)
{
Connect();
}
socketCapture = Socket;
if (socketCapture == null || !socketCapture.Connected)
{
// Failed to connect -- Connect will have already declared this connection dead, so recycle the message
return false;
}
}
catch (Exception)
{
//No need to log any errors, as we alraedy do it inside Connect().
return false;
}
return true;
}
protected override void OnGetSendingSocketFailure(Message msg, string error)
{
msg.TargetSilo = null; // clear previous destination!
MsgCenter.SendMessage(msg);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void OnMessageSerializationFailure(Message msg, Exception exc)
{
// we only get here if we failed to serialise the msg (or any other catastrophic failure).
// Request msg fails to serialise on the sending silo, so we just enqueue a rejection msg.
Log.Warn(ErrorCode.ProxyClient_SerializationError, String.Format("Unexpected error serializing message to gateway {0}.", Address), exc);
FailMessage(msg, String.Format("Unexpected error serializing message to gateway {0}. {1}", Address, exc));
if (msg.Direction == Message.Directions.Request || msg.Direction == Message.Directions.OneWay)
{
return;
}
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
// if we failed sending an original response, turn the response body into an error and reply with it.
msg.Result = Message.ResponseTypes.Error;
msg.BodyObject = Response.ExceptionResponse(exc);
try
{
MsgCenter.SendMessage(msg);
}
catch (Exception ex)
{
// If we still can't serialize, drop the message on the floor
Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Unable to serialize message - DROPPING " + msg, ex);
msg.ReleaseBodyAndHeaderBuffers();
}
}
protected override void OnSendFailure(Socket socket, SiloAddress targetSilo)
{
MarkAsDisconnected(socket);
}
protected override void ProcessMessageAfterSend(Message msg, bool sendError, string sendErrorStr)
{
msg.ReleaseBodyAndHeaderBuffers();
if (sendError)
{
// We can't recycle the current message, because that might wind up with it getting delivered out of order, so we have to reject it
FailMessage(msg, sendErrorStr);
}
}
protected override void FailMessage(Message msg, string reason)
{
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
if (MsgCenter.Running && msg.Direction == Message.Directions.Request)
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, reason);
MsgCenter.QueueIncomingMessage(error);
}
else
{
Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Tests
{
public partial class StringTests
{
[Theory]
[InlineData(0, 0)]
[InlineData(3, 1)]
public static void Ctor_CharSpan_EmptyString(int length, int offset)
{
Assert.Same(string.Empty, new string(new ReadOnlySpan<char>(new char[length], offset, 0)));
}
[Theory]
[InlineData(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0' }, 0, 8, "abcdefgh")]
[InlineData(new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\0', 'i', 'j', 'k' }, 0, 12, "abcdefgh\0ijk")]
[InlineData(new char[] { 'a', 'b', 'c' }, 0, 0, "")]
[InlineData(new char[] { 'a', 'b', 'c' }, 0, 1, "a")]
[InlineData(new char[] { 'a', 'b', 'c' }, 2, 1, "c")]
[InlineData(new char[] { '\u8001', '\u8002', '\ufffd', '\u1234', '\ud800', '\udfff' }, 0, 6, "\u8001\u8002\ufffd\u1234\ud800\udfff")]
public static void Ctor_CharSpan(char[] valueArray, int startIndex, int length, string expected)
{
var span = new ReadOnlySpan<char>(valueArray, startIndex, length);
Assert.Equal(expected, new string(span));
}
[Fact]
public static void Create_InvalidArguments_Throw()
{
AssertExtensions.Throws<ArgumentNullException>("action", () => string.Create(-1, 0, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => string.Create(-1, 0, (span, state) => { }));
}
[Fact]
public static void Create_Length0_ReturnsEmptyString()
{
bool actionInvoked = false;
Assert.Same(string.Empty, string.Create(0, 0, (span, state) => actionInvoked = true));
Assert.False(actionInvoked);
}
[Fact]
public static void Create_NullState_Allowed()
{
string result = string.Create(1, (object)null, (span, state) =>
{
span[0] = 'a';
Assert.Null(state);
});
Assert.Equal("a", result);
}
[Fact]
public static void Create_ClearsMemory()
{
const int Length = 10;
string result = string.Create(Length, (object)null, (span, state) =>
{
for (int i = 0; i < span.Length; i++)
{
Assert.Equal('\0', span[i]);
}
});
Assert.Equal(new string('\0', Length), result);
}
[Theory]
[InlineData("a")]
[InlineData("this is a test")]
[InlineData("\0\u8001\u8002\ufffd\u1234\ud800\udfff")]
public static void Create_ReturnsExpectedString(string expected)
{
char[] input = expected.ToCharArray();
string result = string.Create(input.Length, input, (span, state) =>
{
Assert.Same(input, state);
for (int i = 0; i < state.Length; i++)
{
span[i] = state[i];
}
});
Assert.Equal(expected, result);
}
[Theory]
[InlineData("Hello", 'H', true)]
[InlineData("Hello", 'Z', false)]
[InlineData("Hello", 'e', true)]
[InlineData("Hello", 'E', false)]
[InlineData("", 'H', false)]
public static void Contains(string s, char value, bool expected)
{
Assert.Equal(expected, s.Contains(value));
}
[Theory]
// CurrentCulture
[InlineData("Hello", 'H', StringComparison.CurrentCulture, true)]
[InlineData("Hello", 'Z', StringComparison.CurrentCulture, false)]
[InlineData("Hello", 'e', StringComparison.CurrentCulture, true)]
[InlineData("Hello", 'E', StringComparison.CurrentCulture, false)]
[InlineData("", 'H', StringComparison.CurrentCulture, false)]
// CurrentCultureIgnoreCase
[InlineData("Hello", 'H', StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("Hello", 'Z', StringComparison.CurrentCultureIgnoreCase, false)]
[InlineData("Hello", 'e', StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("Hello", 'E', StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("", 'H', StringComparison.CurrentCultureIgnoreCase, false)]
// InvariantCulture
[InlineData("Hello", 'H', StringComparison.InvariantCulture, true)]
[InlineData("Hello", 'Z', StringComparison.InvariantCulture, false)]
[InlineData("Hello", 'e', StringComparison.InvariantCulture, true)]
[InlineData("Hello", 'E', StringComparison.InvariantCulture, false)]
[InlineData("", 'H', StringComparison.InvariantCulture, false)]
// InvariantCultureIgnoreCase
[InlineData("Hello", 'H', StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("Hello", 'Z', StringComparison.InvariantCultureIgnoreCase, false)]
[InlineData("Hello", 'e', StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("Hello", 'E', StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("", 'H', StringComparison.InvariantCultureIgnoreCase, false)]
// Ordinal
[InlineData("Hello", 'H', StringComparison.Ordinal, true)]
[InlineData("Hello", 'Z', StringComparison.Ordinal, false)]
[InlineData("Hello", 'e', StringComparison.Ordinal, true)]
[InlineData("Hello", 'E', StringComparison.Ordinal, false)]
[InlineData("", 'H', StringComparison.Ordinal, false)]
// OrdinalIgnoreCase
[InlineData("Hello", 'H', StringComparison.OrdinalIgnoreCase, true)]
[InlineData("Hello", 'Z', StringComparison.OrdinalIgnoreCase, false)]
[InlineData("Hello", 'e', StringComparison.OrdinalIgnoreCase, true)]
[InlineData("Hello", 'E', StringComparison.OrdinalIgnoreCase, true)]
[InlineData("", 'H', StringComparison.OrdinalIgnoreCase, false)]
public static void Contains(string s, char value, StringComparison comparisionType, bool expected)
{
Assert.Equal(expected, s.Contains(value, comparisionType));
}
[Theory]
// CurrentCulture
[InlineData("Hello", "ello", StringComparison.CurrentCulture, true)]
[InlineData("Hello", "ELL", StringComparison.CurrentCulture, false)]
[InlineData("Hello", "ElLo", StringComparison.CurrentCulture, false)]
[InlineData("Hello", "Larger Hello", StringComparison.CurrentCulture, false)]
[InlineData("Hello", "Goodbye", StringComparison.CurrentCulture, false)]
[InlineData("", "", StringComparison.CurrentCulture, true)]
[InlineData("", "hello", StringComparison.CurrentCulture, false)]
[InlineData("Hello", "", StringComparison.CurrentCulture, true)]
[InlineData("Hello", "ell" + SoftHyphen, StringComparison.CurrentCulture, true)]
[InlineData("Hello", "Ell" + SoftHyphen, StringComparison.CurrentCulture, false)]
// CurrentCultureIgnoreCase
[InlineData("Hello", "ello", StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("Hello", "ELL", StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("Hello", "ElLo", StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("Hello", "Larger Hello", StringComparison.CurrentCultureIgnoreCase, false)]
[InlineData("Hello", "Goodbye", StringComparison.CurrentCultureIgnoreCase, false)]
[InlineData("", "", StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("", "hello", StringComparison.CurrentCultureIgnoreCase, false)]
[InlineData("Hello", "", StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("Hello", "ell" + SoftHyphen, StringComparison.CurrentCultureIgnoreCase, true)]
[InlineData("Hello", "Ell" + SoftHyphen, StringComparison.CurrentCultureIgnoreCase, true)]
// InvariantCulture
[InlineData("Hello", "ello", StringComparison.InvariantCulture, true)]
[InlineData("Hello", "ELL", StringComparison.InvariantCulture, false)]
[InlineData("Hello", "ElLo", StringComparison.InvariantCulture, false)]
[InlineData("Hello", "Larger Hello", StringComparison.InvariantCulture, false)]
[InlineData("Hello", "Goodbye", StringComparison.InvariantCulture, false)]
[InlineData("", "", StringComparison.InvariantCulture, true)]
[InlineData("", "hello", StringComparison.InvariantCulture, false)]
[InlineData("Hello", "", StringComparison.InvariantCulture, true)]
[InlineData("Hello", "ell" + SoftHyphen, StringComparison.InvariantCulture, true)]
[InlineData("Hello", "Ell" + SoftHyphen, StringComparison.InvariantCulture, false)]
// InvariantCultureIgnoreCase
[InlineData("Hello", "ello", StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("Hello", "ELL", StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("Hello", "ElLo", StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("Hello", "Larger Hello", StringComparison.InvariantCultureIgnoreCase, false)]
[InlineData("Hello", "Goodbye", StringComparison.InvariantCultureIgnoreCase, false)]
[InlineData("", "", StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("", "hello", StringComparison.InvariantCultureIgnoreCase, false)]
[InlineData("Hello", "", StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("Hello", "ell" + SoftHyphen, StringComparison.InvariantCultureIgnoreCase, true)]
[InlineData("Hello", "Ell" + SoftHyphen, StringComparison.InvariantCultureIgnoreCase, true)]
// Ordinal
[InlineData("Hello", "ello", StringComparison.Ordinal, true)]
[InlineData("Hello", "ELL", StringComparison.Ordinal, false)]
[InlineData("Hello", "ElLo", StringComparison.Ordinal, false)]
[InlineData("Hello", "Larger Hello", StringComparison.Ordinal, false)]
[InlineData("Hello", "Goodbye", StringComparison.Ordinal, false)]
[InlineData("", "", StringComparison.Ordinal, true)]
[InlineData("", "hello", StringComparison.Ordinal, false)]
[InlineData("Hello", "", StringComparison.Ordinal, true)]
[InlineData("Hello", "ell" + SoftHyphen, StringComparison.Ordinal, false)]
[InlineData("Hello", "Ell" + SoftHyphen, StringComparison.Ordinal, false)]
// OrdinalIgnoreCase
[InlineData("Hello", "ello", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("Hello", "ELL", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("Hello", "ElLo", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("Hello", "Larger Hello", StringComparison.OrdinalIgnoreCase, false)]
[InlineData("Hello", "Goodbye", StringComparison.OrdinalIgnoreCase, false)]
[InlineData("", "", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("", "hello", StringComparison.OrdinalIgnoreCase, false)]
[InlineData("Hello", "", StringComparison.OrdinalIgnoreCase, true)]
[InlineData("Hello", "ell" + SoftHyphen, StringComparison.OrdinalIgnoreCase, false)]
[InlineData("Hello", "Ell" + SoftHyphen, StringComparison.OrdinalIgnoreCase, false)]
public static void Contains(string s, string value, StringComparison comparisonType, bool expected)
{
Assert.Equal(expected, s.Contains(value, comparisonType));
}
[Fact]
public static void Contains_StringComparison_TurkishI()
{
string str = "\u0069\u0130";
RemoteInvoke((source) =>
{
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
Assert.True(source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
return SuccessExitCode;
}, str).Dispose();
RemoteInvoke((source) =>
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
Assert.False(source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
return SuccessExitCode;
}, str).Dispose();
}
[Theory]
[InlineData(StringComparison.CurrentCulture)]
[InlineData(StringComparison.CurrentCultureIgnoreCase)]
[InlineData(StringComparison.InvariantCulture)]
[InlineData(StringComparison.InvariantCultureIgnoreCase)]
[InlineData(StringComparison.Ordinal)]
[InlineData(StringComparison.OrdinalIgnoreCase)]
public static void Contains_NullValue_ThrowsArgumentNullException(StringComparison comparisonType)
{
AssertExtensions.Throws<ArgumentNullException>("value", () => "foo".Contains(null, comparisonType));
}
[Theory]
[InlineData(StringComparison.CurrentCulture - 1)]
[InlineData(StringComparison.OrdinalIgnoreCase + 1)]
public static void Contains_InvalidComparisonType_ThrowsArgumentOutOfRangeException(StringComparison comparisonType)
{
AssertExtensions.Throws<ArgumentException>("comparisonType", () => "ab".Contains("a", comparisonType));
}
[Theory]
[InlineData("Hello", 'o', true)]
[InlineData("Hello", 'O', false)]
[InlineData("o", 'o', true)]
[InlineData("o", 'O', false)]
[InlineData("Hello", 'e', false)]
[InlineData("Hello", '\0', false)]
[InlineData("", '\0', false)]
[InlineData("\0", '\0', true)]
[InlineData("", 'a', false)]
[InlineData("abcdefghijklmnopqrstuvwxyz", 'z', true)]
public static void EndsWith(string s, char value, bool expected)
{
Assert.Equal(expected, s.EndsWith(value));
}
[Theory]
[InlineData("Hello", 'H', true)]
[InlineData("Hello", 'h', false)]
[InlineData("H", 'H', true)]
[InlineData("H", 'h', false)]
[InlineData("Hello", 'e', false)]
[InlineData("Hello", '\0', false)]
[InlineData("", '\0', false)]
[InlineData("\0", '\0', true)]
[InlineData("", 'a', false)]
[InlineData("abcdefghijklmnopqrstuvwxyz", 'a', true)]
public static void StartsWith(string s, char value, bool expected)
{
Assert.Equal(expected, s.StartsWith(value));
}
public static IEnumerable<object[]> Join_Char_StringArray_TestData()
{
yield return new object[] { '|', new string[0], 0, 0, "" };
yield return new object[] { '|', new string[] { "a" }, 0, 1, "a" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 3, "a|b|c" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 2, "a|b" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 1, "b" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 2, "b|c" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 3, 0, "" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 0, "" };
yield return new object[] { '|', new string[] { "", "", "" }, 0, 3, "||" };
yield return new object[] { '|', new string[] { null, null, null }, 0, 3, "||" };
}
[Theory]
[MemberData(nameof(Join_Char_StringArray_TestData))]
public static void Join_Char_StringArray(char separator, string[] values, int startIndex, int count, string expected)
{
if (startIndex == 0 && count == values.Length)
{
Assert.Equal(expected, string.Join(separator, values));
Assert.Equal(expected, string.Join(separator, (IEnumerable<string>)values));
Assert.Equal(expected, string.Join(separator, (object[])values));
Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values));
}
Assert.Equal(expected, string.Join(separator, values, startIndex, count));
Assert.Equal(expected, string.Join(separator.ToString(), values, startIndex, count));
}
public static IEnumerable<object[]> Join_Char_ObjectArray_TestData()
{
yield return new object[] { '|', new object[0], "" };
yield return new object[] { '|', new object[] { 1 }, "1" };
yield return new object[] { '|', new object[] { 1, 2, 3 }, "1|2|3" };
yield return new object[] { '|', new object[] { new ObjectWithNullToString(), 2, new ObjectWithNullToString() }, "|2|" };
yield return new object[] { '|', new object[] { "1", null, "3" }, "1||3" };
yield return new object[] { '|', new object[] { "", "", "" }, "||" };
yield return new object[] { '|', new object[] { "", null, "" }, "||" };
yield return new object[] { '|', new object[] { null, null, null }, "||" };
}
[Theory]
[MemberData(nameof(Join_Char_ObjectArray_TestData))]
public static void Join_Char_ObjectArray(char separator, object[] values, string expected)
{
Assert.Equal(expected, string.Join(separator, values));
Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values));
}
[Fact]
public static void Join_Char_NullValues_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null));
AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (object[])null));
AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (IEnumerable<object>)null));
}
[Fact]
public static void Join_Char_NegativeStartIndex_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, -1, 0));
}
[Fact]
public static void Join_Char_NegativeCount_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => string.Join('|', new string[] { "Foo" }, 0, -1));
}
[Theory]
[InlineData(2, 1)]
[InlineData(2, 0)]
[InlineData(1, 2)]
[InlineData(1, 1)]
[InlineData(0, 2)]
[InlineData(-1, 0)]
public static void Join_Char_InvalidStartIndexCount_ThrowsArgumentOutOfRangeException(int startIndex, int count)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, startIndex, count));
}
public static IEnumerable<object[]> Replace_StringComparison_TestData()
{
yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCulture, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCulture, "abc" };
yield return new object[] { "abc", "abc", "", StringComparison.CurrentCulture, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCulture, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.CurrentCulture, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.CurrentCulture, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCulture, "def" };
yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCultureIgnoreCase, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCultureIgnoreCase, "def" };
yield return new object[] { "abc", "abc", "", StringComparison.CurrentCultureIgnoreCase, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCultureIgnoreCase, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.CurrentCultureIgnoreCase, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.CurrentCultureIgnoreCase, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCultureIgnoreCase, "def" };
yield return new object[] { "abc", "abc", "def", StringComparison.Ordinal, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.Ordinal, "abc" };
yield return new object[] { "abc", "abc", "", StringComparison.Ordinal, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.Ordinal, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.Ordinal, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.Ordinal, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.Ordinal, "abc" };
yield return new object[] { "abc", "abc", "def", StringComparison.OrdinalIgnoreCase, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.OrdinalIgnoreCase, "def" };
yield return new object[] { "abc", "abc", "", StringComparison.OrdinalIgnoreCase, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.OrdinalIgnoreCase, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.OrdinalIgnoreCase, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.OrdinalIgnoreCase, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.OrdinalIgnoreCase, "abc" };
yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCulture, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCulture, "abc" };
yield return new object[] { "abc", "abc", "", StringComparison.InvariantCulture, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCulture, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.InvariantCulture, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.InvariantCulture, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCulture, "def" };
yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCultureIgnoreCase, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCultureIgnoreCase, "def" };
yield return new object[] { "abc", "abc", "", StringComparison.InvariantCultureIgnoreCase, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCultureIgnoreCase, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.InvariantCultureIgnoreCase, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.InvariantCultureIgnoreCase, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCultureIgnoreCase, "def" };
string turkishSource = "\u0069\u0130";
yield return new object[] { turkishSource, "\u0069", "a", StringComparison.Ordinal, "a\u0130" };
yield return new object[] { turkishSource, "\u0069", "a", StringComparison.OrdinalIgnoreCase, "a\u0130" };
yield return new object[] { turkishSource, "\u0130", "a", StringComparison.Ordinal, "\u0069a" };
yield return new object[] { turkishSource, "\u0130", "a", StringComparison.OrdinalIgnoreCase, "\u0069a" };
yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCulture, "a\u0130" };
yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCultureIgnoreCase, "a\u0130" };
yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCulture, "\u0069a" };
yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCultureIgnoreCase, "\u0069a" };
}
[Theory]
[MemberData(nameof(Replace_StringComparison_TestData))]
public void Replace_StringComparison_ReturnsExpected(string original, string oldValue, string newValue, StringComparison comparisonType, string expected)
{
Assert.Equal(expected, original.Replace(oldValue, newValue, comparisonType));
}
[Fact]
public void Replace_StringComparison_TurkishI()
{
string src = "\u0069\u0130";
RemoteInvoke((source) =>
{
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
Assert.True("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase));
Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture));
Assert.Equal("aa", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase));
Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture));
Assert.Equal("aa", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase));
CultureInfo.CurrentCulture = new CultureInfo("en-US");
Assert.False("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase));
Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture));
Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase));
Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture));
Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase));
return SuccessExitCode;
}, src).Dispose();
}
public static IEnumerable<object[]> Replace_StringComparisonCulture_TestData()
{
yield return new object[] { "abc", "abc", "def", false, null, "def" };
yield return new object[] { "abc", "ABC", "def", false, null, "abc" };
yield return new object[] { "abc", "abc", "def", false, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "abc", "ABC", "def", false, CultureInfo.InvariantCulture, "abc" };
yield return new object[] { "abc", "abc", "def", true, null, "def" };
yield return new object[] { "abc", "ABC", "def", true, null, "def" };
yield return new object[] { "abc", "abc", "def", true, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "abc", "ABC", "def", true, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, null, "def" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, null, "def" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "\u0069\u0130", "\u0069", "a", false, new CultureInfo("tr-TR"), "a\u0130" };
yield return new object[] { "\u0069\u0130", "\u0069", "a", true, new CultureInfo("tr-TR"), "aa" };
yield return new object[] { "\u0069\u0130", "\u0069", "a", false, CultureInfo.InvariantCulture, "a\u0130" };
yield return new object[] { "\u0069\u0130", "\u0069", "a", true, CultureInfo.InvariantCulture, "a\u0130" };
}
[Theory]
[MemberData(nameof(Replace_StringComparisonCulture_TestData))]
public void Replace_StringComparisonCulture_ReturnsExpected(string original, string oldValue, string newValue, bool ignoreCase, CultureInfo culture, string expected)
{
Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, culture));
if (culture == null)
{
Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, CultureInfo.CurrentCulture));
}
}
[Fact]
public void Replace_StringComparison_NullOldValue_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", StringComparison.CurrentCulture));
AssertExtensions.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", true, CultureInfo.CurrentCulture));
}
[Fact]
public void Replace_StringComparison_EmptyOldValue_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", StringComparison.CurrentCulture));
AssertExtensions.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", true, CultureInfo.CurrentCulture));
}
[Theory]
[InlineData(StringComparison.CurrentCulture - 1)]
[InlineData(StringComparison.OrdinalIgnoreCase + 1)]
public void Replace_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType)
{
AssertExtensions.Throws<ArgumentException>("comparisonType", () => "abc".Replace("abc", "def", comparisonType));
}
private static readonly StringComparison[] StringComparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison));
public static IEnumerable<object[]> GetHashCode_StringComparison_Data => StringComparisons.Select(value => new object[] { value });
[Theory]
[MemberData(nameof(GetHashCode_StringComparison_Data))]
public static void GetHashCode_StringComparison(StringComparison comparisonType)
{
Assert.Equal(StringComparer.FromComparison(comparisonType).GetHashCode("abc"), "abc".GetHashCode(comparisonType));
}
public static IEnumerable<object[]> GetHashCode_NoSuchStringComparison_ThrowsArgumentException_Data => new[]
{
new object[] { StringComparisons.Min() - 1 },
new object[] { StringComparisons.Max() + 1 },
};
[Theory]
[MemberData(nameof(GetHashCode_NoSuchStringComparison_ThrowsArgumentException_Data))]
public static void GetHashCode_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType)
{
AssertExtensions.Throws<ArgumentException>("comparisonType", () => "abc".GetHashCode(comparisonType));
}
[Theory]
[InlineData("")]
[InlineData("a")]
[InlineData("\0")]
[InlineData("abc")]
public static unsafe void ImplicitCast_ResultingSpanMatches(string s)
{
ReadOnlySpan<char> span = s;
Assert.Equal(s.Length, span.Length);
fixed (char* stringPtr = s)
fixed (char* spanPtr = &MemoryMarshal.GetReference(span))
{
Assert.Equal((IntPtr)stringPtr, (IntPtr)spanPtr);
}
}
[Fact]
public static void ImplicitCast_NullString_ReturnsDefaultSpan()
{
ReadOnlySpan<char> span = (string)null;
Assert.True(span == default);
}
[Theory]
[InlineData("Hello", 'l', StringComparison.Ordinal, 2)]
[InlineData("Hello", 'x', StringComparison.Ordinal, -1)]
[InlineData("Hello", 'h', StringComparison.Ordinal, -1)]
[InlineData("Hello", 'o', StringComparison.Ordinal, 4)]
[InlineData("Hello", 'h', StringComparison.OrdinalIgnoreCase, 0)]
[InlineData("HelLo", 'L', StringComparison.OrdinalIgnoreCase, 2)]
[InlineData("HelLo", 'L', StringComparison.Ordinal, 3)]
[InlineData("HelLo", '\0', StringComparison.Ordinal, -1)]
[InlineData("!@#$%", '%', StringComparison.Ordinal, 4)]
[InlineData("!@#$", '!', StringComparison.Ordinal, 0)]
[InlineData("!@#$", '@', StringComparison.Ordinal, 1)]
[InlineData("!@#$%", '%', StringComparison.OrdinalIgnoreCase, 4)]
[InlineData("!@#$", '!', StringComparison.OrdinalIgnoreCase, 0)]
[InlineData("!@#$", '@', StringComparison.OrdinalIgnoreCase, 1)]
[InlineData("_____________\u807f", '\u007f', StringComparison.Ordinal, -1)]
[InlineData("_____________\u807f__", '\u007f', StringComparison.Ordinal, -1)]
[InlineData("_____________\u807f\u007f_", '\u007f', StringComparison.Ordinal, 14)]
[InlineData("__\u807f_______________", '\u007f', StringComparison.Ordinal, -1)]
[InlineData("__\u807f___\u007f___________", '\u007f', StringComparison.Ordinal, 6)]
[InlineData("_____________\u807f", '\u007f', StringComparison.OrdinalIgnoreCase, -1)]
[InlineData("_____________\u807f__", '\u007f', StringComparison.OrdinalIgnoreCase, -1)]
[InlineData("_____________\u807f\u007f_", '\u007f', StringComparison.OrdinalIgnoreCase, 14)]
[InlineData("__\u807f_______________", '\u007f', StringComparison.OrdinalIgnoreCase, -1)]
[InlineData("__\u807f___\u007f___________", '\u007f', StringComparison.OrdinalIgnoreCase, 6)]
public static void IndexOf_SingleLetter(string s, char target, StringComparison stringComparison, int expected)
{
Assert.Equal(expected, s.IndexOf(target, stringComparison));
}
[Fact]
public static void IndexOf_TurkishI_TurkishCulture_Char()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
string s = "Turkish I \u0131s TROUBL\u0130NG!";
char value = '\u0130';
Assert.Equal(19, s.IndexOf(value));
Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
Assert.Equal(19, s.IndexOf(value, StringComparison.Ordinal));
Assert.Equal(19, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
value = '\u0131';
Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
return SuccessExitCode;
}).Dispose();
}
[Fact]
public static void IndexOf_TurkishI_InvariantCulture_Char()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string s = "Turkish I \u0131s TROUBL\u0130NG!";
char value = '\u0130';
Assert.Equal(19, s.IndexOf(value));
Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
value = '\u0131';
Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
return SuccessExitCode;
}).Dispose();
}
[Fact]
public static void IndexOf_TurkishI_EnglishUSCulture_Char()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
string s = "Turkish I \u0131s TROUBL\u0130NG!";
char value = '\u0130';
Assert.Equal(19, s.IndexOf(value));
Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
value = '\u0131';
Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
return SuccessExitCode;
}).Dispose();
}
[Fact]
public static void IndexOf_EquivalentDiacritics_EnglishUSCulture_Char()
{
RemoteInvoke(() =>
{
string s = "Exhibit a\u0300\u00C0";
char value = '\u00C0';
CultureInfo.CurrentCulture = new CultureInfo("en-US");
Assert.Equal(10, s.IndexOf(value));
Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
return SuccessExitCode;
}).Dispose();
}
[Fact]
public static void IndexOf_EquivalentDiacritics_InvariantCulture_Char()
{
RemoteInvoke(() =>
{
string s = "Exhibit a\u0300\u00C0";
char value = '\u00C0';
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Assert.Equal(10, s.IndexOf(value));
Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
return SuccessExitCode;
}).Dispose();
}
[Fact]
public static void IndexOf_CyrillicE_EnglishUSCulture_Char()
{
RemoteInvoke(() =>
{
string s = "Foo\u0400Bar";
char value = '\u0400';
CultureInfo.CurrentCulture = new CultureInfo("en-US");
Assert.Equal(3, s.IndexOf(value));
Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
Assert.Equal(3, s.IndexOf(value, StringComparison.Ordinal));
Assert.Equal(3, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
return SuccessExitCode;
}).Dispose();
}
[Fact]
public static void IndexOf_CyrillicE_InvariantCulture_Char()
{
RemoteInvoke(() =>
{
string s = "Foo\u0400Bar";
char value = '\u0400';
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Assert.Equal(3, s.IndexOf(value));
Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
return SuccessExitCode;
}).Dispose();
}
[Fact]
public static void IndexOf_Invalid_Char()
{
// Invalid comparison type
AssertExtensions.Throws<ArgumentException>("comparisonType", () => "foo".IndexOf('o', StringComparison.CurrentCulture - 1));
AssertExtensions.Throws<ArgumentException>("comparisonType", () => "foo".IndexOf('o', StringComparison.OrdinalIgnoreCase + 1));
}
}
}
| |
#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.Collections.Generic;
using System.Text;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
using System.Numerics;
#endif
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Tests.Bson;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
[TestFixture]
public class JPathExecuteTests : TestFixtureBase
{
[Test]
public void ParseWithEmptyArrayContent()
{
var json = @"{
'controls': [
{
'messages': {
'addSuggestion': {
'en-US': 'Add'
}
}
},
{
'header': {
'controls': []
},
'controls': [
{
'controls': [
{
'defaultCaption': {
'en-US': 'Sort by'
},
'sortOptions': [
{
'label': {
'en-US': 'Name'
}
}
]
}
]
}
]
}
]
}";
JObject jToken = JObject.Parse(json);
IList<JToken> tokens = jToken.SelectTokens("$..en-US").ToList();
Assert.AreEqual(3, tokens.Count);
Assert.AreEqual("Add", (string)tokens[0]);
Assert.AreEqual("Sort by", (string)tokens[1]);
Assert.AreEqual("Name", (string)tokens[2]);
}
[Test]
public void SelectTokenAfterEmptyContainer()
{
string json = @"{
'cont': [],
'test': 'no one will find me'
}";
JObject o = JObject.Parse(json);
IList<JToken> results = o.SelectTokens("$..test").ToList();
Assert.AreEqual(1, results.Count);
Assert.AreEqual("no one will find me", (string)results[0]);
}
[Test]
public void EvaluatePropertyWithRequired()
{
string json = "{\"bookId\":\"1000\"}";
JObject o = JObject.Parse(json);
string bookId = (string)o.SelectToken("bookId", true);
Assert.AreEqual("1000", bookId);
}
[Test]
public void EvaluateEmptyPropertyIndexer()
{
JObject o = new JObject(
new JProperty("", 1));
JToken t = o.SelectToken("['']");
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateEmptyString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("");
Assert.AreEqual(o, t);
t = o.SelectToken("['']");
Assert.AreEqual(null, t);
}
[Test]
public void EvaluateEmptyStringWithMatchingEmptyProperty()
{
JObject o = new JObject(
new JProperty(" ", 1));
JToken t = o.SelectToken("[' ']");
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWhitespaceString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken(" ");
Assert.AreEqual(o, t);
}
[Test]
public void EvaluateDollarString()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("$");
Assert.AreEqual(o, t);
}
[Test]
public void EvaluateDollarTypeString()
{
JObject o = new JObject(
new JProperty("$values", new JArray(1, 2, 3)));
JToken t = o.SelectToken("$values[1]");
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateSingleProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateWildcardProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1),
new JProperty("Blah2", 2));
IList<JToken> t = o.SelectTokens("$.*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void QuoteName()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("['Blah']");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(1, (int)t);
}
[Test]
public void EvaluateMissingProperty()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("Missing[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObject()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JToken t = o.SelectToken("[1]");
Assert.IsNull(t);
}
[Test]
public void EvaluateIndexerOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[1]", true); }, @"Index 1 not valid on JObject.");
}
[Test]
public void EvaluateWildcardIndexOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[*]", true); }, @"Index * not valid on JObject.");
}
[Test]
public void EvaluateSliceOnObjectWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[:]", true); }, @"Array slice is not valid on JObject.");
}
[Test]
public void EvaluatePropertyOnArray()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("BlahBlah");
Assert.IsNull(t);
}
[Test]
public void EvaluateMultipleResultsError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[0, 1]"); }, @"Path returned multiple tokens.");
}
[Test]
public void EvaluatePropertyOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("BlahBlah", true); }, @"Property 'BlahBlah' not valid on JArray.");
}
[Test]
public void EvaluateNoResultsWithMultipleArrayIndexes()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[9,10]", true); }, @"Index 9 outside the bounds of JArray.");
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxerWithError()
{
JConstructor c = new JConstructor("Blah");
ExceptionAssert.Throws<JsonException>(() => { c.SelectToken("[1]", true); }, @"Index 1 outside the bounds of JConstructor.");
}
[Test]
public void EvaluateConstructorOutOfBoundsIndxer()
{
JConstructor c = new JConstructor("Blah");
Assert.IsNull(c.SelectToken("[1]"));
}
[Test]
public void EvaluateMissingPropertyWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("Missing", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
public void EvaluatePropertyWithoutError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
JValue v = (JValue)o.SelectToken("Blah", true);
Assert.AreEqual(1, v.Value);
}
[Test]
public void EvaluateMissingPropertyIndexWithError()
{
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("['Missing','Missing2']", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
public void EvaluateMultiPropertyIndexOnArrayWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("['Missing','Missing2']", true); }, "Properties 'Missing', 'Missing2' not valid on JArray.");
}
[Test]
public void EvaluateArraySliceWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[99:]", true); }, "Array slice of 99 to * returned no results.");
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1:-19]", true); }, "Array slice of 1 to -19 returned no results.");
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:-19]", true); }, "Array slice of * to -19 returned no results.");
a = new JArray();
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:]", true); }, "Array slice of * to * returned no results.");
}
[Test]
public void EvaluateOutOfBoundsIndxer()
{
JArray a = new JArray(1, 2, 3, 4, 5);
JToken t = a.SelectToken("[1000].Ha");
Assert.IsNull(t);
}
[Test]
public void EvaluateArrayOutOfBoundsIndxerWithError()
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1000].Ha", true); }, "Index 1000 outside the bounds of JArray.");
}
[Test]
public void EvaluateArray()
{
JArray a = new JArray(1, 2, 3, 4);
JToken t = a.SelectToken("[1]");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(2, (int)t);
}
[Test]
public void EvaluateArraySlice()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
IList<JToken> t = null;
t = a.SelectTokens("[-3:]").ToList();
Assert.AreEqual(3, t.Count);
Assert.AreEqual(7, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(9, (int)t[2]);
t = a.SelectTokens("[-1:-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(9, (int)t[0]);
t = a.SelectTokens("[-2:-1]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(8, (int)t[0]);
t = a.SelectTokens("[1:1]").ToList();
Assert.AreEqual(0, t.Count);
t = a.SelectTokens("[1:2]").ToList();
Assert.AreEqual(1, t.Count);
Assert.AreEqual(2, (int)t[0]);
t = a.SelectTokens("[::-1]").ToList();
Assert.AreEqual(9, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(8, (int)t[1]);
Assert.AreEqual(7, (int)t[2]);
Assert.AreEqual(6, (int)t[3]);
Assert.AreEqual(5, (int)t[4]);
Assert.AreEqual(4, (int)t[5]);
Assert.AreEqual(3, (int)t[6]);
Assert.AreEqual(2, (int)t[7]);
Assert.AreEqual(1, (int)t[8]);
t = a.SelectTokens("[::-2]").ToList();
Assert.AreEqual(5, t.Count);
Assert.AreEqual(9, (int)t[0]);
Assert.AreEqual(7, (int)t[1]);
Assert.AreEqual(5, (int)t[2]);
Assert.AreEqual(3, (int)t[3]);
Assert.AreEqual(1, (int)t[4]);
}
[Test]
public void EvaluateWildcardArray()
{
JArray a = new JArray(1, 2, 3, 4);
List<JToken> t = a.SelectTokens("[*]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.AreEqual(3, (int)t[2]);
Assert.AreEqual(4, (int)t[3]);
}
[Test]
public void EvaluateArrayMultipleIndexes()
{
JArray a = new JArray(1, 2, 3, 4);
IEnumerable<JToken> t = a.SelectTokens("[1,2,0]");
Assert.IsNotNull(t);
Assert.AreEqual(3, t.Count());
Assert.AreEqual(2, (int)t.ElementAt(0));
Assert.AreEqual(3, (int)t.ElementAt(1));
Assert.AreEqual(1, (int)t.ElementAt(2));
}
[Test]
public void EvaluateScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
}
[Test]
public void EvaluateWildcardScan()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JArray a = new JArray(o1, o2);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(5, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
}
[Test]
public void EvaluateScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..Name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.AreEqual(1, (int)t[0]);
Assert.AreEqual(2, (int)t[1]);
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[2]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[3]));
}
[Test]
public void EvaluateWildcardScanNestResults()
{
JObject o1 = new JObject { { "Name", 1 } };
JObject o2 = new JObject { { "Name", 2 } };
JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } };
JArray a = new JArray(o1, o2, o3);
IList<JToken> t = a.SelectTokens("$..*").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(9, t.Count);
Assert.IsTrue(JToken.DeepEquals(a, t[0]));
Assert.IsTrue(JToken.DeepEquals(o1, t[1]));
Assert.AreEqual(1, (int)t[2]);
Assert.IsTrue(JToken.DeepEquals(o2, t[3]));
Assert.AreEqual(2, (int)t[4]);
Assert.IsTrue(JToken.DeepEquals(o3, t[5]));
Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[6]));
Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[7]));
Assert.AreEqual(3, (int)t[8]);
}
[Test]
public void EvaluateSinglePropertyReturningArray()
{
JObject o = new JObject(
new JProperty("Blah", new[] { 1, 2, 3 }));
JToken t = o.SelectToken("Blah");
Assert.IsNotNull(t);
Assert.AreEqual(JTokenType.Array, t.Type);
t = o.SelectToken("Blah[2]");
Assert.AreEqual(JTokenType.Integer, t.Type);
Assert.AreEqual(3, (int)t);
}
[Test]
public void EvaluateLastSingleCharacterProperty()
{
JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}");
string a2 = (string)o2.SelectToken("People[0].N");
Assert.AreEqual("Jeff", a2);
}
[Test]
public void ExistsQuery()
{
JArray a = new JArray(new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi2", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.hi ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ho")), t[0]));
}
[Test]
public void EqualsQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", "ho")),
new JObject(new JProperty("hi", "ha")));
IList<JToken> t = a.SelectTokens("[ ?( @.['hi'] == 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ha")), t[0]));
}
[Test]
public void NotEqualsQuery()
{
JArray a = new JArray(
new JArray(new JObject(new JProperty("hi", "ho"))),
new JArray(new JObject(new JProperty("hi", "ha"))));
IList<JToken> t = a.SelectTokens("[ ?( @..hi <> 'ha' ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(1, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(new JObject(new JProperty("hi", "ho"))), t[0]));
}
[Test]
public void NoPathQuery()
{
JArray a = new JArray(1, 2, 3);
IList<JToken> t = a.SelectTokens("[ ?( @ > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual(2, (int)t[0]);
Assert.AreEqual(3, (int)t[1]);
}
[Test]
public void MultipleQueries()
{
JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9);
// json path does item based evaluation - http://www.sitepen.com/blog/2008/03/17/jsonpath-support/
// first query resolves array to ints
// int has no children to query
IList<JToken> t = a.SelectTokens("[?(@ <> 1)][?(@ <> 4)][?(@ < 7)]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(0, t.Count);
}
[Test]
public void GreaterQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20)
[Test]
public void GreaterQueryBigInteger()
{
JArray a = new JArray(
new JObject(new JProperty("hi", new BigInteger(1))),
new JObject(new JProperty("hi", new BigInteger(2))),
new JObject(new JProperty("hi", new BigInteger(3))));
IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#endif
[Test]
public void GreaterOrEqualQuery()
{
JArray a = new JArray(
new JObject(new JProperty("hi", 1)),
new JObject(new JProperty("hi", 2)),
new JObject(new JProperty("hi", 2.0)),
new JObject(new JProperty("hi", 3)));
IList<JToken> t = a.SelectTokens("[ ?( @.hi >= 1 ) ]").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(4, t.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 1)), t[0]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[1]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2.0)), t[2]));
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[3]));
}
[Test]
public void NestedQuery()
{
JArray a = new JArray(
new JObject(
new JProperty("name", "Bad Boys"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "Independence Day"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Will Smith"))))),
new JObject(
new JProperty("name", "The Rock"),
new JProperty("cast", new JArray(
new JObject(new JProperty("name", "Nick Cage")))))
);
IList<JToken> t = a.SelectTokens("[?(@.cast[?(@.name=='Will Smith')])].name").ToList();
Assert.IsNotNull(t);
Assert.AreEqual(2, t.Count);
Assert.AreEqual("Bad Boys", (string)t[0]);
Assert.AreEqual("Independence Day", (string)t[1]);
}
[Test]
public void PathWithConstructor()
{
JArray a = JArray.Parse(@"[
{
""Property1"": [
1,
[
[
[]
]
]
]
},
{
""Property2"": new Constructor1(
null,
[
1
]
)
}
]");
JValue v = (JValue)a.SelectToken("[1].Property2[1][0]");
Assert.AreEqual(1L, v.Value);
}
[Test]
public void QueryAgainstNonStringValues()
{
IList<object> values = new List<object>
{
"ff2dc672-6e15-4aa2-afb0-18f4f69596ad",
new Guid("ff2dc672-6e15-4aa2-afb0-18f4f69596ad"),
"http://localhost",
new Uri("http://localhost"),
"2000-12-05T05:07:59Z",
new DateTime(2000, 12, 5, 5, 7, 59, DateTimeKind.Utc),
#if !NET20
"2000-12-05T05:07:59-10:00",
new DateTimeOffset(2000, 12, 5, 5, 7, 59, -TimeSpan.FromHours(10)),
#endif
"SGVsbG8gd29ybGQ=",
Encoding.UTF8.GetBytes("Hello world"),
"365.23:59:59",
new TimeSpan(365, 23, 59, 59)
};
JObject o = new JObject(
new JProperty("prop",
new JArray(
values.Select(v => new JObject(new JProperty("childProp", v)))
)
)
);
IList<JToken> t = o.SelectTokens("$.prop[?(@.childProp =='ff2dc672-6e15-4aa2-afb0-18f4f69596ad')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='http://localhost')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59Z')]").ToList();
Assert.AreEqual(2, t.Count);
#if !NET20
t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59-10:00')]").ToList();
Assert.AreEqual(2, t.Count);
#endif
t = o.SelectTokens("$.prop[?(@.childProp =='SGVsbG8gd29ybGQ=')]").ToList();
Assert.AreEqual(2, t.Count);
t = o.SelectTokens("$.prop[?(@.childProp =='365.23:59:59')]").ToList();
Assert.AreEqual(2, t.Count);
}
[Test]
public void Example()
{
JObject o = JObject.Parse(@"{
""Stores"": [
""Lambton Quay"",
""Willis Street""
],
""Manufacturers"": [
{
""Name"": ""Acme Co"",
""Products"": [
{
""Name"": ""Anvil"",
""Price"": 50
}
]
},
{
""Name"": ""Contoso"",
""Products"": [
{
""Name"": ""Elbow Grease"",
""Price"": 99.95
},
{
""Name"": ""Headlight Fluid"",
""Price"": 4
}
]
}
]
}");
string name = (string)o.SelectToken("Manufacturers[0].Name");
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
Assert.AreEqual("Acme Co", name);
Assert.AreEqual(50m, productPrice);
Assert.AreEqual("Elbow Grease", productName);
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95
Assert.AreEqual(2, storeNames.Count);
Assert.AreEqual("Lambton Quay", storeNames[0]);
Assert.AreEqual("Willis Street", storeNames[1]);
Assert.AreEqual(2, firstProductNames.Count);
Assert.AreEqual(null, firstProductNames[0]);
Assert.AreEqual("Headlight Fluid", firstProductNames[1]);
Assert.AreEqual(149.95m, totalPrice);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using ClientDependency.Core.Config;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Web.Features;
using Umbraco.Web.HealthCheck;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Mvc;
using Umbraco.Web.PropertyEditors;
using Umbraco.Web.Trees;
using Umbraco.Web.WebServices;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Editors
{
/// <summary>
/// Used to collect the server variables for use in the back office angular app
/// </summary>
internal class BackOfficeServerVariables
{
private readonly UrlHelper _urlHelper;
private readonly ApplicationContext _applicationContext;
private readonly HttpContextBase _httpContext;
private readonly IOwinContext _owinContext;
public BackOfficeServerVariables(UrlHelper urlHelper, ApplicationContext applicationContext, IUmbracoSettingsSection umbracoSettings)
{
_urlHelper = urlHelper;
_applicationContext = applicationContext;
_httpContext = _urlHelper.RequestContext.HttpContext;
_owinContext = _httpContext.GetOwinContext();
}
/// <summary>
/// Returns the server variables for non-authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> BareMinimumServerVariables()
{
//this is the filter for the keys that we'll keep based on the full version of the server vars
var keepOnlyKeys = new Dictionary<string, string[]>
{
{"umbracoUrls", new[] {"authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl"}},
{"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage"}},
{"application", new[] {"applicationPath", "cacheBuster"}},
{"isDebuggingEnabled", new string[] { }},
{"features", new [] {"disabledFeatures"}}
};
//now do the filtering...
var defaults = GetServerVariables();
foreach (var key in defaults.Keys.ToArray())
{
if (keepOnlyKeys.ContainsKey(key) == false)
{
defaults.Remove(key);
}
else
{
var asDictionary = defaults[key] as IDictionary;
if (asDictionary != null)
{
var toKeep = keepOnlyKeys[key];
foreach (var k in asDictionary.Keys.Cast<string>().ToArray())
{
if (toKeep.Contains(k) == false)
{
asDictionary.Remove(k);
}
}
}
}
}
//TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
// so based on compat and how things are currently working we need to replace the serverVarsJs one
((Dictionary<string, object>)defaults["umbracoUrls"])["serverVarsJs"] = _urlHelper.Action("ServerVariables", "BackOffice");
return defaults;
}
/// <summary>
/// Returns the server variables for authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> GetServerVariables()
{
var defaultVals = new Dictionary<string, object>
{
{
"umbracoUrls", new Dictionary<string, object>
{
//TODO: Add 'umbracoApiControllerBaseUrl' which people can use in JS
// to prepend their URL. We could then also use this in our own resources instead of
// having each url defined here explicitly - we can do that in v8! for now
// for umbraco services we'll stick to explicitly defining the endpoints.
{"externalLoginsUrl", _urlHelper.Action("ExternalLogin", "BackOffice")},
{"externalLinkLoginsUrl", _urlHelper.Action("LinkLogin", "BackOffice")},
{"legacyTreeJs", _urlHelper.Action("LegacyTreeJs", "BackOffice")},
{"manifestAssetList", _urlHelper.Action("GetManifestAssetList", "BackOffice")},
{"gridConfig", _urlHelper.Action("GetGridConfig", "BackOffice")},
//TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
{"serverVarsJs", _urlHelper.Action("Application", "BackOffice")},
//API URLs
{
"packagesRestApiBaseUrl", Constants.PackageRepository.RestApiBaseUrl
},
{
"redirectUrlManagementApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RedirectUrlManagementController>(
controller => controller.GetEnableState())
},
{
"tourApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TourController>(
controller => controller.GetTours())
},
{
"embedApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RteEmbedController>(
controller => controller.GetEmbed("", 0, 0))
},
{
"userApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UsersController>(
controller => controller.PostSaveUser(null))
},
{
"userGroupsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UserGroupsController>(
controller => controller.PostSaveUserGroup(null))
},
{
"contentApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentController>(
controller => controller.PostSave(null))
},
{
"mediaApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaController>(
controller => controller.GetRootMedia())
},
{
"imagesApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ImagesController>(
controller => controller.GetBigThumbnail(0))
},
{
"sectionApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<SectionController>(
controller => controller.GetSections())
},
{
"treeApplicationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ApplicationTreeController>(
controller => controller.GetApplicationTrees(null, null, null, true))
},
{
"contentTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"mediaTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MacroController>(
controller => controller.GetMacroParameters(0))
},
{
"authenticationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<AuthenticationController>(
controller => controller.PostLogin(null))
},
{
"currentUserApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CurrentUserController>(
controller => controller.PostChangePassword(null))
},
{
"legacyApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LegacyController>(
controller => controller.DeleteLegacyItem(null, null, null))
},
{
"entityApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<EntityController>(
controller => controller.GetById(0, UmbracoEntityTypes.Media))
},
{
"dataTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DataTypeController>(
controller => controller.GetById(0))
},
{
"dashboardApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DashboardController>(
controller => controller.GetDashboard(null))
},
{
"logApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LogController>(
controller => controller.GetEntityLog(0))
},
{
"memberApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberController>(
controller => controller.GetByKey(Guid.Empty))
},
{
"packageInstallApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<PackageInstallController>(
controller => controller.Fetch(string.Empty))
},
{
"relationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RelationController>(
controller => controller.GetById(0))
},
{
"rteApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RichTextPreValueController>(
controller => controller.GetConfiguration())
},
{
"stylesheetApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<StylesheetController>(
controller => controller.GetAll())
},
{
"memberTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTypeController>(
controller => controller.GetAllTypes())
},
{
"updateCheckApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UpdateCheckController>(
controller => controller.GetCheck())
},
{
"tagApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsController>(
controller => controller.GetAllTags(null))
},
{
"templateApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateController>(
controller => controller.GetById(0))
},
{
"memberTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"mediaTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"contentTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"tagsDataBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsDataController>(
controller => controller.GetTags(""))
},
{
"examineMgmtBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ExamineManagementApiController>(
controller => controller.GetIndexerDetails())
},
{
"xmlDataIntegrityBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<XmlDataIntegrityController>(
controller => controller.CheckContentXmlTable())
},
{
"healthCheckBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HealthCheckController>(
controller => controller.GetAllHealthChecks())
},
{
"templateQueryApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateQueryController>(
controller => controller.PostTemplateQuery(null))
},
{
"codeFileApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CodeFileController>(
controller => controller.GetByPath("", ""))
},
{
"helpApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HelpController>(
controller => controller.GetContextHelpForPage("","",""))
},
{
"backOfficeAssetsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<BackOfficeAssetsController>(
controller => controller.GetSupportedMomentLocales())
}
}
},
{
"umbracoSettings", new Dictionary<string, object>
{
{"umbracoPath", GlobalSettings.Path},
{"mediaPath", IOHelper.ResolveUrl(SystemDirectories.Media).TrimEnd('/')},
{"appPluginsPath", IOHelper.ResolveUrl(SystemDirectories.AppPlugins).TrimEnd('/')},
{
"imageFileTypes",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes)
},
{
"disallowedUploadFiles",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles)
},
{
"allowedUploadFiles",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.AllowedUploadFiles)
},
{
"maxFileSize",
GetMaxRequestLength()
},
{"keepUserLoggedIn", UmbracoConfig.For.UmbracoSettings().Security.KeepUserLoggedIn},
{"usernameIsEmail", UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail},
{"cssPath", IOHelper.ResolveUrl(SystemDirectories.Css).TrimEnd('/')},
{"allowPasswordReset", UmbracoConfig.For.UmbracoSettings().Security.AllowPasswordReset},
{"loginBackgroundImage", UmbracoConfig.For.UmbracoSettings().Content.LoginBackgroundImage},
{"showUserInvite", EmailSender.CanSendRequiredEmail},
}
},
{
"umbracoPlugins", new Dictionary<string, object>
{
{"trees", GetTreePluginsMetaData()}
}
},
{
"isDebuggingEnabled", _httpContext.IsDebuggingEnabled
},
{
"application", GetApplicationState()
},
{
"externalLogins", new Dictionary<string, object>
{
{
"providers", _owinContext.Authentication.GetExternalAuthenticationTypes()
.Where(p => p.Properties.ContainsKey("UmbracoBackOffice"))
.Select(p => new
{
authType = p.AuthenticationType, caption = p.Caption,
//TODO: Need to see if this exposes any sensitive data!
properties = p.Properties
})
.ToArray()
}
}
},
{
"features", new Dictionary<string,object>
{
{
"disabledFeatures", new Dictionary<string,object>
{
{ "disableTemplates", FeaturesResolver.Current.Features.Disabled.DisableTemplates}
}
}
}
}
};
return defaultVals;
}
private IEnumerable<Dictionary<string, string>> GetTreePluginsMetaData()
{
var treeTypes = TreeControllerTypes.Value;
//get all plugin trees with their attributes
var treesWithAttributes = treeTypes.Select(x => new
{
tree = x,
attributes =
x.GetCustomAttributes(false)
}).ToArray();
var pluginTreesWithAttributes = treesWithAttributes
//don't resolve any tree decorated with CoreTreeAttribute
.Where(x => x.attributes.All(a => (a is CoreTreeAttribute) == false))
//we only care about trees with the PluginControllerAttribute
.Where(x => x.attributes.Any(a => a is PluginControllerAttribute))
.ToArray();
return (from p in pluginTreesWithAttributes
let treeAttr = p.attributes.OfType<TreeAttribute>().Single()
let pluginAttr = p.attributes.OfType<PluginControllerAttribute>().Single()
select new Dictionary<string, string>
{
{"alias", treeAttr.Alias}, {"packageFolder", pluginAttr.AreaName}
}).ToArray();
}
/// <summary>
/// A lazy reference to all tree controller types
/// </summary>
/// <remarks>
/// We are doing this because if we constantly resolve the tree controller types from the PluginManager it will re-scan and also re-log that
/// it's resolving which is unecessary and annoying.
/// </remarks>
private static readonly Lazy<IEnumerable<Type>> TreeControllerTypes = new Lazy<IEnumerable<Type>>(() => PluginManager.Current.ResolveAttributedTreeControllers().ToArray());
/// <summary>
/// Returns the server variables regarding the application state
/// </summary>
/// <returns></returns>
private Dictionary<string, object> GetApplicationState()
{
var app = new Dictionary<string, object>
{
{"assemblyVersion", UmbracoVersion.AssemblyVersion}
};
var version = UmbracoVersion.GetSemanticVersion().ToSemanticString();
//the value is the hash of the version, cdf version and the configured state
app.Add("cacheBuster", $"{version}.{_applicationContext.IsConfigured}.{ClientDependencySettings.Instance.Version}".GenerateHash());
app.Add("version", version);
//useful for dealing with virtual paths on the client side when hosted in virtual directories especially
app.Add("applicationPath", _httpContext.Request.ApplicationPath.EnsureEndsWith('/'));
//add the server's GMT time offset in minutes
app.Add("serverTimeOffset", Convert.ToInt32(DateTimeOffset.Now.Offset.TotalMinutes));
return app;
}
private string GetMaxRequestLength()
{
var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
if (section == null) return string.Empty;
return section.MaxRequestLength.ToString();
}
}
}
| |
// Copyright (C) 2004-2007 MySQL AB
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as published by
// the Free Software Foundation
//
// There are special exceptions to the terms and conditions of the GPL
// as it is applied to this software. View the full text of the
// exception in file EXCEPTIONS in the directory of this software
// distribution.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections;
using System.Text;
namespace MySql.Data.MySqlClient
{
/// <summary>
/// Summary description for PreparedStatement.
/// </summary>
internal class PreparableStatement : Statement
{
private MySqlField[] paramList;
private int executionCount;
private int statementId;
public PreparableStatement(MySqlCommand command, string text)
: base(command, text)
{
}
#region Properties
public int NumParameters
{
get { return paramList.Length; }
}
public int ExecutionCount
{
get { return executionCount; }
set { executionCount = value; }
}
public bool IsPrepared
{
get { return statementId > 0; }
}
public int StatementId
{
get { return statementId; }
}
#endregion
public virtual void Prepare()
{
// strip out names from parameter markers
string text;
ArrayList parameter_names = PrepareCommandText(out text);
// ask our connection to send the prepare command
statementId = Driver.PrepareStatement(text, ref paramList);
// now we need to assign our field names since we stripped them out
// for the prepare
for (int i = 0; i < parameter_names.Count; i++)
paramList[i].ColumnName = (string) parameter_names[i];
}
public override void Execute()
{
// if we are not prepared, then call down to our base
if (!IsPrepared)
{
base.Execute();
return;
}
MySqlStream stream = new MySqlStream(Driver.Encoding);
//TODO: support long data here
// create our null bitmap
BitArray nullMap = new BitArray(Parameters.Count);
// now we run through the parameters that PREPARE sent back and use
// those names to index into the parameters the user gave us.
// if the user set that parameter to NULL, then we set the null map
// accordingly
if (paramList != null)
for (int x = 0; x < paramList.Length; x++)
{
MySqlParameter p = Parameters[paramList[x].ColumnName];
if (p.Value == DBNull.Value || p.Value == null)
nullMap[x] = true;
}
byte[] nullMapBytes = new byte[(Parameters.Count + 7)/8];
// we check this because Mono doesn't ignore the case where nullMapBytes
// is zero length.
if (nullMapBytes.Length > 0)
nullMap.CopyTo(nullMapBytes, 0);
// start constructing our packet
stream.WriteInteger(statementId, 4);
stream.WriteByte(0); // flags; always 0 for 4.1
stream.WriteInteger(1, 4); // interation count; 1 for 4.1
stream.Write(nullMapBytes);
//if (parameters != null && parameters.Count > 0)
stream.WriteByte(1); // rebound flag
//else
// packet.WriteByte( 0 );
//TODO: only send rebound if parms change
// write out the parameter types
if (paramList != null)
{
foreach (MySqlField param in paramList)
{
MySqlParameter parm = Parameters[param.ColumnName];
stream.WriteInteger(parm.GetPSType(), 2);
}
// now write out all non-null values
foreach (MySqlField param in paramList)
{
int index = Parameters.IndexOf(param.ColumnName);
if (index == -1)
throw new MySqlException("Parameter '" + param.ColumnName +
"' is not defined.");
MySqlParameter parm = Parameters[index];
if (parm.Value == DBNull.Value || parm.Value == null)
continue;
stream.Encoding = param.Encoding;
parm.Serialize(stream, true);
}
}
executionCount++;
Driver.ExecuteStatement(stream.InternalBuffer.ToArray());
}
public override bool ExecuteNext()
{
if (!IsPrepared)
return base.ExecuteNext();
return false;
}
/// <summary>
/// Prepares CommandText for use with the Prepare method
/// </summary>
/// <returns>Command text stripped of all paramter names</returns>
/// <remarks>
/// Takes the output of TokenizeSql and creates a single string of SQL
/// that only contains '?' markers for each parameter. It also creates
/// the parameterMap array list that includes all the paramter names in the
/// order they appeared in the SQL
/// </remarks>
private ArrayList PrepareCommandText(out string stripped_sql)
{
StringBuilder newSQL = new StringBuilder();
ArrayList parameterMap = new ArrayList();
// tokenize the sql first
ArrayList tokens = TokenizeSql(ResolvedCommandText);
parameterMap.Clear();
foreach (string token in tokens)
{
if (token[0] != '@' && token[0] != '?')
newSQL.Append(token);
else
{
parameterMap.Add(token);
newSQL.Append("?");
}
}
stripped_sql = newSQL.ToString();
return parameterMap;
}
public virtual void CloseStatement()
{
if (!IsPrepared) return;
Driver.CloseStatement(statementId);
statementId = 0;
}
}
}
| |
using System;
using System.IO;
using System.Text;
using Abc.Zebus.Util;
namespace Abc.Zebus.Serialization.Protobuf
{
internal sealed class ProtoBufferWriter
{
internal static readonly Encoding Utf8Encoding = Encoding.UTF8;
public const int GuidSize = 18;
private byte[] _buffer;
private int _position;
private int? _savedPosition;
public ProtoBufferWriter() : this(new byte[4096])
{
}
public ProtoBufferWriter(byte[] buffer)
{
_buffer = buffer;
}
public byte[] Buffer => _buffer;
public int Position => _position;
public void Reset()
{
_position = 0;
_savedPosition = null;
}
public byte[] ToArray()
{
var buffer = new byte[_position];
ByteUtil.Copy(Buffer, 0, buffer, 0, _position);
return buffer;
}
public void SavePosition()
{
_savedPosition = _position;
}
public bool TryWriteBoolAtSavedPosition(bool value)
{
if (_savedPosition == null)
return false;
_buffer[_savedPosition.Value] = value ? (byte)1 : (byte)0;
return true;
}
public void WriteBool(bool value)
{
WriteRawByte(value ? (byte) 1 : (byte) 0);
}
public void WriteString(string value, int length)
{
WriteLength(length);
if (_buffer.Length - _position >= length)
{
if (length == value.Length)
{
for (int i = 0; i < length; i++)
{
_buffer[_position + i] = (byte)value[i];
}
}
else
{
Utf8Encoding.GetBytes(value, 0, value.Length, _buffer, _position);
}
_position += length;
}
else
{
byte[] bytes = Utf8Encoding.GetBytes(value);
WriteRawBytes(bytes);
}
}
public void WriteLength(int length)
{
WriteRawVarint32((uint) length);
}
public void WriteRawTag(byte b1)
{
WriteRawByte(b1);
}
internal void WriteRawVarint32(uint value)
{
if (value < 128 && _position < _buffer.Length)
{
_buffer[_position++] = (byte)value;
return;
}
while (value > 127 && _position < _buffer.Length)
{
_buffer[_position++] = (byte) ((value & 0x7F) | 0x80);
value >>= 7;
}
while (value > 127)
{
WriteRawByte((byte) ((value & 0x7F) | 0x80));
value >>= 7;
}
if (_position < _buffer.Length)
{
_buffer[_position++] = (byte) value;
}
else
{
WriteRawByte((byte) value);
}
}
internal void WriteRawByte(byte value)
{
EnsureCapacity(1);
_buffer[_position++] = value;
}
public void WriteGuid(Guid value)
{
EnsureCapacity(GuidSize + 1);
_buffer[_position++] = GuidSize;
var blob = value.ToByteArray();
_buffer[_position++] = 1 << 3 | 1;
for (var i = 0; i < 8; i++)
{
_buffer[_position++] = blob[i];
}
_buffer[_position++] = 2 << 3 | 1;
for (var i = 8; i < 16; i++)
{
_buffer[_position++] = blob[i];
}
}
internal void WriteRawBytes(byte[] value)
{
WriteRawBytes(value, 0, value.Length);
}
internal void WriteRawBytes(byte[] value, int offset, int length)
{
EnsureCapacity(length);
ByteUtil.Copy(value, offset, _buffer, _position, length);
_position += length;
}
public void WriteRawStream(Stream stream)
{
var length = (int)stream.Length;
EnsureCapacity(length);
stream.Position = 0;
var memoryStream = stream as MemoryStream;
if (memoryStream != null)
_position += memoryStream.Read(_buffer, _position, length);
else
WriteRawStreamSlow(stream);
}
private void WriteRawStreamSlow(Stream stream)
{
const int blockSize = 4096;
while (true)
{
var readCount = stream.Read(_buffer, _position, blockSize);
_position += readCount;
if (readCount != blockSize)
break;
}
}
private void EnsureCapacity(int length)
{
if (_buffer.Length - _position >= length)
return;
var newBufferLength = Math.Max(_position + length, _buffer.Length * 2);
var newBuffer = new byte[newBufferLength];
ByteUtil.Copy(_buffer, 0, newBuffer, 0, _buffer.Length);
_buffer = newBuffer;
}
public static int ComputeStringSize(int byteArraySize)
{
return ComputeLengthSize(byteArraySize) + byteArraySize;
}
public static int ComputeLengthSize(int length)
{
return ComputeRawVarint32Size((uint) length);
}
public static int ComputeRawVarint32Size(uint value)
{
if ((value & (0xffffffff << 7)) == 0)
{
return 1;
}
if ((value & (0xffffffff << 14)) == 0)
{
return 2;
}
if ((value & (0xffffffff << 21)) == 0)
{
return 3;
}
if ((value & (0xffffffff << 28)) == 0)
{
return 4;
}
return 5;
}
}
}
| |
using System;
using Android.App;
using Android.Views;
using Android.Graphics;
using System.Collections.Generic;
using Android.Views.InputMethods;
namespace Need2Park
{
class LoginView : UIView
{
UIImageView backgroundImage;
UITextField emailInput;
UITextField passwordInput;
UILabelButton loginButton;
UIView inputContainer;
UIView separator;
bool isLoginInProgess;
LoginActivity activity;
LoaderView loaderView;
public LoginView (LoginActivity activity) : base (activity)
{
this.activity = activity;
backgroundImage = new UIImageView (activity);
backgroundImage.ImageResource = Resource.Drawable.landing_backg;
backgroundImage.SetScaleType (Android.Widget.ImageView.ScaleType.CenterCrop);
backgroundImage.LayoutParameters = LayoutUtils.GetRelativeMatchParent ();
inputContainer = new UIView (activity);
inputContainer.SetRoundBordersWithColor (CustomColors.LightColor, Sizes.LoginInputHeight / 3, Sizes.LoginSeparatorSize);
FocusableInTouchMode = true;
emailInput = new UITextField (activity);
emailInput.Hint = "E - M A I L";
emailInput.Gravity = GravityFlags.Center;
emailInput.SetSingleLine ();
emailInput.InputType = Android.Text.InputTypes.TextVariationEmailAddress;
emailInput.TextSize = Sizes.GetRealSize (9);
emailInput.TextColor = CustomColors.LightColor;
emailInput.SetHintTextColor (CustomColors.LightColorDim);
emailInput.SetPadding (1, 1, 1, 1);
emailInput.ClearFocus ();
passwordInput = new UITextField (activity);
passwordInput.Hint = "P A S S W O R D";
passwordInput.Gravity = GravityFlags.Center;
passwordInput.SetSingleLine ();
passwordInput.InputType = Android.Text.InputTypes.TextVariationPassword;
passwordInput.TextSize = Sizes.GetRealSize (9);
passwordInput.TextColor = CustomColors.LightColor;
passwordInput.SetPadding (1, 1, 1, 1);
passwordInput.SetHintTextColor (CustomColors.LightColorDim);
separator = new UIView (activity);
separator.BackgroundColor = CustomColors.LightColor;
inputContainer.AddViews (
emailInput,
separator,
passwordInput
);
loginButton = new UILabelButton (activity);
loginButton.Text = "L O G I N";
loginButton.Gravity = GravityFlags.Center;
loginButton.BackgroundColor = CustomColors.DarkColor;
loginButton.TextSize = Sizes.GetRealSize (9);
loginButton.SetPadding (1, 1, 1, 1);
// loginButton.Font = Font.Get (FontStyle.Serif, 11);
loginButton.Measure (0, 0);
loginButton.TextColor = CustomColors.LightColor;
int radius = (int)(loginButton.MeasuredHeight * 0.7f);
loginButton.SetCornerRadiusWithColor (CustomColors.DarkColor,
new float[] {
0, 0,
0, 0,
radius, radius,
radius, radius
}
);
loaderView = new LoaderView (activity);
AddViews (
backgroundImage,
inputContainer,
loginButton,
loaderView
);
Frame = new Frame (DeviceInfo.ScreenWidth, DeviceInfo.ScreenHeight - DeviceInfo.StatusBarHeight);
loginButton.Click += HandleLoginClicked;
}
public override void LayoutSubviews ()
{
int containerHeight = 2 * Sizes.LoginInputHeight + Sizes.LoginSeparatorSize;
int loginButtonHeight = loginButton.MeasuredHeight + 4 * Sizes.LoginInputPadding;
int loginButtonWidth = loginButton.MeasuredWidth + 8 * Sizes.LoginInputPadding;
inputContainer.Frame = new Frame (
Sizes.LoginHorizontalPadding,
(Frame.H - containerHeight - loginButtonHeight) / 3,
Frame.W - 2 * Sizes.LoginHorizontalPadding,
containerHeight
);
emailInput.Frame = new Frame (
Sizes.LoginInputPadding,
0,
inputContainer.Frame.W - 2 * Sizes.LoginInputPadding,
Sizes.LoginInputHeight
);
separator.Frame = new Frame (
Sizes.LoginInputPadding,
emailInput.Frame.Bottom,
inputContainer.Frame.W - 2 * Sizes.LoginInputPadding,
Sizes.LoginSeparatorSize
);
passwordInput.Frame = new Frame (
Sizes.LoginInputPadding,
separator.Frame.Bottom,
inputContainer.Frame.W - 2 * Sizes.LoginInputPadding,
Sizes.LoginInputHeight
);
loginButton.Frame = new Frame (
(Frame.W - loginButtonWidth) / 2,
inputContainer.Frame.Bottom,
loginButtonWidth,
loginButtonHeight
);
loaderView.Frame = new Frame (
(Frame.W - Sizes.LoaderSize) / 2,
(int)((Frame.H - Sizes.LoaderSize) * 0.8f),
Sizes.LoaderSize,
Sizes.LoaderSize
);
}
async void HandleLoginClicked (object sender, EventArgs e)
{
emailInput.ClearFocus ();
passwordInput.ClearFocus ();
HideKeyboard ();
if (!isLoginInProgess) {
if (string.IsNullOrWhiteSpace (emailInput.Text)
|| string.IsNullOrWhiteSpace (passwordInput.Text)) {
// bad input
} else {
isLoginInProgess = true;
LoginRequest loginRequest = new LoginRequest {
Email = emailInput.Text,
Password = passwordInput.Text
};
loaderView.ShowAnimation ();
LoginResponse response = await Networking.SendLoginRequest (loginRequest);
if (string.IsNullOrEmpty (response.SessionId)) {
DialogUtils.CreateDialog (activity, "Oops!", "Failed to log in with these credentials.");
} else {
UserInfo user = new UserInfo {
Name = response.Name,
Email = response.email,
SessionId = response.SessionId
};
LoginState.ActiveUser = user;
activity.CacheUser (user);
List<ParkingLotInfo> parkingLotInfoList = await Networking.SendParkingLotsRequest ();
if (parkingLotInfoList != null) {
LoginState.ActiveUser.AccessInfo.AddRange (parkingLotInfoList);
} else {
// TODO handle failing in life
}
activity.Finish ();
}
isLoginInProgess = false;
loaderView.StopAnimating ();
}
}
}
const string inputMethod = "input_method";
void HideKeyboard ()
{
InputMethodManager manager = (InputMethodManager)activity.GetSystemService (inputMethod);
manager.HideSoftInputFromWindow (this.WindowToken, 0);
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using System.IO;
using System.Globalization;
using fyiReporting.RdlDesign.Resources;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Control supports the properties for DataSet/Rows elements. This is an extension to
/// the RDL specification allowing data to be defined within a report.
/// </summary>
internal partial class DataSetRowsCtl : System.Windows.Forms.UserControl, IProperty
{
private DesignXmlDraw _Draw;
private DataSetValues _dsv;
private XmlNode _dsNode;
private DataTable _DataTable;
internal DataSetRowsCtl(DesignXmlDraw dxDraw, XmlNode dsNode, DataSetValues dsv)
{
_Draw = dxDraw;
_dsv = dsv;
_dsNode = dsNode;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
CreateDataTable(); // create data table based on the existing fields
XmlNode rows = _Draw.GetNamedChildNode(_dsNode, "Rows");
if (rows == null)
rows = _Draw.GetNamedChildNode(_dsNode, "fyi:Rows");
string file=null;
if (rows != null)
{
file = _Draw.GetElementAttribute(rows, "File", null);
PopulateRows(rows);
}
this.dgRows.DataSource = _DataTable;
if (file != null)
{
tbRowsFile.Text = file;
this.chkRowsFile.Checked = true;
}
chkRowsFile_CheckedChanged(this, new EventArgs());
}
private void CreateDataTable()
{
_DataTable = new DataTable();
dgTableStyle.GridColumnStyles.Clear(); // reset the grid column styles
foreach (DataRow dr in _dsv.Fields.Rows)
{
if (dr[0] == DBNull.Value)
continue;
if (dr[2] == DBNull.Value)
{}
else if (((string) dr[2]).Length > 0)
continue;
string name = (string) dr[0];
DataGridTextBoxColumn dgc = new DataGridTextBoxColumn();
dgTableStyle.GridColumnStyles.Add(dgc);
dgc.HeaderText = name;
dgc.MappingName = name;
dgc.Width = 75;
string type = dr["TypeName"] as string;
Type t = type == null || type.Length == 0? typeof(string):
fyiReporting.RDL.DataType.GetStyleType(type);
_DataTable.Columns.Add(new DataColumn(name,t));
}
}
private void PopulateRows(XmlNode rows)
{
object[] rowValues = new object[_DataTable.Columns.Count];
bool bSkipMsg = false;
foreach (XmlNode rNode in rows.ChildNodes)
{
if (rNode.Name != "Row")
continue;
int col=0;
bool bBuiltRow=false; // if all columns will be null we won't add the row
foreach (DataColumn dc in _DataTable.Columns)
{
XmlNode dNode = _Draw.GetNamedChildNode(rNode, dc.ColumnName);
if (dNode != null)
bBuiltRow = true;
if (dNode == null)
rowValues[col] = null;
else if (dc.DataType == typeof(string))
rowValues[col] = dNode.InnerText;
else
{
object box;
try
{
if (dc.DataType == typeof(int))
box = Convert.ToInt32(dNode.InnerText, NumberFormatInfo.InvariantInfo);
else if (dc.DataType == typeof(decimal))
box = Convert.ToDecimal(dNode.InnerText, NumberFormatInfo.InvariantInfo);
else if (dc.DataType == typeof(long))
box = Convert.ToInt64(dNode.InnerText, NumberFormatInfo.InvariantInfo);
else if (DesignerUtility.IsNumeric(dc.DataType)) // catch all numeric
box = Convert.ToDouble(dNode.InnerText, NumberFormatInfo.InvariantInfo);
else if (dc.DataType == typeof(DateTime))
{
box = Convert.ToDateTime(dNode.InnerText,
System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
else
{
box = dNode.InnerText;
}
rowValues[col] = box;
}
catch (Exception e)
{
if (!bSkipMsg)
{
if (MessageBox.Show(string.Format(Strings.DataSetRowsCtl_ShowB_UnableConvert,
dc.DataType, dNode.InnerText, e.Message) + Environment.NewLine + Strings.DataSetRowsCtl_ShowB_WantSeeErrors,
Strings.DataSetRowsCtl_ShowB_ErrorReadingDataRows, MessageBoxButtons.YesNo) == DialogResult.No)
bSkipMsg = true;
}
rowValues[col] = dNode.InnerText;
}
}
col++;
}
if (bBuiltRow)
_DataTable.Rows.Add(rowValues);
}
}
public bool IsValid()
{
if (chkRowsFile.Checked && tbRowsFile.Text.Length == 0)
{
MessageBox.Show(Strings.DataSetRowsCtl_ShowC_FileNameRequired);
return false;
}
return true;
}
public void Apply()
{
// Remove the old row
XmlNode rows = _Draw.GetNamedChildNode(this._dsNode, "Rows");
if (rows == null)
rows = _Draw.GetNamedChildNode(this._dsNode, "fyi:Rows");
if (rows != null)
_dsNode.RemoveChild(rows);
// different result if we just want the file
if (this.chkRowsFile.Checked)
{
rows = _Draw.GetCreateNamedChildNode(_dsNode, "fyi:Rows");
_Draw.SetElementAttribute(rows, "File", this.tbRowsFile.Text);
}
else
{
rows = GetXmlData();
if (rows.HasChildNodes)
_dsNode.AppendChild(rows);
}
}
private void bDelete_Click(object sender, System.EventArgs e)
{
this._DataTable.Rows.RemoveAt(this.dgRows.CurrentRowIndex);
}
private void bUp_Click(object sender, System.EventArgs e)
{
int cr = dgRows.CurrentRowIndex;
if (cr <= 0) // already at the top
return;
SwapRow(_DataTable.Rows[cr-1], _DataTable.Rows[cr]);
dgRows.CurrentRowIndex = cr-1;
}
private void bDown_Click(object sender, System.EventArgs e)
{
int cr = dgRows.CurrentRowIndex;
if (cr < 0) // invalid index
return;
if (cr + 1 >= _DataTable.Rows.Count)
return; // already at end
SwapRow(_DataTable.Rows[cr+1], _DataTable.Rows[cr]);
dgRows.CurrentRowIndex = cr+1;
}
private void SwapRow(DataRow tdr, DataRow fdr)
{
// Loop thru all the columns in a row and swap the data
for (int ci=0; ci < _DataTable.Columns.Count; ci++)
{
object save = tdr[ci];
tdr[ci] = fdr[ci];
fdr[ci] = save;
}
return;
}
private void chkRowsFile_CheckedChanged(object sender, System.EventArgs e)
{
this.tbRowsFile.Enabled = chkRowsFile.Checked;
this.bRowsFile.Enabled = chkRowsFile.Checked;
this.bDelete.Enabled = !chkRowsFile.Checked;
this.bUp.Enabled = !chkRowsFile.Checked;
this.bDown.Enabled = !chkRowsFile.Checked;
this.dgRows.Enabled = !chkRowsFile.Checked;
}
private void bRowsFile_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = Strings.DataSetRowsCtl_bRowsFile_Click_XMLFilesFilter;
ofd.FilterIndex = 1;
ofd.FileName = "*.xml";
ofd.Title = Strings.DataSetRowsCtl_bRowsFile_Click_XMLFilesTitle;
ofd.DefaultExt = "xml";
ofd.AddExtension = true;
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
string file = Path.GetFileName(ofd.FileName);
this.tbRowsFile.Text = file;
}
}
finally
{
ofd.Dispose();
}
}
private bool DidFieldsChange()
{
int col=0;
foreach (DataRow dr in _dsv.Fields.Rows)
{
if (col >= _DataTable.Columns.Count)
return true;
if (dr[0] == DBNull.Value)
continue;
if (dr[2] == DBNull.Value)
{}
else if (((string) dr[2]).Length > 0)
continue;
string name = (string) (dr[1] == DBNull.Value? dr[0]: dr[1]);
if (_DataTable.Columns[col].ColumnName != name)
return true;
col++;
}
if (col == _DataTable.Columns.Count)
return false;
else
return true;
}
private XmlNode GetXmlData()
{
XmlDocumentFragment fDoc = _Draw.ReportDocument.CreateDocumentFragment();
XmlNode rows = _Draw.CreateElement(fDoc, "fyi:Rows", null);
foreach (DataRow dr in _DataTable.Rows)
{
XmlNode row = _Draw.CreateElement(rows, "Row", null);
bool bRowBuilt=false;
foreach (DataColumn dc in _DataTable.Columns)
{
if (dr[dc] == DBNull.Value)
continue;
string val;
if (dc.DataType == typeof(DateTime))
{
val = Convert.ToString(dr[dc],
System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
else
{
val = Convert.ToString(dr[dc], NumberFormatInfo.InvariantInfo);
}
if (val == null)
continue;
_Draw.CreateElement(row, dc.ColumnName, val);
bRowBuilt = true; // we've populated at least one column; so keep row
}
if (!bRowBuilt)
rows.RemoveChild(row);
}
return rows;
}
private void DataSetRowsCtl_VisibleChanged(object sender, System.EventArgs e)
{
if (!DidFieldsChange()) // did the structure of the fields change
return;
// Need to reset the data; this assumes that some of the data rows are similar
XmlNode rows = GetXmlData(); // get old data
CreateDataTable(); // this recreates the datatable
PopulateRows(rows); // repopulate the datatable
this.dgRows.DataSource = _DataTable; // this recreates the datatable so reset grid
}
private void bClear_Click(object sender, System.EventArgs e)
{
this._DataTable.Rows.Clear();
}
private void bLoad_Click(object sender, System.EventArgs e)
{
// Load the data from the SQL; we append the data to what already exists
try
{
// Obtain the connection information
XmlNode rNode = _Draw.GetReportNode();
XmlNode dsNode = _Draw.GetNamedChildNode(rNode, "DataSources");
if (dsNode == null)
return;
XmlNode datasource=null;
foreach (XmlNode dNode in dsNode)
{
if (dNode.Name != "DataSource")
continue;
XmlAttribute nAttr = dNode.Attributes["Name"];
if (nAttr == null) // shouldn't really happen
continue;
if (nAttr.Value != _dsv.DataSourceName)
continue;
datasource = dNode;
break;
}
if (datasource == null)
{
MessageBox.Show(string.Format(Strings.DataSetRowsCtl_Show_DatasourceNotFound, _dsv.DataSourceName), Strings.DataSetRowsCtl_Show_LoadFailed);
return;
}
// get the connection information
string connection = "";
string dataProvider = "";
string dataSourceReference = _Draw.GetElementValue(datasource, "DataSourceReference", null);
if (dataSourceReference != null)
{
// This is not very pretty code since it is assuming the structure of the windows parenting.
// But there isn't any other way to get this information from here.
Control p = _Draw;
MDIChild mc = null;
while (p != null && !(p is RdlDesigner))
{
if (p is MDIChild)
mc = (MDIChild)p;
p = p.Parent;
}
if (p == null || mc == null || mc.SourceFile == null)
{
MessageBox.Show(Strings.DataSetRowsCtl_ShowC_UnableLocateDSR);
return;
}
Uri filename = new Uri(Path.GetDirectoryName(mc.SourceFile.LocalPath) + Path.DirectorySeparatorChar + dataSourceReference);
if (!DesignerUtility.GetSharedConnectionInfo((RdlDesigner)p, filename.LocalPath, out dataProvider, out connection))
{
return;
}
}
else
{
XmlNode cpNode = DesignXmlDraw.FindNextInHierarchy(datasource, "ConnectionProperties", "ConnectString");
connection = cpNode == null ? "" : cpNode.InnerText;
XmlNode datap = DesignXmlDraw.FindNextInHierarchy(datasource, "ConnectionProperties", "DataProvider");
dataProvider = datap == null ? "" : datap.InnerText;
}
// Populate the data table
DesignerUtility.GetSqlData(dataProvider, connection, _dsv.CommandText, null, _DataTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DataSetRowsCtl_Show_LoadFailed);
}
}
}
}
| |
/*
* 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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps=OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.CoreModules.Framework
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CapabilitiesModule")]
public class CapabilitiesModule : INonSharedRegionModule, ICapabilitiesModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_showCapsCommandFormat = " {0,-38} {1,-60}\n";
protected Scene m_scene;
/// <summary>
/// Each agent has its own capabilities handler.
/// </summary>
protected Dictionary<UUID, Caps> m_capsObjects = new Dictionary<UUID, Caps>();
protected Dictionary<UUID, string> m_capsPaths = new Dictionary<UUID, string>();
protected Dictionary<UUID, Dictionary<ulong, string>> m_childrenSeeds
= new Dictionary<UUID, Dictionary<ulong, string>>();
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<ICapabilitiesModule>(this);
MainConsole.Instance.Commands.AddCommand(
"Comms", false, "show caps list",
"show caps list",
"Shows list of registered capabilities for users.", HandleShowCapsListCommand);
MainConsole.Instance.Commands.AddCommand(
"Comms", false, "show caps stats by user",
"show caps stats by user [<first-name> <last-name>]",
"Shows statistics on capabilities use by user.",
"If a user name is given, then prints a detailed breakdown of caps use ordered by number of requests received.",
HandleShowCapsStatsByUserCommand);
MainConsole.Instance.Commands.AddCommand(
"Comms", false, "show caps stats by cap",
"show caps stats by cap [<cap-name>]",
"Shows statistics on capabilities use by capability.",
"If a capability name is given, then prints a detailed breakdown of use by each user.",
HandleShowCapsStatsByCapCommand);
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
m_scene.UnregisterModuleInterface<ICapabilitiesModule>(this);
}
public void PostInitialise()
{
}
public void Close() {}
public string Name
{
get { return "Capabilities Module"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void CreateCaps(UUID agentId)
{
if (m_scene.RegionInfo.EstateSettings.IsBanned(agentId))
return;
Caps caps;
String capsObjectPath = GetCapsPath(agentId);
lock (m_capsObjects)
{
if (m_capsObjects.ContainsKey(agentId))
{
Caps oldCaps = m_capsObjects[agentId];
//m_log.WarnFormat(
// "[CAPS]: Recreating caps for agent {0} in region {1}. Old caps path {2}, new caps path {3}. ",
// agentId, m_scene.RegionInfo.RegionName, oldCaps.CapsObjectPath, capsObjectPath);
}
caps = new Caps(MainServer.Instance, m_scene.RegionInfo.ExternalHostName,
(MainServer.Instance == null) ? 0: MainServer.Instance.Port,
capsObjectPath, agentId, m_scene.RegionInfo.RegionName);
m_capsObjects[agentId] = caps;
}
m_scene.EventManager.TriggerOnRegisterCaps(agentId, caps);
}
public void RemoveCaps(UUID agentId)
{
m_log.DebugFormat("[CAPS]: Remove caps for agent {0} in region {1}", agentId, m_scene.RegionInfo.RegionName);
lock (m_childrenSeeds)
{
if (m_childrenSeeds.ContainsKey(agentId))
{
m_childrenSeeds.Remove(agentId);
}
}
lock (m_capsObjects)
{
if (m_capsObjects.ContainsKey(agentId))
{
m_capsObjects[agentId].DeregisterHandlers();
m_scene.EventManager.TriggerOnDeregisterCaps(agentId, m_capsObjects[agentId]);
m_capsObjects.Remove(agentId);
}
else
{
m_log.WarnFormat(
"[CAPS]: Received request to remove CAPS handler for root agent {0} in {1}, but no such CAPS handler found!",
agentId, m_scene.RegionInfo.RegionName);
}
}
}
public Caps GetCapsForUser(UUID agentId)
{
lock (m_capsObjects)
{
if (m_capsObjects.ContainsKey(agentId))
{
return m_capsObjects[agentId];
}
}
return null;
}
public void SetAgentCapsSeeds(AgentCircuitData agent)
{
lock (m_capsPaths)
m_capsPaths[agent.AgentID] = agent.CapsPath;
lock (m_childrenSeeds)
m_childrenSeeds[agent.AgentID]
= ((agent.ChildrenCapSeeds == null) ? new Dictionary<ulong, string>() : agent.ChildrenCapSeeds);
}
public string GetCapsPath(UUID agentId)
{
lock (m_capsPaths)
{
if (m_capsPaths.ContainsKey(agentId))
{
return m_capsPaths[agentId];
}
}
return null;
}
public Dictionary<ulong, string> GetChildrenSeeds(UUID agentID)
{
Dictionary<ulong, string> seeds = null;
lock (m_childrenSeeds)
if (m_childrenSeeds.TryGetValue(agentID, out seeds))
return seeds;
return new Dictionary<ulong, string>();
}
public void DropChildSeed(UUID agentID, ulong handle)
{
Dictionary<ulong, string> seeds;
lock (m_childrenSeeds)
{
if (m_childrenSeeds.TryGetValue(agentID, out seeds))
{
seeds.Remove(handle);
}
}
}
public string GetChildSeed(UUID agentID, ulong handle)
{
Dictionary<ulong, string> seeds;
string returnval;
lock (m_childrenSeeds)
{
if (m_childrenSeeds.TryGetValue(agentID, out seeds))
{
if (seeds.TryGetValue(handle, out returnval))
return returnval;
}
}
return null;
}
public void SetChildrenSeed(UUID agentID, Dictionary<ulong, string> seeds)
{
//m_log.DebugFormat(" !!! Setting child seeds in {0} to {1}", m_scene.RegionInfo.RegionName, seeds.Count);
lock (m_childrenSeeds)
m_childrenSeeds[agentID] = seeds;
}
public void DumpChildrenSeeds(UUID agentID)
{
m_log.Info("================ ChildrenSeed "+m_scene.RegionInfo.RegionName+" ================");
lock (m_childrenSeeds)
{
foreach (KeyValuePair<ulong, string> kvp in m_childrenSeeds[agentID])
{
uint x, y;
Utils.LongToUInts(kvp.Key, out x, out y);
x = x / Constants.RegionSize;
y = y / Constants.RegionSize;
m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
}
}
}
private void HandleShowCapsListCommand(string module, string[] cmdParams)
{
if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
return;
StringBuilder capsReport = new StringBuilder();
capsReport.AppendFormat("Region {0}:\n", m_scene.RegionInfo.RegionName);
lock (m_capsObjects)
{
foreach (KeyValuePair<UUID, Caps> kvp in m_capsObjects)
{
capsReport.AppendFormat("** User {0}:\n", kvp.Key);
Caps caps = kvp.Value;
for (IDictionaryEnumerator kvp2 = caps.CapsHandlers.GetCapsDetails(false, null).GetEnumerator(); kvp2.MoveNext(); )
{
Uri uri = new Uri(kvp2.Value.ToString());
capsReport.AppendFormat(m_showCapsCommandFormat, kvp2.Key, uri.PathAndQuery);
}
foreach (KeyValuePair<string, PollServiceEventArgs> kvp2 in caps.GetPollHandlers())
capsReport.AppendFormat(m_showCapsCommandFormat, kvp2.Key, kvp2.Value.Url);
foreach (KeyValuePair<string, string> kvp3 in caps.ExternalCapsHandlers)
capsReport.AppendFormat(m_showCapsCommandFormat, kvp3.Key, kvp3.Value);
}
}
MainConsole.Instance.Output(capsReport.ToString());
}
private void HandleShowCapsStatsByCapCommand(string module, string[] cmdParams)
{
if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
return;
if (cmdParams.Length != 5 && cmdParams.Length != 6)
{
MainConsole.Instance.Output("Usage: show caps stats by cap [<cap-name>]");
return;
}
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Region {0}:\n", m_scene.Name);
if (cmdParams.Length == 5)
{
BuildSummaryStatsByCapReport(sb);
}
else if (cmdParams.Length == 6)
{
BuildDetailedStatsByCapReport(sb, cmdParams[5]);
}
MainConsole.Instance.Output(sb.ToString());
}
private void BuildDetailedStatsByCapReport(StringBuilder sb, string capName)
{
sb.AppendFormat("Capability name {0}\n", capName);
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("User Name", 34);
cdt.AddColumn("Req Received", 12);
cdt.AddColumn("Req Handled", 12);
cdt.Indent = 2;
Dictionary<string, int> receivedStats = new Dictionary<string, int>();
Dictionary<string, int> handledStats = new Dictionary<string, int>();
m_scene.ForEachScenePresence(
sp =>
{
Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);
if (caps == null)
return;
Dictionary<string, IRequestHandler> capsHandlers = caps.CapsHandlers.GetCapsHandlers();
IRequestHandler reqHandler;
if (capsHandlers.TryGetValue(capName, out reqHandler))
{
receivedStats[sp.Name] = reqHandler.RequestsReceived;
handledStats[sp.Name] = reqHandler.RequestsHandled;
}
else
{
PollServiceEventArgs pollHandler = null;
if (caps.TryGetPollHandler(capName, out pollHandler))
{
receivedStats[sp.Name] = pollHandler.RequestsReceived;
handledStats[sp.Name] = pollHandler.RequestsHandled;
}
}
}
);
foreach (KeyValuePair<string, int> kvp in receivedStats.OrderByDescending(kp => kp.Value))
{
cdt.AddRow(kvp.Key, kvp.Value, handledStats[kvp.Key]);
}
sb.Append(cdt.ToString());
}
private void BuildSummaryStatsByCapReport(StringBuilder sb)
{
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Name", 34);
cdt.AddColumn("Req Received", 12);
cdt.AddColumn("Req Handled", 12);
cdt.Indent = 2;
Dictionary<string, int> receivedStats = new Dictionary<string, int>();
Dictionary<string, int> handledStats = new Dictionary<string, int>();
m_scene.ForEachScenePresence(
sp =>
{
Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);
if (caps == null)
return;
foreach (IRequestHandler reqHandler in caps.CapsHandlers.GetCapsHandlers().Values)
{
string reqName = reqHandler.Name ?? "";
if (!receivedStats.ContainsKey(reqName))
{
receivedStats[reqName] = reqHandler.RequestsReceived;
handledStats[reqName] = reqHandler.RequestsHandled;
}
else
{
receivedStats[reqName] += reqHandler.RequestsReceived;
handledStats[reqName] += reqHandler.RequestsHandled;
}
}
foreach (KeyValuePair<string, PollServiceEventArgs> kvp in caps.GetPollHandlers())
{
string name = kvp.Key;
PollServiceEventArgs pollHandler = kvp.Value;
if (!receivedStats.ContainsKey(name))
{
receivedStats[name] = pollHandler.RequestsReceived;
handledStats[name] = pollHandler.RequestsHandled;
}
else
{
receivedStats[name] += pollHandler.RequestsReceived;
handledStats[name] += pollHandler.RequestsHandled;
}
}
}
);
foreach (KeyValuePair<string, int> kvp in receivedStats.OrderByDescending(kp => kp.Value))
cdt.AddRow(kvp.Key, kvp.Value, handledStats[kvp.Key]);
sb.Append(cdt.ToString());
}
private void HandleShowCapsStatsByUserCommand(string module, string[] cmdParams)
{
if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_scene)
return;
if (cmdParams.Length != 5 && cmdParams.Length != 7)
{
MainConsole.Instance.Output("Usage: show caps stats by user [<first-name> <last-name>]");
return;
}
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Region {0}:\n", m_scene.Name);
if (cmdParams.Length == 5)
{
BuildSummaryStatsByUserReport(sb);
}
else if (cmdParams.Length == 7)
{
string firstName = cmdParams[5];
string lastName = cmdParams[6];
ScenePresence sp = m_scene.GetScenePresence(firstName, lastName);
if (sp == null)
return;
BuildDetailedStatsByUserReport(sb, sp);
}
MainConsole.Instance.Output(sb.ToString());
}
private void BuildDetailedStatsByUserReport(StringBuilder sb, ScenePresence sp)
{
sb.AppendFormat("Avatar name {0}, type {1}\n", sp.Name, sp.IsChildAgent ? "child" : "root");
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Cap Name", 34);
cdt.AddColumn("Req Received", 12);
cdt.AddColumn("Req Handled", 12);
cdt.Indent = 2;
Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);
if (caps == null)
return;
List<CapTableRow> capRows = new List<CapTableRow>();
foreach (IRequestHandler reqHandler in caps.CapsHandlers.GetCapsHandlers().Values)
capRows.Add(new CapTableRow(reqHandler.Name, reqHandler.RequestsReceived, reqHandler.RequestsHandled));
foreach (KeyValuePair<string, PollServiceEventArgs> kvp in caps.GetPollHandlers())
capRows.Add(new CapTableRow(kvp.Key, kvp.Value.RequestsReceived, kvp.Value.RequestsHandled));
foreach (CapTableRow ctr in capRows.OrderByDescending(ctr => ctr.RequestsReceived))
cdt.AddRow(ctr.Name, ctr.RequestsReceived, ctr.RequestsHandled);
sb.Append(cdt.ToString());
}
private void BuildSummaryStatsByUserReport(StringBuilder sb)
{
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Name", 32);
cdt.AddColumn("Type", 5);
cdt.AddColumn("Req Received", 12);
cdt.AddColumn("Req Handled", 12);
cdt.Indent = 2;
m_scene.ForEachScenePresence(
sp =>
{
Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);
if (caps == null)
return;
Dictionary<string, IRequestHandler> capsHandlers = caps.CapsHandlers.GetCapsHandlers();
int totalRequestsReceived = 0;
int totalRequestsHandled = 0;
foreach (IRequestHandler reqHandler in capsHandlers.Values)
{
totalRequestsReceived += reqHandler.RequestsReceived;
totalRequestsHandled += reqHandler.RequestsHandled;
}
Dictionary<string, PollServiceEventArgs> capsPollHandlers = caps.GetPollHandlers();
foreach (PollServiceEventArgs handler in capsPollHandlers.Values)
{
totalRequestsReceived += handler.RequestsReceived;
totalRequestsHandled += handler.RequestsHandled;
}
cdt.AddRow(sp.Name, sp.IsChildAgent ? "child" : "root", totalRequestsReceived, totalRequestsHandled);
}
);
sb.Append(cdt.ToString());
}
private class CapTableRow
{
public string Name { get; set; }
public int RequestsReceived { get; set; }
public int RequestsHandled { get; set; }
public CapTableRow(string name, int requestsReceived, int requestsHandled)
{
Name = name;
RequestsReceived = requestsReceived;
RequestsHandled = requestsHandled;
}
}
}
}
| |
using Bridge.Test.NUnit;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Bridge.ClientTest.Batch3.BridgeIssues
{
/// <summary>
/// The tests here ensures linq implementation of IEnumerable resolves to
/// the right call given its underlying involved type.
/// </summary>
[TestFixture(TestNameFormat = "#3885 - {0}")]
public class Bridge3885
{
/// <summary>
/// This is the exact same scenario as reported in the issue.
/// </summary>
public class DoubleTest : IEnumerable<int>, IEnumerable<double>
{
public int Max { get; }
public DoubleTest(int max)
{
Max = max;
}
public IEnumerator<int> GetEnumerator() => new IntEnumerator(this);
IEnumerator<double> IEnumerable<double>.GetEnumerator() => new DoubleEnumerator(this);
IEnumerator IEnumerable.GetEnumerator() => new IntEnumerator(this);
class IntEnumerator : IEnumerator<int>
{
private readonly int _max;
public IntEnumerator(DoubleTest test)
{
_max = test.Max;
Current = -1;
}
public int Current { get; set; }
object IEnumerator.Current => Current;
public void Dispose() { }
public void Reset() { Current = -1; }
public bool MoveNext() => ++Current <= _max;
}
class DoubleEnumerator : IEnumerator<double>
{
private readonly int _max;
public DoubleEnumerator(DoubleTest test)
{
_max = test.Max;
Current = -.1;
}
public double Current { get; set; }
object IEnumerator.Current => Current;
public void Dispose() { }
public void Reset() { Current = -.1; }
public bool MoveNext() => (Current += .1) <= _max;
}
}
/// <summary>
/// Slightly changed scenario involving string instead.
/// </summary>
public class StringTest : IEnumerable<int>, IEnumerable<string>
{
public int Max { get; }
public StringTest(int max)
{
Max = max;
}
public IEnumerator<int> GetEnumerator() => new IntEnumerator(this);
IEnumerator<string> IEnumerable<string>.GetEnumerator() => new StringEnumerator(this);
IEnumerator IEnumerable.GetEnumerator() => new IntEnumerator(this);
class IntEnumerator : IEnumerator<int>
{
private readonly int _max;
public IntEnumerator(StringTest test)
{
_max = test.Max;
Current = -1;
}
public int Current { get; set; }
object IEnumerator.Current => Current;
public void Dispose() { }
public void Reset() { Current = -1; }
public bool MoveNext() => ++Current <= _max;
}
class StringEnumerator : IEnumerator<string>
{
private readonly int _max;
private int _index;
public StringEnumerator(StringTest test)
{
_max = test.Max;
_index = -1;
Current = "";
}
public string Current { get; set; }
object IEnumerator.Current => Current;
public void Dispose() { }
public void Reset() { Current = ""; _index = -1; }
public bool MoveNext()
{
Current = "s" + ++_index;
return _index < _max;
}
}
}
/// <summary>
/// Tests the string variation by checking whether the resolved type
/// is the correct one (string!).
/// </summary>
[Test]
public static void TestLinqEnumerationOnString()
{
{
var test = new StringTest(1);
foreach (var i in test)
{
Assert.True((object)i is int, "The resolved type is int.");
}
foreach (var i in (IEnumerable<string>)test)
{
Assert.True((object)i is string, "The resolved type is string.");
}
foreach (var i in ((IEnumerable<string>)test).Select(d => d))
{
Assert.True((object)i is string, "The resolved type is string.");
}
}
{
IEnumerable<string> test = new StringTest(1);
foreach (var i in test)
{
Assert.True((object)i is string, "The resolved type is string.");
}
foreach (var i in test.Select(d => d))
{
Assert.True((object)i is string, "The resolved type is string.");
}
}
}
/// <summary>
/// The original format of the test, counting whether the iteration
/// amount is congruent with the step.
/// </summary>
[Test]
public static void TestLinqEnumerationOnDouble()
{
{
var test = new DoubleTest(1);
var count = 0;
foreach (var i in test)
{
count++;
}
Assert.AreEqual(2, count, "0 - 1 in steps of 1 results in two iterations.");
count = 0;
foreach (var i in (IEnumerable<double>)test)
{
count++;
}
Assert.AreEqual(11, count, "0 - 1 in steps of 0.1 results in eleven iterations.");
count = 0;
foreach (var i in ((IEnumerable<double>)test).Select(d => d))
{
count++;
}
Assert.AreEqual(11, count, "0 - 1 in steps of 0.1 results in eleven iterations.");
}
{
IEnumerable<double> test = new DoubleTest(1);
var count = 0;
foreach (var i in test)
{
count++;
}
Assert.AreEqual(11, count, "0 - 1 in steps of 0.1 results in eleven iterations.");
count = 0;
foreach (var i in test.Select(d => d))
{
count++;
}
Assert.AreEqual(11, count, "0 - 1 in steps of 0.1 results in eleven iterations.");
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class DoNotRaiseExceptionsInUnexpectedLocationsTests
{
#region Property and Event Tests
[Fact]
public async Task CSharpPropertyNoDiagnosticsAsync()
{
var code = @"
using System;
public class C
{
public int PropWithNoException { get { return 10; } set { } }
public int PropWithSetterException { get { return 10; } set { throw new NotSupportedException(); } }
public int PropWithAllowedException { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public int this[int x] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
}
class NonPublic
{
public int PropWithException { get { throw new Exception(); } set { throw new NotSupportedException(); } }
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpPropertyWithDerivedExceptionNoDiagnosticsAsync()
{
var code = @"
using System;
public class C
{
public int this[int x] { get { throw new ArgumentOutOfRangeException(); } set { throw new ArgumentOutOfRangeException(); } }
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicPropertyNoDiagnosticsAsync()
{
var code = @"
Imports System
Public Class C
Public Property PropWithNoException As Integer
Get
Return 10
End Get
Set
End Set
End Property
Public Property PropWithSetterException As Integer
Get
Return 10
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Public Property PropWithAllowedException As Integer
Get
Throw New NotSupportedException()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Default Public Property Item(x As Integer) As Integer
Get
Throw New NotSupportedException()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
End Class
Class NonPublic
Public Property PropWithInvalidException As Integer
Get
Throw New Exception() 'Doesn't fire because it's not visible outside assembly
End Get
Set
End Set
End Property
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicPropertyWithDerivedExceptionNoDiagnosticsAsync()
{
var code = @"
Imports System
Public Class C
Default Public Property Item(x As Integer) As Integer
Get
Throw New ArgumentOutOfRangeException()
End Get
Set
Throw New ArgumentOutOfRangeException()
End Set
End Property
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpPropertyWithInvalidExceptionsAsync()
{
var code = @"
using System;
public class C
{
public int Prop1 { get { throw new Exception(); } set { throw new NotSupportedException(); } }
public int this[int x] { get { throw new Exception(); } set { throw new NotSupportedException(); } }
public event EventHandler Event1 { add { throw new Exception(); } remove { throw new Exception(); } }
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpPropertyResultAt(6, 30, "get_Prop1", "Exception"),
GetCSharpPropertyResultAt(7, 36, "get_Item", "Exception"),
GetCSharpAllowedExceptionsResultAt(8, 46, "add_Event1", "Exception"),
GetCSharpAllowedExceptionsResultAt(8, 80, "remove_Event1", "Exception"));
}
[Fact]
public async Task BasicPropertyWithInvalidExceptionsAsync()
{
var code = @"
Imports System
Public Class C
Public Property Prop1 As Integer
Get
Throw New Exception()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Default Public Property Item(x As Integer) As Integer
Get
Throw New Exception()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Public Custom Event Event1 As EventHandler
AddHandler(ByVal value As EventHandler)
Throw New Exception()
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Throw New Exception()
End RemoveHandler
' RaiseEvent accessors are considered private and we won't flag this exception.
RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
Throw New Exception()
End RaiseEvent
End Event
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicPropertyResultAt(7, 12, "get_Prop1", "Exception"),
GetBasicPropertyResultAt(15, 12, "get_Item", "Exception"),
GetBasicAllowedExceptionsResultAt(24, 13, "add_Event1", "Exception"),
GetBasicAllowedExceptionsResultAt(28, 13, "remove_Event1", "Exception"));
}
[Fact, WorkItem(1842, "https://github.com/dotnet/roslyn-analyzers/issues/1842")]
public async Task CSharpIndexer_KeyNotFoundException_NoDiagnosticsAsync()
{
var code = @"
using System.Collections.Generic;
public class C
{
public int this[int x] { get { throw new KeyNotFoundException(); } }
}";
await VerifyCS.VerifyAnalyzerAsync(code);
}
#endregion
#region Equals, GetHashCode, Dispose and ToString Tests
[Fact]
public async Task CSharpEqualsAndGetHashCodeWithExceptionsAsync()
{
var code = @"
using System;
public class C
{
public override bool Equals(object obj)
{
throw new Exception();
}
public override int GetHashCode()
{
throw new ArgumentException("""");
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"),
GetCSharpNoExceptionsResultAt(12, 9, "GetHashCode", "ArgumentException"));
}
[Fact]
public async Task BasicEqualsAndGetHashCodeWithExceptionsAsync()
{
var code = @"
Imports System
Public Class C
Public Overrides Function Equals(obj As Object) As Boolean
Throw New Exception()
End Function
Public Overrides Function GetHashCode() As Integer
Throw New ArgumentException("""")
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(6, 9, "Equals", "Exception"),
GetBasicNoExceptionsResultAt(9, 9, "GetHashCode", "ArgumentException"));
}
[Fact]
public async Task CSharpEqualsAndGetHashCodeNoDiagnosticsAsync()
{
var code = @"
using System;
public class C
{
public new bool Equals(object obj)
{
throw new Exception();
}
public new int GetHashCode()
{
throw new ArgumentException("""");
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task BasicEqualsAndGetHashCodeNoDiagnosticsAsync()
{
var code = @"
Imports System
Public Class C
Public Shadows Function Equals(obj As Object) As Boolean
Throw New Exception()
End Function
Public Shadows Function GetHashCode() As Integer
Throw New ArgumentException("""")
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code);
}
[Fact]
public async Task CSharpIEquatableEqualsWithExceptionsAsync()
{
var code = @"
using System;
public class C : IEquatable<C>
{
public bool Equals(C obj)
{
throw new Exception();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"));
}
[Fact]
public async Task BasicIEquatableEqualsExceptionsAsync()
{
var code = @"
Imports System
Public Class C
Implements IEquatable(Of C)
Public Function Equals(obj As C) As Boolean Implements IEquatable(Of C).Equals
Throw New Exception()
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(7, 9, "Equals", "Exception"));
}
[Fact]
public async Task CSharpIHashCodeProviderGetHashCodeAsync()
{
var code = @"
using System;
using System.Collections;
public class C : IHashCodeProvider
{
public int GetHashCode(object obj)
{
throw new Exception();
}
}
public class D : IHashCodeProvider
{
public int GetHashCode(object obj)
{
throw new ArgumentException(""obj""); // this is fine.
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpAllowedExceptionsResultAt(8, 9, "GetHashCode", "Exception"));
}
[Fact]
public async Task BasicIHashCodeProviderGetHashCodeAsync()
{
var code = @"
Imports System
Imports System.Collections
Public Class C
Implements IHashCodeProvider
Public Function GetHashCode(obj As Object) As Integer Implements IHashCodeProvider.GetHashCode
Throw New Exception()
End Function
End Class
Public Class D
Implements IHashCodeProvider
Public Function GetHashCode(obj As Object) As Integer Implements IHashCodeProvider.GetHashCode
Throw New ArgumentException() ' This is fine.
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicAllowedExceptionsResultAt(7, 9, "GetHashCode", "Exception"));
}
[Fact]
public async Task CSharpIEqualityComparerAsync()
{
var code = @"
using System;
using System.Collections.Generic;
public class C : IEqualityComparer<C>
{
public bool Equals(C obj1, C obj2)
{
throw new Exception();
}
public int GetHashCode(C obj)
{
throw new Exception();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"),
GetCSharpAllowedExceptionsResultAt(12, 9, "GetHashCode", "Exception"));
}
[Fact]
public async Task BasicIEqualityComparerAsync()
{
var code = @"
Imports System
Imports System.Collections.Generic
Public Class C
Implements IEqualityComparer(Of C)
Public Function Equals(obj1 As C, obj2 As C) As Boolean Implements IEqualityComparer(Of C).Equals
Throw New Exception()
End Function
Public Function GetHashCode(obj As C) As Integer Implements IEqualityComparer(Of C).GetHashCode
Throw New Exception()
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(7, 9, "Equals", "Exception"),
GetBasicAllowedExceptionsResultAt(10, 9, "GetHashCode", "Exception"));
}
[Fact]
public async Task CSharpIDisposableAsync()
{
var code = @"
using System;
public class C : IDisposable
{
public void Dispose()
{
throw new Exception();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, "Dispose", "Exception"));
}
[Fact]
public async Task BasicIDisposableAsync()
{
var code = @"
Imports System
Public Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New Exception()
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(7, 9, "Dispose", "Exception"));
}
[Fact]
public async Task CSharpToStringWithExceptionsAsync()
{
var code = @"
using System;
public class C
{
public override string ToString()
{
throw new Exception();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, "ToString", "Exception"));
}
[Fact]
public async Task BasicToStringWithExceptionsAsync()
{
var code = @"
Imports System
Public Class C
Public Overrides Function ToString() As String
Throw New Exception()
End Function
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(6, 9, "ToString", "Exception"));
}
#endregion
#region Constructor and Destructor tests
[Fact]
public async Task CSharpStaticConstructorWithExceptionsAsync()
{
var code = @"
using System;
class NonPublic
{
static NonPublic()
{
throw new Exception();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, ".cctor", "Exception"));
}
[Fact]
public async Task BasicStaticConstructorWithExceptionsAsync()
{
var code = @"
Imports System
Class NonPublic
Shared Sub New()
Throw New Exception()
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(6, 9, ".cctor", "Exception"));
}
[Fact]
public async Task CSharpFinalizerWithExceptionsAsync()
{
var code = @"
using System;
class NonPublic
{
~NonPublic()
{
throw new Exception();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, "Finalize", "Exception"));
}
[Fact]
public async Task BasicFinalizerWithExceptionsAsync()
{
var code = @"
Imports System
Class NonPublic
Protected Overrides Sub Finalize()
Throw New Exception()
End Sub
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(6, 9, "Finalize", "Exception"));
}
#endregion
#region Operator tests
[Fact]
public async Task CSharpEqualityOperatorWithExceptionsAsync()
{
var code = @"
using System;
public class C
{
public static C operator ==(C c1, C c2)
{
throw new Exception();
}
public static C operator !=(C c1, C c2)
{
throw new Exception();
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, "op_Equality", "Exception"),
GetCSharpNoExceptionsResultAt(12, 9, "op_Inequality", "Exception"));
}
[Fact]
public async Task BasicEqualityOperatorWithExceptionsAsync()
{
var code = @"
Imports System
Public Class C
Public Shared Operator =(c1 As C, c2 As C) As C
Throw New Exception()
End Operator
Public Shared Operator <>(c1 As C, c2 As C) As C
Throw New Exception()
End Operator
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(6, 9, "op_Equality", "Exception"),
GetBasicNoExceptionsResultAt(9, 9, "op_Inequality", "Exception"));
}
[Fact]
[WorkItem(5021, "https://github.com/dotnet/roslyn-analyzers/issues/5021")]
public async Task CSharpComparisonOperatorWithExceptionsAsync()
{
var code = @"
using System;
public class C
{
public static bool operator <=(C left, C right)
{
{|#0:throw new Exception();|}
}
public static bool operator >=(C left, C right)
{
{|#1:throw new Exception();|}
}
public static bool operator <(C left, C right)
{
{|#2:throw new Exception();|}
}
public static bool operator >(C left, C right)
{
{|#3:throw new Exception();|}
}
}";
await VerifyCS.VerifyAnalyzerAsync(
code,
GetCSharpNoExceptionsResultAt(0, "op_LessThanOrEqual", "Exception"),
GetCSharpNoExceptionsResultAt(1, "op_GreaterThanOrEqual", "Exception"),
GetCSharpNoExceptionsResultAt(2, "op_LessThan", "Exception"),
GetCSharpNoExceptionsResultAt(3, "op_GreaterThan", "Exception"));
}
[Fact]
public async Task BasicComparisonOperatorWithExceptionsAsync()
{
var code = @"
Imports System
Public Class C
Public Shared Operator <=(left As C, right As C) As Boolean
{|#0:Throw New Exception()|}
End Operator
Public Shared Operator >=(left As C, right As C) As Boolean
{|#1:Throw New Exception()|}
End Operator
Public Shared Operator <(left As C, right As C) As Boolean
{|#2:Throw New Exception()|}
End Operator
Public Shared Operator >(left As C, right As C) As Boolean
{|#3:Throw New Exception()|}
End Operator
End Class";
await VerifyVB.VerifyAnalyzerAsync(
code,
GetBasicNoExceptionsResultAt(0, "op_LessThanOrEqual", "Exception"),
GetBasicNoExceptionsResultAt(1, "op_GreaterThanOrEqual", "Exception"),
GetBasicNoExceptionsResultAt(2, "op_LessThan", "Exception"),
GetBasicNoExceptionsResultAt(3, "op_GreaterThan", "Exception"));
}
[Fact]
public async Task CSharpImplicitOperatorWithExceptionsAsync()
{
var code = @"
using System;
public class C
{
public static implicit operator int(C c1)
{
throw new Exception();
}
public static explicit operator double(C c1)
{
throw new Exception(); // This is fine.
}
}
";
await VerifyCS.VerifyAnalyzerAsync(code,
GetCSharpNoExceptionsResultAt(8, 9, "op_Implicit", "Exception"));
}
[Fact]
public async Task BasicImplicitOperatorWithExceptionsAsync()
{
var code = @"
Imports System
Public Class C
Public Shared Widening Operator CType(x As Integer) As C
Throw New Exception()
End Operator
Public Shared Narrowing Operator CType(x As Double) As C
Throw New Exception()
End Operator
End Class
";
await VerifyVB.VerifyAnalyzerAsync(code,
GetBasicNoExceptionsResultAt(6, 9, "op_Implicit", "Exception"));
}
#endregion
private static DiagnosticResult GetCSharpPropertyResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.PropertyGetterRule, methodName, exceptionName);
}
private static DiagnosticResult GetCSharpAllowedExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.HasAllowedExceptionsRule, methodName, exceptionName);
}
private static DiagnosticResult GetCSharpNoExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule, methodName, exceptionName);
}
private static DiagnosticResult GetCSharpNoExceptionsResultAt(int markupKey, string methodName, string exceptionName)
{
return VerifyCS.Diagnostic(DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule)
.WithLocation(markupKey)
.WithArguments(methodName, exceptionName);
}
private static DiagnosticResult GetBasicPropertyResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.PropertyGetterRule, methodName, exceptionName);
}
private static DiagnosticResult GetBasicAllowedExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.HasAllowedExceptionsRule, methodName, exceptionName);
}
private static DiagnosticResult GetBasicNoExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule, methodName, exceptionName);
}
private static DiagnosticResult GetBasicNoExceptionsResultAt(int markupKey, string methodName, string exceptionName)
{
return VerifyVB.Diagnostic(DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule)
.WithLocation(markupKey)
.WithArguments(methodName, exceptionName);
}
private static DiagnosticResult GetCSharpResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(rule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(arguments);
private static DiagnosticResult GetBasicResultAt(int line, int column, DiagnosticDescriptor rule, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(rule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(arguments);
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using ServiceStack.Common.Utils;
using System.Text;
using FirebirdSql.Data.FirebirdClient;
using ServiceStack.Common.Extensions;
namespace ServiceStack.OrmLite.Firebird
{
public class FirebirdOrmLiteDialectProvider : OrmLiteDialectProviderBase<FirebirdOrmLiteDialectProvider>
{
private readonly List<string> RESERVED = new List<string>(new[] {
"USER","ORDER","PASSWORD", "ACTIVE","LEFT","DOUBLE", "FLOAT", "DECIMAL","STRING", "DATE","DATETIME", "TYPE","TIMESTAMP",
"INDEX","UNIQUE", "PRIMARY", "KEY", "ALTER", "DROP", "CREATE", "DELETE"
});
public static FirebirdOrmLiteDialectProvider Instance = new FirebirdOrmLiteDialectProvider();
internal long LastInsertId { get; set; }
protected bool CompactGuid;
internal const string DefaultGuidDefinition = "VARCHAR(37)";
internal const string CompactGuidDefinition = "CHAR(16) CHARACTER SET OCTETS";
public FirebirdOrmLiteDialectProvider()
: this(false)
{
}
public FirebirdOrmLiteDialectProvider(bool compactGuid)
{
CompactGuid = compactGuid;
base.BoolColumnDefinition = base.IntColumnDefinition;
base.GuidColumnDefinition = CompactGuid ? CompactGuidDefinition : DefaultGuidDefinition;
base.AutoIncrementDefinition= string.Empty;
base.DateTimeColumnDefinition="TIMESTAMP";
base.TimeColumnDefinition = "TIME";
base.RealColumnDefinition= "FLOAT";
base.DefaultStringLength=128;
base.InitColumnTypeMap();
}
public override IDbConnection CreateConnection(string connectionString, Dictionary<string, string> options)
{
if (options != null)
{
foreach (var option in options)
{
connectionString += option.Key + "=" + option.Value + ";";
}
}
return new FbConnection(connectionString);
}
public override long GetLastInsertId(IDbCommand dbCmd)
{
return LastInsertId;
}
public override object ConvertDbValue(object value, Type type)
{
if (value == null || value is DBNull) return null;
if (type == typeof(bool))
{
var intVal = int.Parse(value.ToString());
return intVal != 0;
}
if(type == typeof(System.Double))
return double.Parse(value.ToString());
if (type == typeof(Guid) && BitConverter.IsLittleEndian) // TODO: check big endian
{
if (CompactGuid)
{
byte[] raw = ((Guid)value).ToByteArray();
return new Guid(System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt32(raw, 0)),
System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(raw, 4)),
System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(raw, 6)),
raw[8], raw[9], raw[10], raw[11], raw[12], raw[13], raw[14], raw[15]);
}
return new Guid(value.ToString());
}
try
{
return base.ConvertDbValue(value, type);
}
catch (Exception )
{
throw;
}
}
public override string GetQuotedValue(object value, Type fieldType)
{
if (value == null) return "NULL";
if (fieldType == typeof(Guid))
{
if (CompactGuid)
return "X'" + ((Guid)value).ToString("N") + "'";
else
return string.Format("CAST('{0}' AS {1})", (Guid)value, DefaultGuidDefinition); // TODO : check this !!!
}
if (fieldType == typeof(DateTime) || fieldType == typeof( DateTime?) )
{
var dateValue = (DateTime)value;
string iso8601Format= dateValue.ToString("yyyy-MM-dd HH:mm:ss.fff").EndsWith("00:00:00.000")?
"yyyy-MM-dd"
:"yyyy-MM-dd HH:mm:ss.fff";
return base.GetQuotedValue(dateValue.ToString(iso8601Format), typeof(string));
}
if (fieldType == typeof(bool ?) || fieldType == typeof(bool))
{
var boolValue = (bool)value;
return base.GetQuotedValue(boolValue ? "1" : "0", typeof(string));
}
if (fieldType == typeof(decimal ?) || fieldType == typeof(decimal) ||
fieldType == typeof(double ?) || fieldType == typeof(double) ||
fieldType == typeof(float ?) || fieldType == typeof(float) ){
var s = base.GetQuotedValue( value, fieldType);
if (s.Length>20) s= s.Substring(0,20);
return "'" + s + "'"; // when quoted exception is more clear!
}
return base.GetQuotedValue(value, fieldType);
}
public override string ToSelectStatement(Type tableType, string sqlFilter, params object[] filterParams)
{
var sql = new StringBuilder();
const string SelectStatement = "SELECT ";
var modelDef = GetModel(tableType);
var isFullSelectStatement =
!string.IsNullOrEmpty(sqlFilter)
&& sqlFilter.Length > SelectStatement.Length
&& sqlFilter.Substring(0, SelectStatement.Length).ToUpper().Equals(SelectStatement);
if (isFullSelectStatement) return sqlFilter.SqlFormat(filterParams);
sql.AppendFormat("SELECT {0} \nFROM {1}",
GetColumnNames(modelDef),
GetQuotedTableName(modelDef));
if (!string.IsNullOrEmpty(sqlFilter))
{
sqlFilter = sqlFilter.SqlFormat(filterParams);
if (!sqlFilter.StartsWith("\nORDER ", StringComparison.InvariantCultureIgnoreCase)
&& !sqlFilter.StartsWith("\nROWS ", StringComparison.InvariantCultureIgnoreCase)) // ROWS <m> [TO <n>])
{
sql.Append("\nWHERE ");
}
sql.Append(sqlFilter);
}
return sql.ToString();
}
public override string ToInsertRowStatement(object objWithProperties, IList<string> insertFields, IDbCommand dbCommand)
{
var sbColumnNames = new StringBuilder();
var sbColumnValues = new StringBuilder();
var tableType = objWithProperties.GetType();
var modelDef= GetModel(tableType);
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if( fieldDef.IsComputed ) continue;
if( insertFields.Count>0 && ! insertFields.Contains( fieldDef.Name )) continue;
if( (fieldDef.AutoIncrement || ! string.IsNullOrEmpty(fieldDef.Sequence)
|| fieldDef.Name == OrmLiteConfig.IdField)
&& dbCommand != null)
{
if (fieldDef.AutoIncrement && string.IsNullOrEmpty(fieldDef.Sequence))
{
fieldDef.Sequence = Sequence(
(modelDef.IsInSchema
? modelDef.Schema+"_"+NamingStrategy.GetTableName(modelDef.ModelName)
: NamingStrategy.GetTableName(modelDef.ModelName)),
fieldDef.FieldName, fieldDef.Sequence);
}
PropertyInfo pi = tableType.GetProperty(fieldDef.Name,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
var result = GetNextValue(dbCommand, fieldDef.Sequence, pi.GetValue(objWithProperties, new object[] { }) );
if (pi.PropertyType == typeof(String))
ReflectionUtils.SetProperty(objWithProperties, pi, result.ToString());
else if(pi.PropertyType == typeof(Int16))
ReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt16(result));
else if(pi.PropertyType == typeof(Int32))
ReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt32(result));
else if(pi.PropertyType == typeof(Guid))
ReflectionUtils.SetProperty(objWithProperties, pi, result);
else
ReflectionUtils.SetProperty(objWithProperties, pi, Convert.ToInt64(result));
}
if (sbColumnNames.Length > 0) sbColumnNames.Append(",");
if (sbColumnValues.Length > 0) sbColumnValues.Append(",");
try
{
sbColumnNames.Append(string.Format("{0}",GetQuotedColumnName(fieldDef.FieldName)));
if (!string.IsNullOrEmpty(fieldDef.Sequence) && dbCommand==null)
sbColumnValues.Append(string.Format("@{0}",fieldDef.Name));
else
sbColumnValues.Append(fieldDef.GetQuotedValue(objWithProperties));
}
catch (Exception)
{
throw;
}
}
var sql = string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
GetQuotedTableName(modelDef), sbColumnNames, sbColumnValues);
return sql;
}
public override string ToUpdateRowStatement(object objWithProperties, IList<string> updateFields)
{
var sqlFilter = new StringBuilder();
var sql = new StringBuilder();
var tableType = objWithProperties.GetType();
var modelDef = GetModel(tableType);
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if( fieldDef.IsComputed) continue;
try
{
if ((fieldDef.IsPrimaryKey || fieldDef.Name == OrmLiteConfig.IdField)
&& updateFields.Count == 0)
{
if (sqlFilter.Length > 0) sqlFilter.Append(" AND ");
sqlFilter.AppendFormat("{0} = {1}",
GetQuotedColumnName(fieldDef.FieldName),
fieldDef.GetQuotedValue(objWithProperties));
continue;
}
if (updateFields.Count>0 && !updateFields.Contains(fieldDef.Name)) continue;
if (sql.Length > 0) sql.Append(",");
sql.AppendFormat("{0} = {1}",
GetQuotedColumnName(fieldDef.FieldName),
fieldDef.GetQuotedValue(objWithProperties));
}
catch (Exception)
{
throw;
}
}
var updateSql = string.Format("UPDATE {0} \nSET {1} {2}",
GetQuotedTableName(modelDef), sql, (sqlFilter.Length>0? "\nWHERE "+ sqlFilter:""));
return updateSql;
}
public override string ToDeleteRowStatement(object objWithProperties)
{
var tableType = objWithProperties.GetType();
var modelDef = GetModel(tableType);
var sqlFilter = new StringBuilder();
foreach (var fieldDef in modelDef.FieldDefinitions)
{
try
{
if (fieldDef.IsPrimaryKey || fieldDef.Name == OrmLiteConfig.IdField)
{
if (sqlFilter.Length > 0) sqlFilter.Append(" AND ");
sqlFilter.AppendFormat("{0} = {1}",
GetQuotedColumnName(fieldDef.FieldName),
fieldDef.GetQuotedValue(objWithProperties));
}
}
catch (Exception)
{
throw;
}
}
var deleteSql = string.Format("DELETE FROM {0} WHERE {1}",
GetQuotedTableName(modelDef), sqlFilter);
return deleteSql;
}
public override string ToCreateTableStatement(Type tableType)
{
var sbColumns = new StringBuilder();
var sbConstraints = new StringBuilder();
var sbPk= new StringBuilder();
var modelDef = GetModel(tableType);
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.IsPrimaryKey)
{
sbPk.AppendFormat(sbPk.Length != 0 ? ",{0}" : "{0}", GetQuotedColumnName(fieldDef.FieldName));
}
if (sbColumns.Length != 0) sbColumns.Append(", \n ");
var columnDefinition = GetColumnDefinition(
fieldDef.FieldName,
fieldDef.FieldType,
fieldDef.IsPrimaryKey,
fieldDef.AutoIncrement,
fieldDef.IsNullable,
fieldDef.FieldLength,
fieldDef.Scale,
fieldDef.DefaultValue);
sbColumns.Append(columnDefinition);
if (fieldDef.ForeignKey == null) continue;
var refModelDef = GetModel(fieldDef.ForeignKey.ReferenceType);
var modelName= modelDef.IsInSchema
? modelDef.Schema + "_" + NamingStrategy.GetTableName(modelDef.ModelName)
: NamingStrategy.GetTableName(modelDef.ModelName);
var refModelName= refModelDef.IsInSchema
? refModelDef.Schema + "_" + NamingStrategy.GetTableName(refModelDef.ModelName)
: NamingStrategy.GetTableName(refModelDef.ModelName);
sbConstraints.AppendFormat(", \n\n CONSTRAINT {0} FOREIGN KEY ({1}) REFERENCES {2} ({3})",
GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef)),
GetQuotedColumnName(fieldDef.FieldName),
GetQuotedTableName(refModelDef),
GetQuotedColumnName(refModelDef.PrimaryKey.FieldName));
}
if (sbPk.Length !=0) sbColumns.AppendFormat(", \n PRIMARY KEY({0})", sbPk);
var sql = new StringBuilder(string.Format(
"CREATE TABLE {0} \n(\n {1}{2} \n); \n",
GetQuotedTableName(modelDef),
sbColumns,
sbConstraints));
return sql.ToString();
}
public override List<string> ToCreateSequenceStatements(Type tableType){
var gens = new List<string>();
var modelDef = GetModel(tableType);
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.AutoIncrement || ! fieldDef.Sequence.IsNullOrEmpty())
{
gens.Add("CREATE GENERATOR "
+ Sequence( (modelDef.IsInSchema
? modelDef.Schema+"_" + NamingStrategy.GetTableName(modelDef.ModelName)
: NamingStrategy.GetTableName(modelDef.ModelName)), fieldDef.FieldName, fieldDef.Sequence) +";" );
}
}
return gens;
}
public override string GetColumnDefinition (string fieldName, Type fieldType,
bool isPrimaryKey, bool autoIncrement, bool isNullable,
int? fieldLength, int? scale, string defaultValue)
{
string fieldDefinition;
if (fieldType == typeof(string))
{
fieldDefinition = string.Format(StringLengthColumnDefinitionFormat,
fieldLength.GetValueOrDefault(DefaultStringLength));
}
else if( fieldType==typeof(Decimal) ){
fieldDefinition= string.Format("{0} ({1},{2})", DecimalColumnDefinition,
fieldLength.GetValueOrDefault(DefaultDecimalPrecision),
scale.GetValueOrDefault(DefaultDecimalScale) );
}
else
{
fieldDefinition = GetColumnTypeDefinition(fieldType);
}
var sql = new StringBuilder();
sql.AppendFormat("{0} {1}", GetQuotedColumnName(fieldName), fieldDefinition);
if (!isNullable)
{
sql.Append(" NOT NULL");
}
if (!string.IsNullOrEmpty(defaultValue))
{
sql.AppendFormat(DefaultValueFormat, defaultValue);
}
return sql.ToString();
}
public override List<string> ToCreateIndexStatements(Type tableType)
{
var sqlIndexes = new List<string>();
var modelDef = GetModel(tableType);
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (!fieldDef.IsIndexed) continue;
var indexName = GetIndexName(
fieldDef.IsUnique,
(modelDef.IsInSchema
? modelDef.Schema + "_" + modelDef.ModelName
: modelDef.ModelName).SafeVarName(),
fieldDef.FieldName);
sqlIndexes.Add(
ToCreateIndexStatement(fieldDef.IsUnique, indexName, modelDef, fieldDef.FieldName,false));
}
foreach (var compositeIndex in modelDef.CompositeIndexes)
{
var indexName = GetIndexName(compositeIndex.Unique,
(modelDef.IsInSchema ?
modelDef.Schema +"_"+ GetQuotedTableName(modelDef):
GetQuotedTableName(modelDef) ).SafeVarName(),
string.Join("_", compositeIndex.FieldNames.ToArray()));
var indexNames = string.Join(",", compositeIndex.FieldNames.ToArray());
sqlIndexes.Add(
ToCreateIndexStatement(compositeIndex.Unique, indexName, modelDef, indexNames,false));
}
return sqlIndexes;
}
protected override string ToCreateIndexStatement(bool isUnique, string indexName, ModelDefinition modelDef, string fieldName, bool isCombined)
{
return string.Format("CREATE {0} INDEX {1} ON {2} ({3} ); \n",
isUnique ? "UNIQUE" : "",
indexName,
GetQuotedTableName(modelDef),
GetQuotedColumnName(fieldName));
}
public override string ToExistStatement( Type fromTableType,
object objWithProperties,
string sqlFilter,
params object[] filterParams)
{
var fromModelDef = GetModel(fromTableType);
var sql = new StringBuilder();
sql.AppendFormat("SELECT 1 \nFROM {0}", GetQuotedTableName(fromModelDef));
var filter = new StringBuilder();
if(objWithProperties!=null){
var tableType = objWithProperties.GetType();
if(fromTableType!=tableType){
int i=0;
var fpk= new List<FieldDefinition>();
var modelDef = GetModel(tableType);
foreach (var def in modelDef.FieldDefinitions)
{
if (def.IsPrimaryKey) fpk.Add(def);
}
foreach (var fieldDef in fromModelDef.FieldDefinitions)
{
if (fieldDef.IsComputed) continue;
try
{
if (fieldDef.ForeignKey !=null
&& GetModel(fieldDef.ForeignKey.ReferenceType).ModelName == modelDef.ModelName)
{
if (filter.Length > 0) filter.Append(" AND ");
filter.AppendFormat("{0} = {1}", GetQuotedColumnName(fieldDef.FieldName),
fpk[i].GetQuotedValue(objWithProperties));
i++;
}
}
catch (Exception)
{
throw;
}
}
}
else
{
var modelDef = GetModel(tableType);
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.IsComputed) continue;
try
{
if (fieldDef.IsPrimaryKey)
{
if (filter.Length > 0) filter.Append(" AND ");
filter.AppendFormat("{0} = {1}",
GetQuotedColumnName(fieldDef.FieldName),
fieldDef.GetQuotedValue(objWithProperties));
}
}
catch (Exception)
{
throw;
}
}
}
if (filter.Length>0) sql.AppendFormat("\nWHERE {0} ", filter);
}
if (!string.IsNullOrEmpty(sqlFilter))
{
sqlFilter = sqlFilter.SqlFormat(filterParams);
if (!sqlFilter.StartsWith("\nORDER ", StringComparison.InvariantCultureIgnoreCase)
&& !sqlFilter.StartsWith("\nROWS ", StringComparison.InvariantCultureIgnoreCase)) // ROWS <m> [TO <n>])
{
sql.Append( filter.Length>0? " AND ": "\nWHERE ");
}
sql.Append(sqlFilter);
}
var sb = new StringBuilder("select 1 from RDB$DATABASE where");
sb.AppendFormat(" exists ({0})", sql.ToString() );
return sb.ToString();
}
public override string ToSelectFromProcedureStatement(
object fromObjWithProperties,
Type outputModelType,
string sqlFilter,
params object[] filterParams)
{
var sbColumnValues = new StringBuilder();
Type fromTableType = fromObjWithProperties.GetType();
var modelDef = GetModel(fromTableType);
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (sbColumnValues.Length > 0) sbColumnValues.Append(",");
try
{
sbColumnValues.Append( fieldDef.GetQuotedValue(fromObjWithProperties) );
}
catch (Exception)
{
throw;
}
}
var sql = new StringBuilder();
sql.AppendFormat("SELECT {0} \nFROM {1} {2}{3}{4} \n",
GetColumnNames(GetModel(outputModelType)),
GetQuotedTableName(modelDef),
sbColumnValues.Length > 0 ? "(" : "",
sbColumnValues,
sbColumnValues.Length > 0 ? ")" : "");
if (!string.IsNullOrEmpty(sqlFilter))
{
sqlFilter = sqlFilter.SqlFormat(filterParams);
if (!sqlFilter.StartsWith("\nORDER ", StringComparison.InvariantCultureIgnoreCase)
&& !sqlFilter.StartsWith("\nROWS ", StringComparison.InvariantCultureIgnoreCase)) // ROWS <m> [TO <n>]
{
sql.Append("\nWHERE ");
}
sql.Append(sqlFilter);
}
return sql.ToString();
}
public override string ToExecuteProcedureStatement(object objWithProperties)
{
var sbColumnValues = new StringBuilder();
var tableType = objWithProperties.GetType();
var modelDef = GetModel(tableType);
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (sbColumnValues.Length > 0) sbColumnValues.Append(",");
try
{
sbColumnValues.Append(fieldDef.GetQuotedValue(objWithProperties));
}
catch (Exception)
{
throw;
}
}
var sql = string.Format("EXECUTE PROCEDURE {0} {1}{2}{3};",
GetQuotedTableName(modelDef),
sbColumnValues.Length > 0 ? "(" : "",
sbColumnValues,
sbColumnValues.Length > 0 ? ")" : "");
return sql;
}
private object GetNextValue(IDbCommand dbCmd, string sequence, object value)
{
Object retObj;
if (value.ToString() != "0")
{
long nv;
if (long.TryParse(value.ToString(), out nv))
{
LastInsertId=nv;
retObj= LastInsertId;
}
else
{
LastInsertId=0;
retObj =value;
}
return retObj;
}
dbCmd.CommandText = string.Format("select next value for {0} from RDB$DATABASE",Quote(sequence));
long result = (long) dbCmd.ExecuteScalar();
LastInsertId = result;
return result;
}
public bool QuoteNames { get; set; }
private string Quote(string name)
{
return QuoteNames
? string.Format("\"{0}\"",name)
: RESERVED.Contains(name.ToUpper())
? string.Format("\"{0}\"", name)
: name;
}
public override string GetColumnNames(ModelDefinition modelDef)
{
if (QuoteNames) return modelDef.GetColumnNames();
var sqlColumns = new StringBuilder();
modelDef.FieldDefinitions.ForEach(x =>
sqlColumns.AppendFormat("{0} {1}",
sqlColumns.Length > 0 ? "," : "",
GetQuotedColumnName(x.FieldName)));
return sqlColumns.ToString();
}
public override string GetQuotedName(string fieldName)
{
return Quote(fieldName);
}
public override string GetQuotedTableName(ModelDefinition modelDef)
{
if (!modelDef.IsInSchema)
return Quote(NamingStrategy.GetTableName(modelDef.ModelName));
return Quote(string.Format("{0}_{1}", modelDef.Schema,
NamingStrategy.GetTableName(modelDef.ModelName)));
}
public override string GetQuotedTableName(string tableName)
{
return Quote(NamingStrategy.GetTableName(tableName));
}
public override string GetQuotedColumnName(string fieldName)
{
return Quote(NamingStrategy.GetColumnName(fieldName));
}
private string Sequence(string modelName,string fieldName, string sequence)
{
return sequence.IsNullOrEmpty()
? Quote(modelName + "_" + fieldName + "_GEN")
: Quote(sequence);
}
public override SqlExpressionVisitor<T> ExpressionVisitor<T> ()
{
return new FirebirdSqlExpressionVisitor<T>();
}
public override bool DoesTableExist(IDbCommand dbCmd, string tableName)
{
if (!QuoteNames & !RESERVED.Contains(tableName.ToUpper()))
{
tableName = tableName.ToUpper();
}
var sql = "SELECT count(*) FROM rdb$relations " +
"WHERE rdb$system_flag = 0 AND rdb$view_blr IS NULL AND rdb$relation_name ={0}"
.SqlFormat(tableName);
dbCmd.CommandText = sql;
var result = dbCmd.GetLongScalar();
return result > 0;
}
}
}
/*
DEBUG: Ignoring existing generator 'CREATE GENERATOR ModelWFDT_Id_GEN;': unsuccessful metadata update
DEFINE GENERATOR failed
attempt to store duplicate value (visible to active transactions) in unique index "RDB$INDEX_11"
*/
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
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.Gaming.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedRealmsServiceClientTest
{
[xunit::FactAttribute]
public void GetRealmRequestObject()
{
moq::Mock<RealmsService.RealmsServiceClient> mockGrpcClient = new moq::Mock<RealmsService.RealmsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRealmRequest request = new GetRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
Realm expectedResponse = new Realm
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
TimeZone = "time_zone73f23b20",
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetRealm(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RealmsServiceClient client = new RealmsServiceClientImpl(mockGrpcClient.Object, null);
Realm response = client.GetRealm(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRealmRequestObjectAsync()
{
moq::Mock<RealmsService.RealmsServiceClient> mockGrpcClient = new moq::Mock<RealmsService.RealmsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRealmRequest request = new GetRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
Realm expectedResponse = new Realm
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
TimeZone = "time_zone73f23b20",
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetRealmAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Realm>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RealmsServiceClient client = new RealmsServiceClientImpl(mockGrpcClient.Object, null);
Realm responseCallSettings = await client.GetRealmAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Realm responseCancellationToken = await client.GetRealmAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRealm()
{
moq::Mock<RealmsService.RealmsServiceClient> mockGrpcClient = new moq::Mock<RealmsService.RealmsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRealmRequest request = new GetRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
Realm expectedResponse = new Realm
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
TimeZone = "time_zone73f23b20",
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetRealm(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RealmsServiceClient client = new RealmsServiceClientImpl(mockGrpcClient.Object, null);
Realm response = client.GetRealm(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRealmAsync()
{
moq::Mock<RealmsService.RealmsServiceClient> mockGrpcClient = new moq::Mock<RealmsService.RealmsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRealmRequest request = new GetRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
Realm expectedResponse = new Realm
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
TimeZone = "time_zone73f23b20",
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetRealmAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Realm>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RealmsServiceClient client = new RealmsServiceClientImpl(mockGrpcClient.Object, null);
Realm responseCallSettings = await client.GetRealmAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Realm responseCancellationToken = await client.GetRealmAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRealmResourceNames()
{
moq::Mock<RealmsService.RealmsServiceClient> mockGrpcClient = new moq::Mock<RealmsService.RealmsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRealmRequest request = new GetRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
Realm expectedResponse = new Realm
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
TimeZone = "time_zone73f23b20",
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetRealm(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RealmsServiceClient client = new RealmsServiceClientImpl(mockGrpcClient.Object, null);
Realm response = client.GetRealm(request.RealmName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRealmResourceNamesAsync()
{
moq::Mock<RealmsService.RealmsServiceClient> mockGrpcClient = new moq::Mock<RealmsService.RealmsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRealmRequest request = new GetRealmRequest
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
};
Realm expectedResponse = new Realm
{
RealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
TimeZone = "time_zone73f23b20",
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetRealmAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Realm>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RealmsServiceClient client = new RealmsServiceClientImpl(mockGrpcClient.Object, null);
Realm responseCallSettings = await client.GetRealmAsync(request.RealmName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Realm responseCancellationToken = await client.GetRealmAsync(request.RealmName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PreviewRealmUpdateRequestObject()
{
moq::Mock<RealmsService.RealmsServiceClient> mockGrpcClient = new moq::Mock<RealmsService.RealmsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewRealmUpdateRequest request = new PreviewRealmUpdateRequest
{
Realm = new Realm(),
UpdateMask = new wkt::FieldMask(),
PreviewTime = new wkt::Timestamp(),
};
PreviewRealmUpdateResponse expectedResponse = new PreviewRealmUpdateResponse
{
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewRealmUpdate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
RealmsServiceClient client = new RealmsServiceClientImpl(mockGrpcClient.Object, null);
PreviewRealmUpdateResponse response = client.PreviewRealmUpdate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PreviewRealmUpdateRequestObjectAsync()
{
moq::Mock<RealmsService.RealmsServiceClient> mockGrpcClient = new moq::Mock<RealmsService.RealmsServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewRealmUpdateRequest request = new PreviewRealmUpdateRequest
{
Realm = new Realm(),
UpdateMask = new wkt::FieldMask(),
PreviewTime = new wkt::Timestamp(),
};
PreviewRealmUpdateResponse expectedResponse = new PreviewRealmUpdateResponse
{
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewRealmUpdateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PreviewRealmUpdateResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
RealmsServiceClient client = new RealmsServiceClientImpl(mockGrpcClient.Object, null);
PreviewRealmUpdateResponse responseCallSettings = await client.PreviewRealmUpdateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PreviewRealmUpdateResponse responseCancellationToken = await client.PreviewRealmUpdateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp1.Resources;
using System.Windows.Media;
using System.Threading;
//using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Tasks;
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
String file_name = "PatientData.txt";
tappee();
tuppee();
R29.Fill = new SolidColorBrush(System.Windows.Media.Colors.Green);
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void tuppee()
{
try
{
/*Reminder remind1 = new Reminder("One");
//Uri navigationUri = new Uri("/Reminder1.xaml", UriKind.Relative);
remind1.Title = "Please take your Medicine now";
remind1.Content = "Click to see which tablets";
remind1.BeginTime = DateTime.Parse("26/01/2014 9:30:00");
//remind1.ExpirationTime = DateTime.Parse("26/01/2014 9:45:00");
//remind1.RecurrenceType = 0;
//remind1.NavigationUri = navigationUri;
// Register the reminder with the system.
ScheduledActionService.Add(remind1);
Reminder remind2 = new Reminder("Two");
//Uri navigationUri = new Uri("/Reminder1.xaml", UriKind.Relative);
remind2.Title = "Please take your Medicine now";
remind2.Content = "Click to see which tablets";
remind2.BeginTime = DateTime.Parse("26/01/2014 9:30:00");
//remind1.ExpirationTime = DateTime.Parse("26/01/2014 9:45:00");
//remind1.RecurrenceType = 0;
//remind1.NavigationUri = navigationUri;
// Register the reminder with the system.
ScheduledActionService.Add(remind2);
Reminder remind3 = new Reminder("Three");
//Uri navigationUri = new Uri("/Reminder1.xaml", UriKind.Relative);
remind3.Title = "Please take your Medicine now";
remind3.Content = "Click to see which tablets";
remind3.BeginTime = DateTime.Parse("26/01/2014 9:30:00");
//remind1.ExpirationTime = DateTime.Parse("26/01/2014 9:45:00");
//remind1.RecurrenceType = 0;
//remind1.NavigationUri = navigationUri;
// Register the reminder with the system.
ScheduledActionService.Add(remind3);
/*
Reminder remind2 = new Reminder("Time for your medicine");
Uri navigationUri2 = new Uri("/Reminder2.xaml", UriKind.Relative);
remind2.Title = "Please take your Medicine now";
remind2.Content = "Click to see which tablets";
remind2.BeginTime = DateTime.Parse("26/01/2014 9:30:00");
remind2.ExpirationTime = DateTime.Parse("26/01/2014 9:45:00");
remind2.RecurrenceType = 0;
remind2.NavigationUri = navigationUri2;
// Register the reminder with the system.
ScheduledActionService.Add(remind2);
Reminder remind3 = new Reminder("Time for your medicine");
Uri navigationUri3 = new Uri("/Reminder3.xaml", UriKind.Relative);
remind3.Title = "Time for your Doctors Appointment";
remind3.Content = "Click to see which tablets";
remind3.BeginTime = DateTime.Parse("26/01/2014 9:30:00");
remind3.ExpirationTime = DateTime.Parse("26/01/2014 9:45:00");
remind3.RecurrenceType = 0;
remind3.NavigationUri = navigationUri3;
// Register the reminder with the system.
ScheduledActionService.Add(remind3);*/
SaveAppointmentTask saveAppointmentTask = new SaveAppointmentTask();
saveAppointmentTask.StartTime = DateTime.Now.AddHours(0);
saveAppointmentTask.EndTime = DateTime.Now.AddHours(1);
saveAppointmentTask.Subject = "Doctors Name";
saveAppointmentTask.Location = "Doctors Location";
saveAppointmentTask.Details = "Appointment details";
saveAppointmentTask.IsAllDayEvent = false;
saveAppointmentTask.Reminder = Reminder.FiveMinutes;
saveAppointmentTask.AppointmentStatus = Microsoft.Phone.UserData.AppointmentStatus.Busy;
saveAppointmentTask.Show();
}
catch (Exception e)
{
System.Diagnostics.Debugger.Log(1, "Gen", "Hen");
}
R1.StrokeThickness /= 2;
R2.StrokeThickness /= 2;
R3.StrokeThickness /= 2;
R4.StrokeThickness /= 2;
R5.StrokeThickness /= 2;
R6.StrokeThickness /= 2;
R7.StrokeThickness /= 2;
R8.StrokeThickness /= 2;
R9.StrokeThickness /= 2;
R10.StrokeThickness /= 2;
R11.StrokeThickness /= 2;
R12.StrokeThickness /= 2;
R13.StrokeThickness /= 2;
R14.StrokeThickness /= 2;
R15.StrokeThickness /= 2;
R16.StrokeThickness /= 2;
R17.StrokeThickness /= 2;
R18.StrokeThickness /= 2;
R19.StrokeThickness /= 2;
R20.StrokeThickness /= 2;
R21.StrokeThickness /= 2;
R22.StrokeThickness /= 2;
R23.StrokeThickness /= 2;
R24.StrokeThickness /= 2;
R25.StrokeThickness /= 2;
R26.StrokeThickness /= 2;
R27.StrokeThickness /= 2;
R28.StrokeThickness /= 2;
R29.StrokeThickness /= 2;
R30.StrokeThickness /= 2;
R31.StrokeThickness /= 2;
R32.StrokeThickness /= 2;
R33.StrokeThickness /= 2;
R34.StrokeThickness /= 2;
R35.StrokeThickness /= 2;
}
private void tappee()
{
R1.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R2.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R3.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R4.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R5.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R6.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R7.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R8.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R9.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R10.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R11.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R12.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R13.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R14.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R15.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R16.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R17.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R18.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R19.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R20.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R21.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R22.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R23.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R24.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
//R29.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black); --> Present date
R26.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R27.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R28.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R25.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R30.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R31.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R32.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R33.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R34.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
R35.Fill = new SolidColorBrush(System.Windows.Media.Colors.Black);
}
private void Grid_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R1.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
//TextBlock HorizontalAlignment="Left" Margin="429,32,0,0" TextWrapping="Wrap" Text="Sat" VerticalAlignment="Top" Grid.Row="1"/>
R1.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R2.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R2.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_3(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R3.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R3.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_4(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R4.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R4.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_5(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R5.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R5.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_6(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R6.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R6.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_7(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R7.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R7.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_8(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R8.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R8.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_9(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R9.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R9.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_10(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R10.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R10.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_11(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R11.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R11.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_12(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R12.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R12.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_13(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R13.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R13.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_14(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R14.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R14.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_15(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R15.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R15.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_16(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R16.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R16.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_17(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R17.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R17.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_18(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R18.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R18.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_19(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R19.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R19.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_20(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R20.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R20.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_21(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R21.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R21.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_22(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R22.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R22.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_23(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R23.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R23.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_24(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R24.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R24.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_29(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R29.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R29.Fill = new SolidColorBrush(System.Windows.Media.Colors.Green);
Doctor.Text = "Dr. Syed Sufiyan Neuro";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_26(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R26.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R26.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_27(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R27.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R27.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_28(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R28.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R28.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "No Appointments Today";
MedA.Text = "No medicines Today";
MedB.Text = "";
}
private void Grid_Tap_25(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R25.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R25.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "Dr. Saptarshi Prakash Cardio";
MedA.Text = "No medicines today";
MedB.Text = "";
}
private void Grid_Tap_30(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R30.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R30.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "";
MedA.Text = "Disprin 300mg";
MedB.Text = "Paracetamol 200mg";
}
private void Grid_Tap_31(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R31.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R31.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "";
MedA.Text = "Disprin 300mg";
MedB.Text = "Paracetamol 200mg";
}
private void Grid_Tap_32(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R32.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R32.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "Dr. Karthikeyan Ortho";
MedA.Text = "Disprin 300mg";
MedB.Text = "Paracetamol 200mg";
}
private void Grid_Tap_33(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R33.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R33.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "";
MedA.Text = "No medicines today";
MedB.Text = "";
}
private void Grid_Tap_34(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R34.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R34.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "";
MedA.Text = "No medicines today";
MedB.Text = "";
}
private void Grid_Tap_35(object sender, System.Windows.Input.GestureEventArgs e)
{
tappee();
R35.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
Thread.Sleep(100);
R35.Fill = new SolidColorBrush(System.Windows.Media.Colors.DarkGray);
Doctor.Text = "";
MedA.Text = "No medicines today";
MedB.Text = "";
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
}
// Sample code for building a localized ApplicationBar
//private void BuildLocalizedApplicationBar()
//{
// // Set the page's ApplicationBar to a new instance of ApplicationBar.
// ApplicationBar = new ApplicationBar();
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
/* public struct appointments
{
Boolean appt;
String symptoms,Diagnosis,Meds,followUp;
}
public class MedDay
{
public appointments jan[35];
MedDay()
{
using (System.IO.StreamReader sr = System.IO.File.OpenText("gen.txt"))
{
string s = "";
i=0;
while ((s = sr.ReadLine()) != null)
{
jan[i] = s;
++int;
}
}
}
}*/
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition
{
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition;
using Microsoft.Azure.Management.CosmosDB.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition;
using Microsoft.Azure.Management.CosmosDB.Fluent.Models;
using System.Collections.Generic;
/// <summary>
/// The stage of the cosmos db definition allowing to specify the resource group.
/// </summary>
public interface IWithGroup :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition.IWithGroup<Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithKind>
{
}
/// <summary>
/// The stage of the cosmos db definition allowing to set the database account kind.
/// </summary>
public interface IWithKind :
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithKindBeta
{
/// <summary>
/// The database account kind for the CosmosDB account.
/// </summary>
/// <param name="kind">The account kind.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithConsistencyPolicy WithKind(string kind);
}
/// <summary>
/// The stage of the cosmos db definition allowing the definition of a Virtual Network ACL Rule.
/// </summary>
public interface IWithVirtualNetworkRule :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Specifies a Virtual Network ACL Rule for the CosmosDB account.
/// </summary>
/// <param name="virtualNetworkId">The ID of a virtual network.</param>
/// <param name="subnetName">
/// The name of the subnet within the virtual network; the subnet must have the service
/// endpoints enabled for 'Microsoft.AzureCosmosDB'.
/// </param>
/// <return>The next stage.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithCreate WithVirtualNetwork(string virtualNetworkId, string subnetName);
/// <summary>
/// Specifies the list of Virtual Network ACL Rules for the CosmosDB account.
/// </summary>
/// <param name="virtualNetworkRules">The list of Virtual Network ACL Rules.</param>
/// <return>The next stage.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithCreate WithVirtualNetworkRules(IList<Microsoft.Azure.Management.CosmosDB.Fluent.Models.VirtualNetworkRule> virtualNetworkRules);
}
/// <summary>
/// The stage of the cosmos db definition allowing to set the database account kind.
/// </summary>
public interface IWithKindBeta :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// The database account kind for the CosmosDB account.
/// </summary>
/// <param name="kind">The account kind.</param>
/// <param name="capabilities">The list of Cosmos DB capabilities for the account.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithConsistencyPolicy WithKind(DatabaseAccountKind kind, params Capability[] capabilities);
/// <summary>
/// Creates a Cassandra CosmosDB account.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithConsistencyPolicy WithDataModelCassandra();
/// <summary>
/// Creates a MongoDB CosmosDB account.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithConsistencyPolicy WithDataModelMongoDB();
/// <summary>
/// Creates an Azure Table CosmosDB account.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithConsistencyPolicy WithDataModelAzureTable();
/// <summary>
/// Creates a Gremlin CosmosDB account.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithConsistencyPolicy WithDataModelGremlin();
/// <summary>
/// Creates a SQL CosmosDB account.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithConsistencyPolicy WithDataModelSql();
}
/// <summary>
/// The stage of the definition which contains all the minimum required inputs for
/// the resource to be created, but also allows
/// for any other optional settings to be specified.
/// </summary>
public interface IWithCreate :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.CosmosDB.Fluent.ICosmosDBAccount>,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithConsistencyPolicy,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithReadReplication,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithIpRangeFilter,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithVirtualNetworkRule,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithTags<Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithCreate>
{
}
/// <summary>
/// The stage of the cosmos db definition allowing the definition of a write location.
/// </summary>
public interface IWithReadReplication
{
/// <summary>
/// A georeplication location for the CosmosDB account.
/// </summary>
/// <param name="region">The region for the location.</param>
/// <return>The next stage.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithCreate WithReadReplication(Region region);
}
/// <summary>
/// The stage of the cosmos db definition allowing to set the IP range filter.
/// </summary>
public interface IWithIpRangeFilter
{
/// <summary>
/// CosmosDB Firewall Support: This value specifies the set of IP addresses or IP address ranges in CIDR
/// form to be included as the allowed list of client IPs for a given database account. IP addresses/ranges
/// must be comma separated and must not contain any spaces.
/// </summary>
/// <param name="ipRangeFilter">Specifies the set of IP addresses or IP address ranges.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithCreate WithIpRangeFilter(string ipRangeFilter);
}
/// <summary>
/// The stage of the cosmos db definition allowing the definition of a read location.
/// </summary>
public interface IWithWriteReplication
{
/// <summary>
/// A georeplication location for the CosmosDB account.
/// </summary>
/// <param name="region">The region for the location.</param>
/// <return>The next stage.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithCreate WithWriteReplication(Region region);
}
/// <summary>
/// Grouping of cosmos db definition stages.
/// </summary>
public interface IDefinition :
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IBlank,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithGroup,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithKind,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithWriteReplication,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithReadReplication,
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithCreate
{
}
/// <summary>
/// The first stage of a cosmos db definition.
/// </summary>
public interface IBlank :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithRegion<Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithGroup>
{
}
/// <summary>
/// The stage of the cosmos db definition allowing to set the consistency policy.
/// </summary>
public interface IWithConsistencyPolicy
{
/// <summary>
/// The bounded staleness consistency policy for the CosmosDB account.
/// </summary>
/// <param name="maxStalenessPrefix">The max staleness prefix.</param>
/// <param name="maxIntervalInSeconds">The max interval in seconds.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithWriteReplication WithBoundedStalenessConsistency(long maxStalenessPrefix, int maxIntervalInSeconds);
/// <summary>
/// The strong consistency policy for the CosmosDB account.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithCreate WithStrongConsistency();
/// <summary>
/// The eventual consistency policy for the CosmosDB account.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithWriteReplication WithEventualConsistency();
/// <summary>
/// The session consistency policy for the CosmosDB account.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.CosmosDB.Fluent.CosmosDBAccount.Definition.IWithWriteReplication WithSessionConsistency();
}
}
| |
/******************************************************************************
* 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.Extensions.GetReplicaInfoResponse.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System.IO;
using Novell.Directory.Ldap.Asn1;
using Novell.Directory.Ldap.Rfc2251;
namespace Novell.Directory.Ldap.Extensions
{
/// <summary>
/// Retrieves the replica information from a GetReplicaInfoResponse object.
/// An object in this class is generated from an ExtendedResponse using the
/// ExtendedResponseFactory class.
/// The getReplicaInfoResponse extension uses the following OID:
/// 2.16.840.1.113719.1.27.100.18
/// </summary>
public class GetReplicaInfoResponse : LdapExtendedResponse
{
// Other info as returned by the server
private readonly int partitionID;
private readonly int replicaState;
private readonly int modificationTime;
private readonly int purgeTime;
private readonly int localPartitionID;
private readonly string partitionDN;
private readonly int replicaType;
private readonly int flags;
/// <summary>
/// Constructs an object from the responseValue which contains the
/// replica information.
/// The constructor parses the responseValue which has the following
/// format:
/// responseValue ::=
/// partitionID INTEGER
/// replicaState INTEGER
/// modificationTime INTEGER
/// purgeTime INTEGER
/// localPartitionID INTEGER
/// partitionDN OCTET STRING
/// replicaType INTEGER
/// flags INTEGER
/// </summary>
/// <exception>
/// IOException The response value could not be decoded.
/// </exception>
public GetReplicaInfoResponse(RfcLdapMessage rfcMessage) : base(rfcMessage)
{
if (ResultCode == LdapException.SUCCESS)
{
// parse the contents of the reply
var returnedValue = Value;
if (returnedValue == null)
throw new IOException("No returned value");
// Create a decoder object
var decoder = new LBERDecoder();
if (decoder == null)
throw new IOException("Decoding error");
// Parse the parameters in the order
var currentPtr = new MemoryStream(SupportClass.ToByteArray(returnedValue));
// Parse partitionID
var asn1_partitionID = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_partitionID == null)
throw new IOException("Decoding error");
partitionID = asn1_partitionID.intValue();
// Parse replicaState
var asn1_replicaState = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_replicaState == null)
throw new IOException("Decoding error");
replicaState = asn1_replicaState.intValue();
// Parse modificationTime
var asn1_modificationTime = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_modificationTime == null)
throw new IOException("Decoding error");
modificationTime = asn1_modificationTime.intValue();
// Parse purgeTime
var asn1_purgeTime = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_purgeTime == null)
throw new IOException("Decoding error");
purgeTime = asn1_purgeTime.intValue();
// Parse localPartitionID
var asn1_localPartitionID = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_localPartitionID == null)
throw new IOException("Decoding error");
localPartitionID = asn1_localPartitionID.intValue();
// Parse partitionDN
var asn1_partitionDN = (Asn1OctetString) decoder.decode(currentPtr);
if (asn1_partitionDN == null)
throw new IOException("Decoding error");
partitionDN = asn1_partitionDN.stringValue();
if ((object) partitionDN == null)
throw new IOException("Decoding error");
// Parse replicaType
var asn1_replicaType = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_replicaType == null)
throw new IOException("Decoding error");
replicaType = asn1_replicaType.intValue();
// Parse flags
var asn1_flags = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_flags == null)
throw new IOException("Decoding error");
flags = asn1_flags.intValue();
}
else
{
partitionID = 0;
replicaState = 0;
modificationTime = 0;
purgeTime = 0;
localPartitionID = 0;
partitionDN = "";
replicaType = 0;
flags = 0;
}
}
/// <summary>
/// Returns the numeric identifier for the partition.
/// </summary>
/// <returns>
/// Integer value specifying the partition ID.
/// </returns>
public virtual int getpartitionID()
{
return partitionID;
}
/// <summary>
/// Returns the current state of the replica.
/// </summary>
/// <returns>
/// Integer value specifying the current state of the replica. See
/// ReplicationConstants class for possible values for this field.
/// </returns>
/// <seealso cref="ReplicationConstants.Ldap_RS_BEGIN_ADD">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_DEAD_REPLICA">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_DYING_REPLICA">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_JS_0">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_JS_1">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_JS_2">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_LOCKED">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_MASTER_DONE">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_MASTER_START">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_SS_0">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_TRANSITION_ON">
/// </seealso>
public virtual int getreplicaState()
{
return replicaState;
}
/// <summary>
/// Returns the time of the most recent modification.
/// </summary>
/// <returns>
/// Integer value specifying the last modification time.
/// </returns>
public virtual int getmodificationTime()
{
return modificationTime;
}
/// <summary>
/// Returns the most recent time in which all data has been synchronized.
/// </summary>
/// <returns>
/// Integer value specifying the last purge time.
/// </returns>
public virtual int getpurgeTime()
{
return purgeTime;
}
/// <summary>
/// Returns the local numeric identifier for the replica.
/// </summary>
/// <returns>
/// Integer value specifying the local ID of the partition.
/// </returns>
public virtual int getlocalPartitionID()
{
return localPartitionID;
}
/// <summary>
/// Returns the distinguished name of the partition.
/// </summary>
/// <returns>
/// String value specifying the name of the partition read.
/// </returns>
public virtual string getpartitionDN()
{
return partitionDN;
}
/// <summary>
/// Returns the replica type.
/// See the ReplicationConstants class for possible values for
/// this field.
/// </summary>
/// <returns>
/// Integer identifying the type of the replica.
/// </returns>
/// <seealso cref="ReplicationConstants.Ldap_RT_MASTER">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_SECONDARY">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_READONLY">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_SUBREF">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_SPARSE_WRITE">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_SPARSE_READ">
/// </seealso>
public virtual int getreplicaType()
{
return replicaType;
}
/// <summary>
/// Returns flags that specify whether the replica is busy or is a boundary.
/// See the ReplicationConstants class for possible values for
/// this field.
/// </summary>
/// <returns>
/// Integer value specifying the flags for the replica.
/// </returns>
/// <seealso cref="ReplicationConstants.Ldap_DS_FLAG_BUSY">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_DS_FLAG_BOUNDARY">
/// </seealso>
public virtual int getflags()
{
return flags;
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmKeyboardList
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmKeyboardList() : base()
{
FormClosed += frmKeyboardList_FormClosed;
Load += frmKeyboardList_Load;
KeyPress += frmKeyboardList_KeyPress;
KeyDown += frmKeyboardList_KeyDown;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdNew;
public System.Windows.Forms.Button cmdNew {
get { return withEventsField_cmdNew; }
set {
if (withEventsField_cmdNew != null) {
withEventsField_cmdNew.Click -= cmdNew_Click;
}
withEventsField_cmdNew = value;
if (withEventsField_cmdNew != null) {
withEventsField_cmdNew.Click += cmdNew_Click;
}
}
}
private myDataGridView withEventsField_DataList1;
public myDataGridView DataList1 {
get { return withEventsField_DataList1; }
set {
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick -= DataList1_DblClick;
withEventsField_DataList1.KeyPress -= DataList1_KeyPress;
}
withEventsField_DataList1 = value;
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick += DataList1_DblClick;
withEventsField_DataList1.KeyPress += DataList1_KeyPress;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.Label lbl;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmKeyboardList));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdNew = new System.Windows.Forms.Button();
this.DataList1 = new myDataGridView();
this.txtSearch = new System.Windows.Forms.TextBox();
this.cmdExit = new System.Windows.Forms.Button();
this.lbl = new System.Windows.Forms.Label();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Select a Keyboard";
this.ClientSize = new System.Drawing.Size(259, 433);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmKeyboardList";
this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNew.Text = "&New";
this.cmdNew.Size = new System.Drawing.Size(97, 52);
this.cmdNew.Location = new System.Drawing.Point(6, 375);
this.cmdNew.TabIndex = 4;
this.cmdNew.TabStop = false;
this.cmdNew.BackColor = System.Drawing.SystemColors.Control;
this.cmdNew.CausesValidation = true;
this.cmdNew.Enabled = true;
this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNew.Name = "cmdNew";
//'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State)
this.DataList1.Size = new System.Drawing.Size(244, 342);
this.DataList1.Location = new System.Drawing.Point(6, 27);
this.DataList1.TabIndex = 2;
this.DataList1.Name = "DataList1";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(199, 19);
this.txtSearch.Location = new System.Drawing.Point(51, 3);
this.txtSearch.TabIndex = 1;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(97, 52);
this.cmdExit.Location = new System.Drawing.Point(153, 375);
this.cmdExit.TabIndex = 3;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lbl.Text = "&Search :";
this.lbl.Size = new System.Drawing.Size(40, 13);
this.lbl.Location = new System.Drawing.Point(8, 6);
this.lbl.TabIndex = 0;
this.lbl.BackColor = System.Drawing.Color.Transparent;
this.lbl.Enabled = true;
this.lbl.ForeColor = System.Drawing.SystemColors.ControlText;
this.lbl.Cursor = System.Windows.Forms.Cursors.Default;
this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lbl.UseMnemonic = true;
this.lbl.Visible = true;
this.lbl.AutoSize = true;
this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lbl.Name = "lbl";
this.Controls.Add(cmdNew);
this.Controls.Add(DataList1);
this.Controls.Add(txtSearch);
this.Controls.Add(cmdExit);
this.Controls.Add(lbl);
((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_855 : MapLoop
{
public M_855() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BAK() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new CSH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_SAC(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new DIS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new INC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new LDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 },
new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 },
new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new CTB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_N9(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 },
new L_ADV(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_PO1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100000 },
new L_CTT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
//1000
public class L_SAC : MapLoop
{
public L_SAC(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2000
public class L_N9 : MapLoop
{
public L_N9(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
});
}
}
//3000
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//4000
public class L_ADV : MapLoop
{
public L_ADV(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ADV() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MTX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//5000
public class L_PO1 : MapLoop
{
public L_PO1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PO1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PO3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 40 },
new L_PID(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_SAC_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new IT8() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CSH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new DIS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 },
new INC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new SDQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 500 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new LDT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new L_ACK(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 104 },
new MAN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new CTB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_QTY(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_PKG(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 },
new L_SCH(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 },
new L_N9_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 },
new L_SLN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
});
}
}
//5100
public class L_PID : MapLoop
{
public L_PID(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PID() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//5200
public class L_SAC_1 : MapLoop
{
public L_SAC_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//5300
public class L_ACK : MapLoop
{
public L_ACK(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ACK() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//5400
public class L_QTY : MapLoop
{
public L_QTY(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//5500
public class L_PKG : MapLoop
{
public L_PKG(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new PKG() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//5600
public class L_SCH : MapLoop
{
public L_SCH(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SCH() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//5700
public class L_N9_1 : MapLoop
{
public L_N9_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
});
}
}
//5800
public class L_N1_1 : MapLoop
{
public L_N1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new FOB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new SCH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 },
new TD1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new TD5() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new TD4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PKG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
});
}
}
//5900
public class L_SLN : MapLoop
{
public L_SLN(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SLN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1000 },
new PO3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new CTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
new PAM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new ACK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 104 },
new L_SAC_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new PO4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TAX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new ADV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_QTY_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_N9_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_N1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//5910
public class L_SAC_2 : MapLoop
{
public L_SAC_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SAC() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//5920
public class L_QTY_1 : MapLoop
{
public L_QTY_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//5930
public class L_N9_2 : MapLoop
{
public L_N9_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N9() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//5940
public class L_N1_2 : MapLoop
{
public L_N1_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//6000
public class L_CTT : MapLoop
{
public L_CTT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CTT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
public enum AvailableBlendFactor
{
One,
Zero,
SrcColor,
SrcAlpha,
DstColor,
DstAlpha,
OneMinusSrcColor,
OneMinusSrcAlpha,
OneMinusDstColor,
OneMinusDstAlpha
};
public enum AvailableBlendOps
{
OFF,
Add,
Sub,
RevSub,
Min,
Max
//Direct X11 only
//LogicalClear,
//LogicalSet,
//LogicalCopy,
//LogicalCopyInverted,
//LogicalNoop,
//LogicalInvert,
//LogicalAnd,
//LogicalNand,
//LogicalOr,
//LogicalNor,
//LogicalXor,
//LogicalEquiv,
//LogicalAndReverse,
//LogicalAndInverted,
//LogicalOrReverse,
//LogicalOrInverted
};
public class CommonBlendTypes
{
public string Name;
public AvailableBlendFactor SourceFactor;
public AvailableBlendFactor DestFactor;
public CommonBlendTypes( string name, AvailableBlendFactor sourceFactor, AvailableBlendFactor destFactor )
{
Name = name;
SourceFactor = sourceFactor;
DestFactor = destFactor;
}
}
[Serializable]
public class BlendOpsHelper
{
private const string BlendModesRGBStr = "Blend RGB";
private const string BlendModesAlphaStr = "Blend Alpha";
private const string BlendOpsRGBStr = "Blend Op RGB";
private const string BlendOpsAlphaStr = "Blend Op Alpha";
private const string SourceFactorStr = "Src";
private const string DstFactorStr = "Dst";
private const string SingleBlendFactorStr = "Blend {0} {1}";
private const string SeparateBlendFactorStr = "Blend {0} {1} , {2} {3}";
private const string SingleBlendOpStr = "BlendOp {0}";
private const string SeparateBlendOpStr = "BlendOp {0} , {1}";
private string[] m_commonBlendTypesArr;
private List<CommonBlendTypes> m_commonBlendTypes = new List<CommonBlendTypes> { new CommonBlendTypes("<OFF>", AvailableBlendFactor.Zero, AvailableBlendFactor.Zero ),
new CommonBlendTypes("Custom", AvailableBlendFactor.Zero, AvailableBlendFactor.Zero ) ,
new CommonBlendTypes("Alpha Blend", AvailableBlendFactor.SrcAlpha, AvailableBlendFactor.OneMinusSrcAlpha ) ,
new CommonBlendTypes("Premultiplied ", AvailableBlendFactor.One, AvailableBlendFactor.OneMinusSrcAlpha ),
new CommonBlendTypes("Additive", AvailableBlendFactor.One, AvailableBlendFactor.One ),
new CommonBlendTypes("Soft Additive", AvailableBlendFactor.OneMinusDstColor, AvailableBlendFactor.One ),
new CommonBlendTypes("Multiplicative", AvailableBlendFactor.DstColor, AvailableBlendFactor.Zero ),
new CommonBlendTypes("2x Multiplicative", AvailableBlendFactor.DstColor, AvailableBlendFactor.SrcColor ) };
[SerializeField]
private bool m_enabled = false;
// Blend Factor
// RGB
[SerializeField]
private int m_currentIndex = 0;
[SerializeField]
private AvailableBlendFactor m_sourceFactorRGB = AvailableBlendFactor.Zero;
[SerializeField]
private AvailableBlendFactor m_destFactorRGB = AvailableBlendFactor.Zero;
// Alpha
[SerializeField]
private int m_currentAlphaIndex = 0;
[SerializeField]
private AvailableBlendFactor m_sourceFactorAlpha = AvailableBlendFactor.Zero;
[SerializeField]
private AvailableBlendFactor m_destFactorAlpha = AvailableBlendFactor.Zero;
//Blend Ops
[SerializeField]
private bool m_blendOpEnabled = false;
[SerializeField]
private AvailableBlendOps m_blendOpRGB = AvailableBlendOps.Add;
[SerializeField]
private AvailableBlendOps m_blendOpAlpha = AvailableBlendOps.Add;
public BlendOpsHelper()
{
m_commonBlendTypesArr = new string[ m_commonBlendTypes.Count ];
for ( int i = 0; i < m_commonBlendTypesArr.Length; i++ )
{
m_commonBlendTypesArr[ i ] = m_commonBlendTypes[ i ].Name;
}
}
public void Draw( UndoParentNode owner, bool customBlendAvailable)
{
m_enabled = customBlendAvailable;
// RGB
EditorGUI.BeginChangeCheck();
m_currentIndex = owner.EditorGUILayoutPopup( BlendModesRGBStr, m_currentIndex, m_commonBlendTypesArr );
if ( EditorGUI.EndChangeCheck() )
{
if ( m_currentIndex > 1 )
{
m_sourceFactorRGB = m_commonBlendTypes[ m_currentIndex ].SourceFactor;
m_destFactorRGB = m_commonBlendTypes[ m_currentIndex ].DestFactor;
}
}
EditorGUI.BeginDisabledGroup( m_currentIndex == 0 );
EditorGUI.BeginChangeCheck();
float cached = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 40;
EditorGUILayout.BeginHorizontal();
m_sourceFactorRGB = ( AvailableBlendFactor )owner.EditorGUILayoutEnumPopup( SourceFactorStr, m_sourceFactorRGB );
EditorGUI.indentLevel--;
EditorGUIUtility.labelWidth = 25;
m_destFactorRGB = ( AvailableBlendFactor ) owner.EditorGUILayoutEnumPopup( DstFactorStr, m_destFactorRGB );
EditorGUI.indentLevel++;
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = cached;
if ( EditorGUI.EndChangeCheck() )
{
CheckRGBIndex();
}
EditorGUI.BeginChangeCheck();
m_blendOpRGB = ( AvailableBlendOps )owner.EditorGUILayoutEnumPopup( BlendOpsRGBStr, m_blendOpRGB );
if ( EditorGUI.EndChangeCheck() )
{
m_blendOpEnabled = m_blendOpRGB != AvailableBlendOps.OFF;
}
EditorGUI.EndDisabledGroup();
//if ( m_currentIndex == 0 )
// m_currentAlphaIndex = 0;
//if ( m_blendOpRGB == AvailableBlendOps.OFF )
// m_blendOpAlpha = AvailableBlendOps.OFF;
// Alpha
EditorGUILayout.Separator();
//EditorGUI.BeginDisabledGroup( m_currentAlphaIndex == 0 );
EditorGUI.BeginChangeCheck();
m_currentAlphaIndex = owner.EditorGUILayoutPopup( BlendModesAlphaStr, m_currentAlphaIndex, m_commonBlendTypesArr );
if ( EditorGUI.EndChangeCheck() )
{
if ( m_currentAlphaIndex > 0 )
{
m_sourceFactorAlpha = m_commonBlendTypes[ m_currentAlphaIndex ].SourceFactor;
m_destFactorAlpha = m_commonBlendTypes[ m_currentAlphaIndex ].DestFactor;
}
}
//EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(m_currentAlphaIndex == 0);
//EditorGUI.BeginDisabledGroup( m_currentAlphaIndex == 0 );
EditorGUI.BeginChangeCheck();
cached = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 40;
EditorGUILayout.BeginHorizontal();
m_sourceFactorAlpha = ( AvailableBlendFactor )owner.EditorGUILayoutEnumPopup( SourceFactorStr, m_sourceFactorAlpha );
EditorGUI.indentLevel--;
EditorGUIUtility.labelWidth = 25;
m_destFactorAlpha = ( AvailableBlendFactor ) owner.EditorGUILayoutEnumPopup( DstFactorStr, m_destFactorAlpha );
EditorGUI.indentLevel++;
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = cached;
if ( EditorGUI.EndChangeCheck() )
{
CheckAlphaIndex();
}
m_blendOpAlpha = ( AvailableBlendOps ) owner.EditorGUILayoutEnumPopup( BlendOpsAlphaStr, m_blendOpAlpha );
EditorGUI.EndDisabledGroup();
EditorGUILayout.Separator();
}
void CheckRGBIndex()
{
int count = m_commonBlendTypes.Count;
m_currentIndex = 1;
for ( int i = 1; i < count; i++ )
{
if ( m_commonBlendTypes[ i ].SourceFactor == m_sourceFactorRGB && m_commonBlendTypes[ i ].DestFactor == m_destFactorRGB )
{
m_currentIndex = i;
return;
}
}
}
void CheckAlphaIndex()
{
int count = m_commonBlendTypes.Count;
m_currentAlphaIndex = 1;
for ( int i = 1; i < count; i++ )
{
if ( m_commonBlendTypes[ i ].SourceFactor == m_sourceFactorAlpha && m_commonBlendTypes[ i ].DestFactor == m_destFactorAlpha )
{
m_currentAlphaIndex = i;
if ( m_currentAlphaIndex > 0 && m_currentIndex == 0 )
m_currentIndex = 1;
return;
}
}
if ( m_currentAlphaIndex > 0 && m_currentIndex == 0 )
m_currentIndex = 1;
}
public void ReadFromString( ref uint index, ref string[] nodeParams )
{
m_currentIndex = Convert.ToInt32( nodeParams[ index++ ] );
m_sourceFactorRGB = ( AvailableBlendFactor ) Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
m_destFactorRGB = ( AvailableBlendFactor ) Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
m_currentAlphaIndex = Convert.ToInt32( nodeParams[ index++ ] );
m_sourceFactorAlpha = ( AvailableBlendFactor ) Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
m_destFactorAlpha = ( AvailableBlendFactor ) Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
m_blendOpRGB = ( AvailableBlendOps ) Enum.Parse( typeof( AvailableBlendOps ), nodeParams[ index++ ] );
m_blendOpAlpha = ( AvailableBlendOps ) Enum.Parse( typeof( AvailableBlendOps ), nodeParams[ index++ ] );
m_enabled = (m_currentIndex > 0 || m_currentAlphaIndex > 0);
m_blendOpEnabled = ( m_blendOpRGB != AvailableBlendOps.OFF );
}
public void WriteToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentIndex );
IOUtils.AddFieldValueToString( ref nodeInfo, m_sourceFactorRGB );
IOUtils.AddFieldValueToString( ref nodeInfo, m_destFactorRGB );
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentAlphaIndex );
IOUtils.AddFieldValueToString( ref nodeInfo, m_sourceFactorAlpha );
IOUtils.AddFieldValueToString( ref nodeInfo, m_destFactorAlpha );
IOUtils.AddFieldValueToString( ref nodeInfo, m_blendOpRGB );
IOUtils.AddFieldValueToString( ref nodeInfo, m_blendOpAlpha );
}
public string CreateBlendOps()
{
string result = "\t\t" + CurrentBlendFactor + "\n";
if ( m_blendOpEnabled )
{
result += "\t\t" + CurrentBlendOp + "\n";
}
return result;
}
public string CurrentBlendFactorSingle { get { return string.Format( SingleBlendFactorStr, m_sourceFactorRGB, m_destFactorRGB ); } }
//public string CurrentBlendFactorSingleAlpha { get { return string.Format(SeparateBlendFactorStr, m_sourceFactorRGB, m_destFactorRGB, m_sourceFactorAlpha, m_destFactorAlpha); } }
public string CurrentBlendFactorSeparate { get { return string.Format( SeparateBlendFactorStr, (m_currentIndex > 0 ? m_sourceFactorRGB : AvailableBlendFactor.One), (m_currentIndex > 0 ? m_destFactorRGB: AvailableBlendFactor.Zero), m_sourceFactorAlpha, m_destFactorAlpha ); } }
public string CurrentBlendFactor { get { return ( ( m_currentAlphaIndex > 0 ) ? CurrentBlendFactorSeparate : CurrentBlendFactorSingle ); } }
public string CurrentBlendOpSingle { get { return string.Format( SingleBlendOpStr, m_blendOpRGB ); } }
public string CurrentBlendOpSeparate { get { return string.Format( SeparateBlendOpStr, (m_currentIndex > 0 ? m_blendOpRGB : AvailableBlendOps.Add), m_blendOpAlpha ); } }
public string CurrentBlendOp { get { return ( ( m_currentAlphaIndex > 0 && m_blendOpAlpha != AvailableBlendOps.OFF ) ? CurrentBlendOpSeparate : CurrentBlendOpSingle ); } }
public bool Active { get { return m_enabled && ( m_currentIndex > 0 || m_currentAlphaIndex > 0); } }
}
}
| |
/*
* 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.Reflection;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
namespace OpenSim.Region.Framework.Scenes.Tests
{
/// <summary>
/// Basic scene object status tests
/// </summary>
[TestFixture]
public class SceneObjectStatusTests : OpenSimTestCase
{
private TestScene m_scene;
private UUID m_ownerId = TestHelpers.ParseTail(0x1);
private SceneObjectGroup m_so1;
private SceneObjectGroup m_so2;
[SetUp]
public void Init()
{
m_scene = new SceneHelpers().SetupScene();
m_so1 = SceneHelpers.CreateSceneObject(1, m_ownerId, "so1", 0x10);
m_so2 = SceneHelpers.CreateSceneObject(1, m_ownerId, "so2", 0x20);
}
[Test]
public void TestSetTemporary()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_so1.ScriptSetTemporaryStatus(true);
// Is this really the correct flag?
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.TemporaryOnRez));
Assert.That(m_so1.Backup, Is.False);
// Test setting back to non-temporary
m_so1.ScriptSetTemporaryStatus(false);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Backup, Is.True);
}
[Test]
public void TestSetPhantomSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhantomStatus(true);
// Console.WriteLine("so.RootPart.Flags [{0}]", so.RootPart.Flags);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom));
m_so1.ScriptSetPhantomStatus(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetNonPhysicsVolumeDetectSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetVolumeDetect(true);
// Console.WriteLine("so.RootPart.Flags [{0}]", so.RootPart.Flags);
// PrimFlags.JointLP2P is incorrect it now means VolumeDetect (as defined by viewers)
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom | PrimFlags.JointLP2P));
m_so1.ScriptSetVolumeDetect(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetPhysicsSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Physics));
m_so1.ScriptSetPhysicsStatus(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetPhysicsVolumeDetectSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
m_so1.ScriptSetVolumeDetect(true);
// PrimFlags.JointLP2P is incorrect it now means VolumeDetect (as defined by viewers)
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom | PrimFlags.Physics | PrimFlags.JointLP2P));
m_so1.ScriptSetVolumeDetect(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Physics));
}
[Test]
public void TestSetPhysicsLinkset()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
m_so1.ScriptSetPhysicsStatus(false);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsBothPhysical()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so1.ScriptSetPhysicsStatus(true);
m_so2.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsRootPhysicalOnly()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so1.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsChildPhysicalOnly()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so2.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.None));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Plugins.CountlySDK.Enums;
using Plugins.CountlySDK.Helpers;
using Plugins.CountlySDK.Models;
namespace Plugins.CountlySDK.Services
{
public class ConsentCountlyService : AbstractBaseService
{
internal bool RequiresConsent { get; private set; }
internal readonly RequestCountlyHelper _requestCountlyHelper;
private Dictionary<string, Consents[]> _countlyConsentGroups;
internal readonly Dictionary<Consents, bool> CountlyConsents;
internal ConsentCountlyService(CountlyConfiguration config, CountlyLogHelper logHelper, ConsentCountlyService consentService, RequestCountlyHelper requestCountlyHelper) : base(config, logHelper, consentService)
{
Log.Debug("[ConsentCountlyService] Initializing.");
_requestCountlyHelper = requestCountlyHelper;
CountlyConsents = new Dictionary<Consents, bool>();
RequiresConsent = _configuration.RequiresConsent;
_countlyConsentGroups = new Dictionary<string, Consents[]>(_configuration.ConsentGroups);
if (_configuration.EnabledConsentGroups != null) {
foreach (KeyValuePair<string, Consents[]> entry in _countlyConsentGroups) {
if (_configuration.EnabledConsentGroups.Contains(entry.Key)) {
SetConsentInternal(entry.Value, true, sendRequest: false, ConsentChangedAction.Initialization);
}
}
}
SetConsentInternal(_configuration.GivenConsent, true, sendRequest: false, ConsentChangedAction.Initialization);
}
#region Public Methods
/// <summary>
/// Check if consent for the specific feature has been given
/// </summary>
/// <param name="consent">The consent that should be checked</param>
/// <returns>Returns "true" if the consent for the checked feature has been provided</returns>
public bool CheckConsent(Consents consent)
{
lock (LockObj) {
Log.Info("[ConsentCountlyService] CheckConsent : consent = " + consent.ToString());
return CheckConsentInternal(consent);
}
}
/// <summary>
/// An internal function to check if consent for the specific feature has been given
/// </summary>
/// <param name="consent">The consent that should be checked</param>
/// <returns>Returns "true" if the consent for the checked feature has been provided</returns>
internal bool CheckConsentInternal(Consents consent)
{
bool result = !RequiresConsent || (CountlyConsents.ContainsKey(consent) && CountlyConsents[consent]);
Log.Verbose("[ConsentCountlyService] CheckConsent : consent = " + consent.ToString() + ", result = " + result);
return result;
}
/// <summary>
/// Check if consent for any feature has been given
/// </summary>
/// <returns>Returns "true" if consent is given for any of the possible features</returns>
internal bool AnyConsentGiven()
{
bool result = !RequiresConsent;
if (result) {
Log.Verbose("[ConsentCountlyService] AnyConsentGiven = " + result);
return result;
}
foreach (KeyValuePair<Consents, bool> entry in CountlyConsents) {
if (entry.Value) {
result = true;
break;
}
}
Log.Verbose("[ConsentCountlyService] AnyConsentGiven = " + result);
return result;
}
/// <summary>
/// Give consent to the provided features
/// </summary>
/// <param name="consents">array of consents for which consent should be given</param>
/// <returns></returns>
public void GiveConsent(Consents[] consents)
{
lock (LockObj) {
Log.Info("[ConsentCountlyService] GiveConsent : consents = " + (consents != null));
if (!RequiresConsent) {
Log.Debug("[ConsentCountlyService] GiveConsent: Please set consent to be required before calling this!");
return;
}
SetConsentInternal(consents, true, sendRequest: true);
}
}
/// <summary>
/// Give consent to all features
/// </summary>
/// <returns></returns>
public void GiveConsentAll()
{
lock (LockObj) {
Log.Info("[ConsentCountlyService] GiveConsentAll");
if (!RequiresConsent) {
Log.Debug("[ConsentCountlyService] GiveConsentAll: Please set consent to be required before calling this!");
return;
}
Consents[] consents = Enum.GetValues(typeof(Consents)).Cast<Consents>().ToArray();
SetConsentInternal(consents, true, sendRequest: true);
}
}
/// <summary>
/// Remove consent from the provided features
/// </summary>
/// <param name="consents">array of consents for which consent should be removed</param>
/// <returns></returns>
public void RemoveConsent(Consents[] consents)
{
lock (LockObj) {
Log.Info("[ConsentCountlyService] RemoveConsent : consents = " + (consents != null));
if (!RequiresConsent) {
Log.Debug("[ConsentCountlyService] RemoveConsent: Please set consent to be required before calling this!");
return;
}
if (consents == null) {
Log.Debug("[ConsentCountlyService] Calling RemoveConsent with null consents list!");
return;
}
//Remove Duplicates entries
consents = consents.Distinct().ToArray();
SetConsentInternal(consents, false, sendRequest: true);
}
}
/// <summary>
/// Remove consent from all features
/// </summary>
/// <returns></returns>
public void RemoveAllConsent()
{
lock (LockObj) {
Log.Info("[ConsentCountlyService] RemoveAllConsent");
if (!RequiresConsent) {
Log.Debug("[ConsentCountlyService] RemoveAllConsent: Please set consent to be required before calling this!");
return;
}
SetConsentInternal(CountlyConsents.Keys.ToArray(), false, sendRequest: true);
}
}
/// <summary>
/// Give consent to the provided feature groups
/// </summary>
/// <param name="groupName">array of consent group for which consent should be given</param>
/// <returns></returns>
public void GiveConsentToGroup(string[] groupName)
{
lock (LockObj) {
Log.Info("[ConsentCountlyService] GiveConsentToGroup : groupName = " + (groupName != null));
if (!RequiresConsent) {
Log.Debug("[ConsentCountlyService] GiveConsentToGroup: Please set consent to be required before calling this!");
return;
}
if (groupName == null) {
Log.Debug("[ConsentCountlyService] Calling GiveConsentToGroup with null groupName!");
return;
}
foreach (string name in groupName) {
if (_countlyConsentGroups.ContainsKey(name)) {
Consents[] consents = _countlyConsentGroups[name];
SetConsentInternal(consents, true, sendRequest: true);
}
}
}
}
/// <summary>
/// Remove consent from the provided feature groups
/// </summary>
/// <param name="groupName">An array of consent group names for which consent should be removed</param>
/// <returns></returns>
public void RemoveConsentOfGroup(string[] groupName)
{
lock (LockObj) {
Log.Info("[ConsentCountlyService] RemoveConsentOfGroup : groupName = " + (groupName != null));
if (!RequiresConsent) {
Log.Debug("[ConsentCountlyService] RemoveConsentOfGroup: Please set consent to be required before calling this!");
return;
}
if (groupName == null) {
Log.Debug("[ConsentCountlyService] Calling RemoveConsentOfGroup with null groupName!");
return;
}
foreach (string name in groupName) {
if (_countlyConsentGroups.ContainsKey(name)) {
Consents[] consents = _countlyConsentGroups[name];
SetConsentInternal(consents, false, sendRequest: true);
}
}
}
}
#endregion
#region Internal Methods
/// <summary>
/// Internal method that send consent changes to server.
/// </summary>
/// <param name="consents">List of consent</param>
/// <param name="value">value to be set</param>
internal async Task SendConsentChanges(List<Consents> consents, bool value)
{
if (!RequiresConsent || consents.Count == 0 || _requestCountlyHelper == null) {
return;
}
JObject jObj = new JObject();
foreach (Consents consent in consents) {
jObj.Add(GetConsentKey(consent), value);
}
Dictionary<string, object> requestParams =
new Dictionary<string, object> { { "consent", jObj } };
_requestCountlyHelper.AddToRequestQueue(requestParams);
await _requestCountlyHelper.ProcessQueue();
}
#endregion
#region Helper Methods
/// <summary>
/// Private method that returns consent key.
/// </summary>
/// <param name="consent">a consent</param>
///<returns>string</returns>
private string GetConsentKey(Consents consent)
{
string key = "";
switch (consent) {
case Consents.Clicks:
key = "clicks";
break;
case Consents.Crashes:
key = "crashes";
break;
case Consents.Events:
key = "events";
break;
case Consents.Location:
key = "location";
break;
case Consents.Push:
key = "push";
break;
case Consents.RemoteConfig:
key = "remote-config";
break;
case Consents.Sessions:
key = "sessions";
break;
case Consents.StarRating:
key = "star-rating";
break;
case Consents.Users:
key = "users";
break;
case Consents.Views:
key = "views";
break;
case Consents.Feedback:
key = "feedback";
break;
}
return key;
}
/// <summary>
/// Private method that update selected consents.
/// </summary>
/// <param name="consents">List of consent</param>
/// <param name="value">value to be set</param>
internal async void SetConsentInternal(Consents[] consents, bool value, bool sendRequest = false, ConsentChangedAction action = ConsentChangedAction.ConsentUpdated)
{
if (consents == null) {
Log.Debug("[ConsentCountlyService] Calling SetConsentInternal with null consents list!");
return;
}
List<Consents> updatedConsents = new List<Consents>(consents.Length);
foreach (Consents consent in consents) {
if (CountlyConsents.ContainsKey(consent) && CountlyConsents[consent] == value) {
continue;
}
if (!CountlyConsents.ContainsKey(consent) && !value) {
continue;
}
updatedConsents.Add(consent);
CountlyConsents[consent] = value;
Log.Debug("[ConsentCountlyService] Setting consent for: [" + consent.ToString() + "] with value: [" + value + "]");
}
if (sendRequest) {
await SendConsentChanges(updatedConsents, value);
}
NotifyListeners(updatedConsents, value, action);
}
/// <summary>
/// On consents changed, call <code>ConsentChanged</code> on all listeners.
/// </summary>
/// <param name="updatedConsents">List of modified consent</param>
/// <param name="newConsentValue">Modified Consents's new value</param>
private void NotifyListeners(List<Consents> updatedConsents, bool newConsentValue, ConsentChangedAction action)
{
if (Listeners == null || updatedConsents.Count < 1) {
return;
}
foreach (AbstractBaseService listener in Listeners) {
listener.ConsentChanged(updatedConsents, newConsentValue, action);
}
}
#endregion
#region override Methods
internal override void DeviceIdChanged(string deviceId, bool merged) { }
#endregion
}
}
| |
#region License
/*
* WebSocketServiceManager.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* 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.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
namespace WebSocketSharp.Server
{
/// <summary>
/// Provides the management function for the WebSocket services.
/// </summary>
/// <remarks>
/// This class manages the WebSocket services provided by
/// the <see cref="WebSocketServer"/> or <see cref="HttpServer"/>.
/// </remarks>
public class WebSocketServiceManager
{
#region Private Fields
private volatile bool _clean;
private Dictionary<string, WebSocketServiceHost> _hosts;
private Logger _log;
private volatile ServerState _state;
private object _sync;
private TimeSpan _waitTime;
#endregion
#region Internal Constructors
internal WebSocketServiceManager (Logger log)
{
_log = log;
_clean = true;
_hosts = new Dictionary<string, WebSocketServiceHost> ();
_state = ServerState.Ready;
_sync = ((ICollection) _hosts).SyncRoot;
_waitTime = TimeSpan.FromSeconds (1);
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of the WebSocket services.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of the services.
/// </value>
public int Count {
get {
lock (_sync)
return _hosts.Count;
}
}
/// <summary>
/// Gets the host instances for the WebSocket services.
/// </summary>
/// <value>
/// <para>
/// An <c>IEnumerable<WebSocketServiceHost></c> instance.
/// </para>
/// <para>
/// It provides an enumerator which supports the iteration over
/// the collection of the host instances.
/// </para>
/// </value>
public IEnumerable<WebSocketServiceHost> Hosts {
get {
lock (_sync)
return _hosts.Values.ToList ();
}
}
/// <summary>
/// Gets the host instance for a WebSocket service with
/// the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// <paramref name="path"/> is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="WebSocketServiceHost"/> instance or
/// <see langword="null"/> if not found.
/// </para>
/// <para>
/// That host instance provides the function to access
/// the information in the service.
/// </para>
/// </value>
/// <param name="path">
/// A <see cref="string"/> that represents an absolute path to
/// the service to find.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// </exception>
public WebSocketServiceHost this[string path] {
get {
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path[0] != '/')
throw new ArgumentException ("Not an absolute path.", "path");
if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
var msg = "It includes either or both query and fragment components.";
throw new ArgumentException (msg, "path");
}
WebSocketServiceHost host;
InternalTryGetServiceHost (path, out host);
return host;
}
}
/// <summary>
/// Gets or sets a value indicating whether the inactive sessions in
/// the WebSocket services are cleaned up periodically.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// <c>true</c> if the inactive sessions are cleaned up every 60 seconds;
/// otherwise, <c>false</c>.
/// </value>
public bool KeepClean {
get {
return _clean;
}
set {
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
foreach (var host in _hosts.Values)
host.KeepClean = value;
_clean = value;
}
}
}
/// <summary>
/// Gets the paths for the WebSocket services.
/// </summary>
/// <value>
/// <para>
/// An <c>IEnumerable<string></c> instance.
/// </para>
/// <para>
/// It provides an enumerator which supports the iteration over
/// the collection of the paths.
/// </para>
/// </value>
public IEnumerable<string> Paths {
get {
lock (_sync)
return _hosts.Keys.ToList ();
}
}
/// <summary>
/// Gets the total number of the sessions in the WebSocket services.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the total number of
/// the sessions in the services.
/// </value>
[Obsolete ("This property will be removed.")]
public int SessionCount {
get {
var cnt = 0;
foreach (var host in Hosts) {
if (_state != ServerState.Start)
break;
cnt += host.Sessions.Count;
}
return cnt;
}
}
/// <summary>
/// Gets or sets the time to wait for the response to the WebSocket Ping or
/// Close.
/// </summary>
/// <remarks>
/// The set operation does nothing if the server has already started or
/// it is shutting down.
/// </remarks>
/// <value>
/// A <see cref="TimeSpan"/> to wait for the response.
/// </value>
/// <exception cref="ArgumentOutOfRangeException">
/// The value specified for a set operation is zero or less.
/// </exception>
public TimeSpan WaitTime {
get {
return _waitTime;
}
set {
if (value <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException ("value", "Zero or less.");
string msg;
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
lock (_sync) {
if (!canSet (out msg)) {
_log.Warn (msg);
return;
}
foreach (var host in _hosts.Values)
host.WaitTime = value;
_waitTime = value;
}
}
}
#endregion
#region Private Methods
private void broadcast (Opcode opcode, byte[] data, Action completed)
{
var cache = new Dictionary<CompressionMethod, byte[]> ();
try {
foreach (var host in Hosts) {
if (_state != ServerState.Start) {
_log.Error ("The server is shutting down.");
break;
}
host.Sessions.Broadcast (opcode, data, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_log.Error (ex.Message);
_log.Debug (ex.ToString ());
}
finally {
cache.Clear ();
}
}
private void broadcast (Opcode opcode, Stream stream, Action completed)
{
var cache = new Dictionary<CompressionMethod, Stream> ();
try {
foreach (var host in Hosts) {
if (_state != ServerState.Start) {
_log.Error ("The server is shutting down.");
break;
}
host.Sessions.Broadcast (opcode, stream, cache);
}
if (completed != null)
completed ();
}
catch (Exception ex) {
_log.Error (ex.Message);
_log.Debug (ex.ToString ());
}
finally {
foreach (var cached in cache.Values)
cached.Dispose ();
cache.Clear ();
}
}
private void broadcastAsync (Opcode opcode, byte[] data, Action completed)
{
ThreadPool.QueueUserWorkItem (
state => broadcast (opcode, data, completed)
);
}
private void broadcastAsync (Opcode opcode, Stream stream, Action completed)
{
ThreadPool.QueueUserWorkItem (
state => broadcast (opcode, stream, completed)
);
}
private Dictionary<string, Dictionary<string, bool>> broadping (
byte[] frameAsBytes, TimeSpan timeout
)
{
var ret = new Dictionary<string, Dictionary<string, bool>> ();
foreach (var host in Hosts) {
if (_state != ServerState.Start) {
_log.Error ("The server is shutting down.");
break;
}
var res = host.Sessions.Broadping (frameAsBytes, timeout);
ret.Add (host.Path, res);
}
return ret;
}
private bool canSet (out string message)
{
message = null;
if (_state == ServerState.Start) {
message = "The server has already started.";
return false;
}
if (_state == ServerState.ShuttingDown) {
message = "The server is shutting down.";
return false;
}
return true;
}
#endregion
#region Internal Methods
internal void Add<TBehavior> (string path, Func<TBehavior> creator)
where TBehavior : WebSocketBehavior
{
path = HttpUtility.UrlDecode (path).TrimSlashFromEnd ();
lock (_sync) {
WebSocketServiceHost host;
if (_hosts.TryGetValue (path, out host))
throw new ArgumentException ("Already in use.", "path");
host = new WebSocketServiceHost<TBehavior> (
path, creator, null, _log
);
if (!_clean)
host.KeepClean = false;
if (_waitTime != host.WaitTime)
host.WaitTime = _waitTime;
if (_state == ServerState.Start)
host.Start ();
_hosts.Add (path, host);
}
}
internal bool InternalTryGetServiceHost (
string path, out WebSocketServiceHost host
)
{
path = HttpUtility.UrlDecode (path).TrimSlashFromEnd ();
lock (_sync)
return _hosts.TryGetValue (path, out host);
}
internal void Start ()
{
lock (_sync) {
foreach (var host in _hosts.Values)
host.Start ();
_state = ServerState.Start;
}
}
internal void Stop (ushort code, string reason)
{
lock (_sync) {
_state = ServerState.ShuttingDown;
foreach (var host in _hosts.Values)
host.Stop (code, reason);
_state = ServerState.Stop;
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a WebSocket service with the specified behavior,
/// <paramref name="path"/>, and <paramref name="initializer"/>.
/// </summary>
/// <remarks>
/// <paramref name="path"/> is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents an absolute path to
/// the service to add.
/// </param>
/// <param name="initializer">
/// <para>
/// An <c>Action<TBehavior></c> delegate or
/// <see langword="null"/> if not needed.
/// </para>
/// <para>
/// That delegate invokes the method called for initializing
/// a new session instance for the service.
/// </para>
/// </param>
/// <typeparam name="TBehavior">
/// The type of the behavior for the service. It must inherit
/// the <see cref="WebSocketBehavior"/> class and it must have
/// a public parameterless constructor.
/// </typeparam>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is already in use.
/// </para>
/// </exception>
public void AddService<TBehavior> (
string path, Action<TBehavior> initializer
)
where TBehavior : WebSocketBehavior, new ()
{
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path[0] != '/')
throw new ArgumentException ("Not an absolute path.", "path");
if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
var msg = "It includes either or both query and fragment components.";
throw new ArgumentException (msg, "path");
}
path = HttpUtility.UrlDecode (path).TrimSlashFromEnd ();
lock (_sync) {
WebSocketServiceHost host;
if (_hosts.TryGetValue (path, out host))
throw new ArgumentException ("Already in use.", "path");
host = new WebSocketServiceHost<TBehavior> (
path, () => new TBehavior (), initializer, _log
);
if (!_clean)
host.KeepClean = false;
if (_waitTime != host.WaitTime)
host.WaitTime = _waitTime;
if (_state == ServerState.Start)
host.Start ();
_hosts.Add (path, host);
}
}
/// <summary>
/// Sends <paramref name="data"/> to every client in the WebSocket services.
/// </summary>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the manager is not Start.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
[Obsolete ("This method will be removed.")]
public void Broadcast (byte[] data)
{
if (_state != ServerState.Start) {
var msg = "The current state of the manager is not Start.";
throw new InvalidOperationException (msg);
}
if (data == null)
throw new ArgumentNullException ("data");
if (data.LongLength <= WebSocket.FragmentLength)
broadcast (Opcode.Binary, data, null);
else
broadcast (Opcode.Binary, new MemoryStream (data), null);
}
/// <summary>
/// Sends <paramref name="data"/> to every client in the WebSocket services.
/// </summary>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the manager is not Start.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="data"/> could not be UTF-8-encoded.
/// </exception>
[Obsolete ("This method will be removed.")]
public void Broadcast (string data)
{
if (_state != ServerState.Start) {
var msg = "The current state of the manager is not Start.";
throw new InvalidOperationException (msg);
}
if (data == null)
throw new ArgumentNullException ("data");
byte[] bytes;
if (!data.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "data");
}
if (bytes.LongLength <= WebSocket.FragmentLength)
broadcast (Opcode.Text, bytes, null);
else
broadcast (Opcode.Text, new MemoryStream (bytes), null);
}
/// <summary>
/// Sends <paramref name="data"/> asynchronously to every client in
/// the WebSocket services.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <param name="completed">
/// <para>
/// An <see cref="Action"/> delegate or <see langword="null"/>
/// if not needed.
/// </para>
/// <para>
/// The delegate invokes the method called when the send is complete.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the manager is not Start.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
[Obsolete ("This method will be removed.")]
public void BroadcastAsync (byte[] data, Action completed)
{
if (_state != ServerState.Start) {
var msg = "The current state of the manager is not Start.";
throw new InvalidOperationException (msg);
}
if (data == null)
throw new ArgumentNullException ("data");
if (data.LongLength <= WebSocket.FragmentLength)
broadcastAsync (Opcode.Binary, data, completed);
else
broadcastAsync (Opcode.Binary, new MemoryStream (data), completed);
}
/// <summary>
/// Sends <paramref name="data"/> asynchronously to every client in
/// the WebSocket services.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <param name="completed">
/// <para>
/// An <see cref="Action"/> delegate or <see langword="null"/>
/// if not needed.
/// </para>
/// <para>
/// The delegate invokes the method called when the send is complete.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the manager is not Start.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="data"/> could not be UTF-8-encoded.
/// </exception>
[Obsolete ("This method will be removed.")]
public void BroadcastAsync (string data, Action completed)
{
if (_state != ServerState.Start) {
var msg = "The current state of the manager is not Start.";
throw new InvalidOperationException (msg);
}
if (data == null)
throw new ArgumentNullException ("data");
byte[] bytes;
if (!data.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "data");
}
if (bytes.LongLength <= WebSocket.FragmentLength)
broadcastAsync (Opcode.Text, bytes, completed);
else
broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed);
}
/// <summary>
/// Sends the data from <paramref name="stream"/> asynchronously to
/// every client in the WebSocket services.
/// </summary>
/// <remarks>
/// <para>
/// The data is sent as the binary data.
/// </para>
/// <para>
/// This method does not wait for the send to be complete.
/// </para>
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> instance from which to read the data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that specifies the number of bytes to send.
/// </param>
/// <param name="completed">
/// <para>
/// An <see cref="Action"/> delegate or <see langword="null"/>
/// if not needed.
/// </para>
/// <para>
/// The delegate invokes the method called when the send is complete.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the manager is not Start.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="stream"/> cannot be read.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="length"/> is less than 1.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// No data could be read from <paramref name="stream"/>.
/// </para>
/// </exception>
[Obsolete ("This method will be removed.")]
public void BroadcastAsync (Stream stream, int length, Action completed)
{
if (_state != ServerState.Start) {
var msg = "The current state of the manager is not Start.";
throw new InvalidOperationException (msg);
}
if (stream == null)
throw new ArgumentNullException ("stream");
if (!stream.CanRead) {
var msg = "It cannot be read.";
throw new ArgumentException (msg, "stream");
}
if (length < 1) {
var msg = "Less than 1.";
throw new ArgumentException (msg, "length");
}
var bytes = stream.ReadBytes (length);
var len = bytes.Length;
if (len == 0) {
var msg = "No data could be read from it.";
throw new ArgumentException (msg, "stream");
}
if (len < length) {
_log.Warn (
String.Format (
"Only {0} byte(s) of data could be read from the stream.",
len
)
);
}
if (len <= WebSocket.FragmentLength)
broadcastAsync (Opcode.Binary, bytes, completed);
else
broadcastAsync (Opcode.Binary, new MemoryStream (bytes), completed);
}
/// <summary>
/// Sends a ping to every client in the WebSocket services.
/// </summary>
/// <returns>
/// <para>
/// A <c>Dictionary<string, Dictionary<string, bool>></c>.
/// </para>
/// <para>
/// It represents a collection of pairs of a service path and another
/// collection of pairs of a session ID and a value indicating whether
/// a pong has been received from the client within a time.
/// </para>
/// </returns>
/// <exception cref="InvalidOperationException">
/// The current state of the manager is not Start.
/// </exception>
[Obsolete ("This method will be removed.")]
public Dictionary<string, Dictionary<string, bool>> Broadping ()
{
if (_state != ServerState.Start) {
var msg = "The current state of the manager is not Start.";
throw new InvalidOperationException (msg);
}
return broadping (WebSocketFrame.EmptyPingBytes, _waitTime);
}
/// <summary>
/// Sends a ping with <paramref name="message"/> to every client in
/// the WebSocket services.
/// </summary>
/// <returns>
/// <para>
/// A <c>Dictionary<string, Dictionary<string, bool>></c>.
/// </para>
/// <para>
/// It represents a collection of pairs of a service path and another
/// collection of pairs of a session ID and a value indicating whether
/// a pong has been received from the client within a time.
/// </para>
/// </returns>
/// <param name="message">
/// <para>
/// A <see cref="string"/> that represents the message to send.
/// </para>
/// <para>
/// The size must be 125 bytes or less in UTF-8.
/// </para>
/// </param>
/// <exception cref="InvalidOperationException">
/// The current state of the manager is not Start.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="message"/> could not be UTF-8-encoded.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The size of <paramref name="message"/> is greater than 125 bytes.
/// </exception>
[Obsolete ("This method will be removed.")]
public Dictionary<string, Dictionary<string, bool>> Broadping (string message)
{
if (_state != ServerState.Start) {
var msg = "The current state of the manager is not Start.";
throw new InvalidOperationException (msg);
}
if (message.IsNullOrEmpty ())
return broadping (WebSocketFrame.EmptyPingBytes, _waitTime);
byte[] bytes;
if (!message.TryGetUTF8EncodedBytes (out bytes)) {
var msg = "It could not be UTF-8-encoded.";
throw new ArgumentException (msg, "message");
}
if (bytes.Length > 125) {
var msg = "Its size is greater than 125 bytes.";
throw new ArgumentOutOfRangeException ("message", msg);
}
var frame = WebSocketFrame.CreatePingFrame (bytes, false);
return broadping (frame.ToArray (), _waitTime);
}
/// <summary>
/// Removes all WebSocket services managed by the manager.
/// </summary>
/// <remarks>
/// A service is stopped with close status 1001 (going away)
/// if it has already started.
/// </remarks>
public void Clear ()
{
List<WebSocketServiceHost> hosts = null;
lock (_sync) {
hosts = _hosts.Values.ToList ();
_hosts.Clear ();
}
foreach (var host in hosts) {
if (host.State == ServerState.Start)
host.Stop (1001, String.Empty);
}
}
/// <summary>
/// Removes a WebSocket service with the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// <para>
/// <paramref name="path"/> is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
/// </para>
/// <para>
/// The service is stopped with close status 1001 (going away)
/// if it has already started.
/// </para>
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found and removed;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents an absolute path to
/// the service to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// </exception>
public bool RemoveService (string path)
{
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path[0] != '/')
throw new ArgumentException ("Not an absolute path.", "path");
if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
var msg = "It includes either or both query and fragment components.";
throw new ArgumentException (msg, "path");
}
path = HttpUtility.UrlDecode (path).TrimSlashFromEnd ();
WebSocketServiceHost host;
lock (_sync) {
if (!_hosts.TryGetValue (path, out host))
return false;
_hosts.Remove (path);
}
if (host.State == ServerState.Start)
host.Stop (1001, String.Empty);
return true;
}
/// <summary>
/// Tries to get the host instance for a WebSocket service with
/// the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// <paramref name="path"/> is converted to a URL-decoded string and
/// / is trimmed from the end of the converted string if any.
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents an absolute path to
/// the service to find.
/// </param>
/// <param name="host">
/// <para>
/// When this method returns, a <see cref="WebSocketServiceHost"/>
/// instance or <see langword="null"/> if not found.
/// </para>
/// <para>
/// That host instance provides the function to access
/// the information in the service.
/// </para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="path"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> is not an absolute path.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="path"/> includes either or both
/// query and fragment components.
/// </para>
/// </exception>
public bool TryGetServiceHost (string path, out WebSocketServiceHost host)
{
if (path == null)
throw new ArgumentNullException ("path");
if (path.Length == 0)
throw new ArgumentException ("An empty string.", "path");
if (path[0] != '/')
throw new ArgumentException ("Not an absolute path.", "path");
if (path.IndexOfAny (new[] { '?', '#' }) > -1) {
var msg = "It includes either or both query and fragment components.";
throw new ArgumentException (msg, "path");
}
return InternalTryGetServiceHost (path, out host);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="_OverlappedAsyncResult.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net.Sockets {
using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32;
using System.Collections.Generic;
//
// OverlappedAsyncResult - used to take care of storage for async Socket operation
// from the BeginSend, BeginSendTo, BeginReceive, BeginReceiveFrom calls.
//
internal class OverlappedAsyncResult: BaseOverlappedAsyncResult {
//
// internal class members
//
private SocketAddress m_SocketAddress;
private SocketAddress m_SocketAddressOriginal; // needed for partial BeginReceiveFrom/EndReceiveFrom completion
// These two are used only as alternatives
internal WSABuffer m_SingleBuffer;
internal WSABuffer[] m_WSABuffers;
//
// the following two will be used only on WinNT to enable completion ports
//
//
// Constructor. We take in the socket that's creating us, the caller's
// state object, and the buffer on which the I/O will be performed.
// We save the socket and state, pin the callers's buffer, and allocate
// an event for the WaitHandle.
//
internal OverlappedAsyncResult(Socket socket, Object asyncState, AsyncCallback asyncCallback) :
base(socket, asyncState, asyncCallback)
{ }
//
internal IntPtr GetSocketAddressPtr()
{
return Marshal.UnsafeAddrOfPinnedArrayElement(m_SocketAddress.m_Buffer, 0);
}
//
internal IntPtr GetSocketAddressSizePtr()
{
return Marshal.UnsafeAddrOfPinnedArrayElement(m_SocketAddress.m_Buffer, m_SocketAddress.GetAddressSizeOffset());
}
//
internal SocketAddress SocketAddress {
get {
return m_SocketAddress;
}
}
//
internal SocketAddress SocketAddressOriginal {
get {
return m_SocketAddressOriginal;
}
set {
m_SocketAddressOriginal = value;
}
}
//
// SetUnmanagedStructures -
// Fills in Overlapped Structures used in an Async Overlapped Winsock call
// these calls are outside the runtime and are unmanaged code, so we need
// to prepare specific structures and ints that lie in unmanaged memory
// since the Overlapped calls can be Async
//
internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, SocketAddress socketAddress, bool pinSocketAddress)
{
//
// Fill in Buffer Array structure that will be used for our send/recv Buffer
//
m_SocketAddress = socketAddress;
if (pinSocketAddress && m_SocketAddress != null)
{
object[] objectsToPin = null;
objectsToPin = new object[2];
objectsToPin[0] = buffer;
m_SocketAddress.CopyAddressSizeIntoBuffer();
objectsToPin[1] = m_SocketAddress.m_Buffer;
base.SetUnmanagedStructures(objectsToPin);
} else {
base.SetUnmanagedStructures(buffer);
}
m_SingleBuffer.Length = size;
m_SingleBuffer.Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset);
}
internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, SocketAddress socketAddress, bool pinSocketAddress, ref OverlappedCache overlappedCache)
{
SetupCache(ref overlappedCache);
SetUnmanagedStructures(buffer, offset, size, socketAddress, pinSocketAddress);
}
internal void SetUnmanagedStructures(BufferOffsetSize[] buffers)
{
//
// Fill in Buffer Array structure that will be used for our send/recv Buffer
//
m_WSABuffers = new WSABuffer[buffers.Length];
object[] objectsToPin = new object[buffers.Length];
for (int i = 0; i < buffers.Length; i++)
objectsToPin[i] = buffers[i].Buffer;
// has to be called now to pin memory
base.SetUnmanagedStructures(objectsToPin);
for (int i = 0; i < buffers.Length; i++)
{
m_WSABuffers[i].Length = buffers[i].Size;
m_WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffers[i].Buffer, buffers[i].Offset);
}
}
internal void SetUnmanagedStructures(BufferOffsetSize[] buffers, ref OverlappedCache overlappedCache)
{
SetupCache(ref overlappedCache);
SetUnmanagedStructures(buffers);
}
internal void SetUnmanagedStructures(IList<ArraySegment<byte>> buffers)
{
// Fill in Buffer Array structure that will be used for our send/recv Buffer
//
//make sure we don't let the app mess up the buffer array enough to cause
//corruption.
int count = buffers.Count;
ArraySegment<byte>[] buffersCopy = new ArraySegment<byte>[count];
for (int i=0;i<count;i++) {
buffersCopy[i] = buffers[i];
ValidationHelper.ValidateSegment(buffersCopy[i]);
}
m_WSABuffers = new WSABuffer[count];
object[] objectsToPin = new object[count];
for (int i = 0; i < count; i++)
objectsToPin[i] = buffersCopy[i].Array;
base.SetUnmanagedStructures(objectsToPin);
for (int i = 0; i < count; i++)
{
m_WSABuffers[i].Length = buffersCopy[i].Count;
m_WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffersCopy[i].Array, buffersCopy[i].Offset);
}
}
internal void SetUnmanagedStructures(IList<ArraySegment<byte>> buffers, ref OverlappedCache overlappedCache)
{
SetupCache(ref overlappedCache);
SetUnmanagedStructures(buffers);
}
//
// This method is called after an asynchronous call is made for the user,
// it checks and acts accordingly if the IO:
// 1) completed synchronously.
// 2) was pended.
// 3) failed.
//
internal override object PostCompletion(int numBytes)
{
if (ErrorCode == 0) {
if(Logging.On)LogBuffer(numBytes);
}
return (int)numBytes;
}
void LogBuffer(int size) {
GlobalLog.Assert(Logging.On, "OverlappedAsyncResult#{0}::LogBuffer()|Logging is off!", ValidationHelper.HashString(this));
if (size > -1) {
if (m_WSABuffers != null) {
foreach (WSABuffer wsaBuffer in m_WSABuffers) {
Logging.Dump(Logging.Sockets, AsyncObject, "PostCompletion", wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
if ((size -= wsaBuffer.Length) <=0)
break;
}
}
else {
Logging.Dump(Logging.Sockets, AsyncObject, "PostCompletion", m_SingleBuffer.Pointer, Math.Min(m_SingleBuffer.Length, size));
}
}
}
}; // class OverlappedAsyncResult
} // namespace System.Net.Sockets
| |
using csscript;
using CSScripting;
using CSScriptLib;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Xunit;
using static System.Environment;
namespace CLI
{
public class CliTestFolder
{
public static string root = Assembly.GetExecutingAssembly().Location.GetDirName().PathJoin("test.cli").EnsureDir();
public CliTestFolder()
{
Directory.GetFiles(root, "*", SearchOption.AllDirectories)
.ToList()
.ForEach(File.Delete);
Environment.CurrentDirectory = root;
}
public static void Set(string path)
=> Environment.CurrentDirectory = root = path.EnsureDir();
}
public class cscs_cli : IClassFixture<CliTestFolder>
{
public cscs_cli()
{
#if DEBUG
var config = "Debug";
#else
var config = "Release";
#endif
cscs_exe = Environment.GetEnvironmentVariable("css_test_asm") ?? $@"..\..\..\..\..\cscs\bin\{config}\net{Environment.Version.Major}.0\cscs.dll".GetFullPath();
var cmd_dir = cscs_exe.ChangeFileName("-self");
if (cmd_dir.DirExists())
static_content = cmd_dir;
else
static_content = $@"..\..\..\..\..\out\static_content".GetFullPath();
}
public string cscs_exe;
public string static_content;
string cscs_run(string args, string dir = null) => "dotnet".Run($"\"{cscs_exe}\" {args}", dir).Trim();
[Fact]
public void create_and_execute_default_script()
{
var script_file = nameof(create_and_execute_default_script) + ".cs";
var output = cscs_run($"-new {script_file}");
Assert.True(File.Exists(script_file));
Assert.True(File.Exists(script_file));
Assert.StartsWith("Created:", output);
output = cscs_run(script_file);
Assert.Contains("Hello from C#", output);
}
[Fact]
public void switch_engine_from_CLI()
{
var script_file = nameof(switch_engine_from_CLI);
var output = cscs_run($"-new {script_file}");
output = cscs_run($"-check -verbose -ng:dotnet {script_file}");
Assert.Contains("Compiler engine: dotnet", output);
output = cscs_run($"-check -verbose -ng:csc {script_file}");
Assert.Contains("Compiler engine: csc", output);
}
[Fact]
public void switch_engine_from_code_with_full_directive()
{
var script_file = nameof(switch_engine_from_code_with_full_directive) + ".cs";
var output = cscs_run($"-new {script_file}");
var script_code = File.ReadAllText(script_file);
// full directive //css_engine
File.WriteAllText(script_file, "//css_engine dotnet" + NewLine + script_code);
output = cscs_run($"-check -verbose {script_file}");
Assert.Contains("Compiler engine: dotnet", output);
File.WriteAllText(script_file, "//css_engine csc" + NewLine + script_code);
output = cscs_run($"-check -verbose {script_file}");
Assert.Contains("Compiler engine: csc", output);
}
[Fact]
public void switch_engine_from_code_with_short_directive()
{
var script_file = nameof(switch_engine_from_code_with_short_directive) + ".cs";
var output = cscs_run($"-new {script_file}");
var script_code = File.ReadAllText(script_file);
// short directive //css_ng
File.WriteAllText(script_file, "//css_ng dotnet" + NewLine + script_code);
output = cscs_run($"-check -verbose {script_file}");
Assert.Contains("Compiler engine: dotnet", output);
File.WriteAllText(script_file, "//css_ng csc" + NewLine + script_code);
output = cscs_run($"-check -verbose {script_file}");
Assert.Contains("Compiler engine: csc", output);
}
[Fact]
public void switch_engine_from_settings()
{
var script_file = nameof(switch_engine_from_settings);
var settings_file = nameof(switch_engine_from_settings).GetFullPath() + ".config";
var settings = new Settings();
var output = cscs_run($"-new {script_file}");
// --------------
settings.DefaultCompilerEngine = "dotnet";
settings.Save(settings_file);
output = cscs_run($"-check -verbose -config:{settings_file} {script_file}");
Assert.Contains("Compiler engine: dotnet", output);
// --------------
settings.DefaultCompilerEngine = "csc";
settings.Save(settings_file);
output = cscs_run($"-check -verbose -config:\"{settings_file}\" {script_file}");
Assert.Contains("Compiler engine: csc", output);
}
[Fact]
public void new_toplevel()
{
var script_file = nameof(new_toplevel);
var output = cscs_run($"-new:toplevel {script_file}");
output = cscs_run($"-check -ng:dotnet {script_file}");
Assert.Equal("Compile: OK", output);
output = cscs_run($"-check -ng:csc {script_file}");
Assert.Equal("Compile: OK", output);
}
[Fact]
public void compile_dll()
{
// Issue #255: Relative path for cscs.exe -out option results in wrong output folder
var script_file = ".".PathJoin("temp", $"{nameof(compile_dll)}");
var dll_file = ".".PathJoin("temp", $"{nameof(compile_dll)}.dll");
var output = cscs_run($"-new:console {script_file}");
output = cscs_run($"-cd -out:{dll_file} {script_file}");
Assert.Contains("Created: " + dll_file.GetFullPath(), output);
output = cscs_run($"-ng:csc -cd -out:{dll_file} {script_file}");
Assert.Contains("Created: " + dll_file.GetFullPath(), output);
}
[Fact]
public void new_console()
{
var script_file = nameof(new_console);
var output = cscs_run($"-new:console {script_file}");
output = cscs_run($"-check -ng:dotnet {script_file}");
Assert.Equal("Compile: OK", output);
}
[Fact]
public void syntax_version_10()
{
var script = (nameof(syntax_version_10) + ".cs").GetFullPath();
var script_g = script.ChangeExtension(".g.cs");
File.WriteAllText(script, @$"
//css_inc {script_g}
Console.WriteLine(""Hello, World!"");");
File.WriteAllText(script_g, @"
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;");
var output = cscs_run($"-ng:dotnet \"{script}\"");
Assert.Equal("Hello, World!", output);
output = cscs_run($"-ng:csc \"{script}\"");
Assert.Equal("Hello, World!", output);
output = cscs_run($"-ng:roslyn \"{script}\"");
Assert.Equal("Hello, World!", output);
}
[Fact]
public void complex_commands()
{
var is_win = (Environment.OSVersion.Platform == PlatformID.Win32NT);
var probing_dir = $"-dir:{static_content}";
var output = cscs_run($"{probing_dir} -self");
Assert.Equal(cscs_exe, output);
output = cscs_run($"{probing_dir} -self-run");
Assert.Equal(cscs_exe, output);
// -------------- it will fail on Linux as elevation will be required. so building exe
// needs to be tested manually.
if (is_win && !Assembly.GetEntryAssembly().Location.EndsWith("css.dll"))
{
// css may be locked (e.g.it is running this test)
output = cscs_run($"{probing_dir} -self-exe");
Assert.Equal($"Created: {cscs_exe.ChangeFileName("css.exe")}", output);
output = cscs_run($"{probing_dir} -self-exe-run");
Assert.Equal($"Created: {cscs_exe.ChangeFileName("css.exe")}", output);
output = cscs_run($"{probing_dir} -self-exe-build");
Assert.Equal($"Created: {cscs_exe.ChangeFileName("css.exe")}", output);
}
}
[Fact]
[FactWinOnly]
public void new_winform()
{
var script_file = nameof(new_winform);
var output = cscs_run($"-new:winform {script_file}");
output = cscs_run($"-check -ng:dotnet {script_file}");
Assert.Equal("Compile: OK", output);
output = cscs_run($"-check -ng:csc {script_file}");
Assert.Equal("Compile: OK", output);
}
[Fact]
public void compiler_output()
{
var script_file = nameof(compiler_output);
var output = cscs_run($"-new {script_file}");
output = cscs_run($"-check -ng:csc {script_file}");
Assert.Equal("Compile: OK", output);
}
[Fact]
[FactWinOnly]
public void new_wpf_with_cscs()
{
/*
// WPF is a special case. If WPF script uses compiled (not dynamically loaded) XAML then
// it needs to be compiled to BAML. The same way as MSBuild does for a WPF vs project.
// Thus csc.exe simply not capable of doing this so you need to use dotnet engine.
script_type | host_app | compiler_engine | compilation | hosting | overall execution | special_steps
-------------------------------------------------|---------------|-----------|--------------------------------------
console | cscs | csc | success | success | success |
console | csws | csc | success | success | success |
console | cscs | dotnet | success | success | success |
console | csws | dotnet | success | success | success |
winform | cscs | csc | success | success | success | //css_winapp
winform | csws | csc | success | success | success | //css_winapp
winform | cscs | dotnet | success | success | success | //css_winapp
winform | csws | dotnet | success | success | success | //css_winapp
WPF | cscs | csc | failure | failure | failure | //css_winapp
WPF | csws | csc | failure | failure | failure | //css_winapp
WPF | cscs | dotnet | success | failure | failure | //css_winapp
WPF | cscs | dotnet | success | success | success | //css_winapp (execute `cscs -wpf:enable` once)
WPF | csws | dotnet | success | success | success | //css_winapp
*/
if (!Runtime.IsLinux)
{
var script_file = nameof(new_wpf_with_cscs) + ".cs";
var output = cscs_run($"-new:wpf {script_file}");
// --------------
output = cscs_run($"-check {script_file}");
Assert.Equal("Compile: OK", output);
// --------------
// removing in-code engine directive so the engine from CLI param will be used
var content = File.ReadAllLines(script_file).Where(x => !x.Contains("//css_ng")).ToArray();
File.WriteAllLines(script_file, content);
output = cscs_run($"-check -ng:dotnet {script_file}");
Assert.Equal("Compile: OK", output);
// csc engine supposed to fail to compile WPF
output = cscs_run($"-check -ng:csc {script_file}");
Assert.Contains("BUILD: error : In order to compile XAML you need to use 'dotnet' compiler", output);
}
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Flow Interview Log Entry
///<para>SObject Name: FlowInterviewLogEntry</para>
///<para>Custom Object: False</para>
///</summary>
public class SfFlowInterviewLogEntry : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "FlowInterviewLogEntry"; }
}
///<summary>
/// Flow Interview Log Entry ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>AutoNumber field</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "name")]
[Updateable(false), Createable(false)]
public string Name { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Flow Interview Log ID
/// <para>Name: FlowInterviewLogId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "flowInterviewLogId")]
[Updateable(false), Createable(false)]
public string FlowInterviewLogId { get; set; }
///<summary>
/// ReferenceTo: FlowInterviewLog
/// <para>RelationshipName: FlowInterviewLog</para>
///</summary>
[JsonProperty(PropertyName = "flowInterviewLog")]
[Updateable(false), Createable(false)]
public SfFlowInterviewLog FlowInterviewLog { get; set; }
///<summary>
/// Log Entry Type
/// <para>Name: LogEntryType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "logEntryType")]
[Updateable(false), Createable(false)]
public string LogEntryType { get; set; }
///<summary>
/// Element API Name
/// <para>Name: ElementApiName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "elementApiName")]
[Updateable(false), Createable(false)]
public string ElementApiName { get; set; }
///<summary>
/// Log Entry Timestamp
/// <para>Name: LogEntryTimestamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "logEntryTimestamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LogEntryTimestamp { get; set; }
///<summary>
/// Duration In Minutes Since Flow Start
/// <para>Name: DurationSinceStartInMinutes</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "durationSinceStartInMinutes")]
[Updateable(false), Createable(false)]
public double? DurationSinceStartInMinutes { get; set; }
///<summary>
/// Element Duration in Minutes
/// <para>Name: ElementDurationInMinutes</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "elementDurationInMinutes")]
[Updateable(false), Createable(false)]
public double? ElementDurationInMinutes { get; set; }
///<summary>
/// Element Label
/// <para>Name: ElementLabel</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "elementLabel")]
[Updateable(false), Createable(false)]
public string ElementLabel { get; set; }
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.ScenarioTest.SqlTests;
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
using Xunit.Abstractions;
using RestTestFramework = Microsoft.Rest.ClientRuntime.Azure.TestFramework;
namespace Microsoft.Azure.Commands.Sql.Test.ScenarioTests
{
public class AuditingTests : SqlTestsBase
{
protected override void SetupManagementClients(RestTestFramework.MockContext context)
{
var sqlClient = GetSqlClient(context);
var sqlLegacyClient = GetLegacySqlClient();
var storageV2Client = GetStorageV2Client();
var resourcesClient = GetResourcesClient();
var newResourcesClient = GetResourcesClient(context);
var authorizationClient = GetAuthorizationManagementClient();
helper.SetupSomeOfManagementClients(sqlClient, sqlLegacyClient, storageV2Client, resourcesClient, newResourcesClient, authorizationClient);
}
public AuditingTests(ITestOutputHelper output) : base(output)
{
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseUpdatePolicyWithStorage()
{
RunPowerShellTest("Test-AuditingDatabaseUpdatePolicyWithStorage");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingServerUpdatePolicyWithStorage()
{
RunPowerShellTest("Test-AuditingServerUpdatePolicyWithStorage");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseUpdatePolicyWithEventTypes()
{
RunPowerShellTest("Test-AuditingDatabaseUpdatePolicyWithEventTypes");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingServerUpdatePolicyWithEventTypes()
{
RunPowerShellTest("Test-AuditingServerUpdatePolicyWithEventTypes");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDisableDatabaseAuditing()
{
RunPowerShellTest("Test-AuditingDisableDatabaseAuditing");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDisableServerAuditing()
{
RunPowerShellTest("Test-AuditingDisableServerAuditing");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseDisableEnableKeepProperties()
{
RunPowerShellTest("Test-AuditingDatabaseDisableEnableKeepProperties");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingServerDisableEnableKeepProperties()
{
RunPowerShellTest("Test-AuditingServerDisableEnableKeepProperties");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingUseServerDefault()
{
RunPowerShellTest("Test-AuditingUseServerDefault");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingFailedDatabaseUpdatePolicyWithNoStorage()
{
RunPowerShellTest("Test-AuditingFailedDatabaseUpdatePolicyWithNoStorage");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingFailedServerUpdatePolicyWithNoStorage()
{
RunPowerShellTest("Test-AuditingFailedServerUpdatePolicyWithNoStorage");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingFailedUseServerDefault()
{
RunPowerShellTest("Test-AuditingFailedUseServerDefault");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseUpdatePolicyWithEventTypeShortcuts()
{
RunPowerShellTest("Test-AuditingDatabaseUpdatePolicyWithEventTypeShortcuts");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingServerUpdatePolicyWithEventTypeShortcuts()
{
RunPowerShellTest("Test-AuditingServerUpdatePolicyWithEventTypeShortcuts");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseUpdatePolicyKeepPreviousStorage()
{
RunPowerShellTest("Test-AuditingDatabaseUpdatePolicyKeepPreviousStorage");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingServerUpdatePolicyKeepPreviousStorage()
{
RunPowerShellTest("Test-AuditingServerUpdatePolicyKeepPreviousStorage");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingFailWithBadDatabaseIndentity()
{
RunPowerShellTest("Test-AuditingFailWithBadDatabaseIndentity");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingFailWithBadServerIndentity()
{
RunPowerShellTest("Test-AuditingFailWithBadServerIndentity");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseStorageKeyRotation()
{
RunPowerShellTest("Test-AuditingDatabaseStorageKeyRotation");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingServerStorageKeyRotation()
{
RunPowerShellTest("Test-AuditingServerStorageKeyRotation");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingServerUpdatePolicyWithRetention()
{
RunPowerShellTest("Test-AuditingServerUpdatePolicyWithRetention");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseUpdatePolicyWithRetention()
{
RunPowerShellTest("Test-AuditingDatabaseUpdatePolicyWithRetention");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingServerRetentionKeepProperties()
{
RunPowerShellTest("Test-AuditingServerRetentionKeepProperties");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseRetentionKeepProperties()
{
RunPowerShellTest("Test-AuditingDatabaseRetentionKeepProperties");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestBlobAuditingOnDatabase()
{
RunPowerShellTest("Test-BlobAuditingOnDatabase");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestBlobAuditingOnServer()
{
RunPowerShellTest("Test-BlobAuditingOnServer");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestDatatabaseAuditingTypeMigration()
{
RunPowerShellTest("Test-DatatabaseAuditingTypeMigration");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestServerAuditingTypeMigration()
{
RunPowerShellTest("Test-ServerAuditingTypeMigration");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestAuditingDatabaseUpdatePolicyWithSameNameStorageOnDifferentRegion()
{
RunPowerShellTest("Test-AuditingDatabaseUpdatePolicyWithSameNameStorageOnDifferentRegion");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetServerAndDatabaseAuditingInUkRegion()
{
RunPowerShellTest("Test-GetServerAndDatabaseAuditingInUkRegion");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestBlobAuditingWithAuditActionGroups()
{
RunPowerShellTest("Test-BlobAuditingWithAuditActionGroups");
}
}
}
| |
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace TwainLib
{
public enum TwainCommand
{
Not = -1,
Null = 0,
TransferReady = 1,
CloseRequest = 2,
CloseOk = 3,
DeviceEvent = 4
}
public class Twain
{
private const short CountryUSA = 1;
private const short LanguageUSA = 13;
public Twain(string ProductName)
{
appid = new TwIdentity();
appid.Id = IntPtr.Zero;
appid.Version.MajorNum = 1;
appid.Version.MinorNum = 1;
appid.Version.Language = LanguageUSA;
appid.Version.Country = CountryUSA;
appid.Version.Info = "Hack 1";
appid.ProtocolMajor = TwProtocol.Major;
appid.ProtocolMinor = TwProtocol.Minor;
appid.SupportedGroups = (int)(TwDG.Image | TwDG.Control);
appid.Manufacturer = "NETMaster";
appid.ProductFamily = "Freeware";
appid.ProductName = ProductName;
srcds = new TwIdentity();
srcds.Id = IntPtr.Zero;
evtmsg.EventPtr = Marshal.AllocHGlobal(Marshal.SizeOf(winmsg));
}
~Twain()
{
Marshal.FreeHGlobal(evtmsg.EventPtr);
}
public void Init(IntPtr hwndp)
{
Finish();
TwRC rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.OpenDSM, ref hwndp);
if (rc == TwRC.Success)
{
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.GetDefault, srcds);
if (rc == TwRC.Success)
hwnd = hwndp;
else
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.CloseDSM, ref hwndp);
}
}
public void Select()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return;
}
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.UserSelect, srcds);
}
public void Acquire()
{
TwRC rc;
CloseSrc();
if (appid.Id == IntPtr.Zero)
{
Init(hwnd);
if (appid.Id == IntPtr.Zero)
return;
}
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.OpenDS, srcds);
if (rc != TwRC.Success)
return;
TwCapability cap = new TwCapability(TwCap.XferCount, 1);
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, cap);
if (rc != TwRC.Success)
{
CloseSrc();
return;
}
TwUserInterface guif = new TwUserInterface();
guif.ShowUI = 1;
guif.ModalUI = 1;
guif.ParentHand = hwnd;
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface, TwMSG.EnableDS, guif);
if (rc != TwRC.Success)
{
CloseSrc();
return;
}
}
public ArrayList TransferPictures()
{
ArrayList pics = new ArrayList();
if (srcds.Id == IntPtr.Zero)
return pics;
TwRC rc;
IntPtr hbitmap = IntPtr.Zero;
TwPendingXfers pxfr = new TwPendingXfers();
do
{
pxfr.Count = 0;
hbitmap = IntPtr.Zero;
TwImageInfo iinf = new TwImageInfo();
rc = DSiinf(appid, srcds, TwDG.Image, TwDAT.ImageInfo, TwMSG.Get, iinf);
if (rc != TwRC.Success)
{
CloseSrc();
return pics;
}
rc = DSixfer(appid, srcds, TwDG.Image, TwDAT.ImageNativeXfer, TwMSG.Get, ref hbitmap);
if (rc != TwRC.XferDone)
{
CloseSrc();
return pics;
}
rc = DSpxfer(appid, srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.EndXfer, pxfr);
if (rc != TwRC.Success)
{
CloseSrc();
return pics;
}
pics.Add(hbitmap);
}
while (pxfr.Count != 0);
rc = DSpxfer(appid, srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.Reset, pxfr);
return pics;
}
public TwainCommand PassMessage(ref Message m)
{
if (srcds.Id == IntPtr.Zero)
return TwainCommand.Not;
int pos = GetMessagePos();
winmsg.hwnd = m.HWnd;
winmsg.message = m.Msg;
winmsg.wParam = m.WParam;
winmsg.lParam = m.LParam;
winmsg.time = GetMessageTime();
winmsg.x = (short)pos;
winmsg.y = (short)(pos >> 16);
Marshal.StructureToPtr(winmsg, evtmsg.EventPtr, false);
evtmsg.Message = 0;
TwRC rc = DSevent(appid, srcds, TwDG.Control, TwDAT.Event, TwMSG.ProcessEvent, ref evtmsg);
if (rc == TwRC.NotDSEvent)
return TwainCommand.Not;
if (evtmsg.Message == (short)TwMSG.XFerReady)
return TwainCommand.TransferReady;
if (evtmsg.Message == (short)TwMSG.CloseDSReq)
return TwainCommand.CloseRequest;
if (evtmsg.Message == (short)TwMSG.CloseDSOK)
return TwainCommand.CloseOk;
if (evtmsg.Message == (short)TwMSG.DeviceEvent)
return TwainCommand.DeviceEvent;
return TwainCommand.Null;
}
public void CloseSrc()
{
TwRC rc;
if (srcds.Id != IntPtr.Zero)
{
TwUserInterface guif = new TwUserInterface();
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface, TwMSG.DisableDS, guif);
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.CloseDS, srcds);
}
}
public void Finish()
{
TwRC rc;
CloseSrc();
if (appid.Id != IntPtr.Zero)
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.CloseDSM, ref hwnd);
appid.Id = IntPtr.Zero;
}
private IntPtr hwnd;
private TwIdentity appid;
private TwIdentity srcds;
private TwEvent evtmsg;
private WINMSG winmsg;
// ------ DSM entry point DAT_ variants:
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMparent([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr refptr);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMident([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwIdentity idds);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSMstatus([In, Out] TwIdentity origin, IntPtr zeroptr, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwStatus dsmstat);
// ------ DSM entry point DAT_ variants to DS:
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSuserif([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, TwUserInterface guif);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSevent([In, Out] TwIdentity origin, [In, Out] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref TwEvent evt);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSstatus([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwStatus dsmstat);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DScap([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwCapability capa);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSiinf([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwImageInfo imginf);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSixfer([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, ref IntPtr hbitmap);
[DllImport("twain_32.dll", EntryPoint = "#1")]
private static extern TwRC DSpxfer([In, Out] TwIdentity origin, [In] TwIdentity dest, TwDG dg, TwDAT dat, TwMSG msg, [In, Out] TwPendingXfers pxfr);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalAlloc(int flags, int size);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalLock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern bool GlobalUnlock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GlobalFree(IntPtr handle);
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int GetMessagePos();
[DllImport("user32.dll", ExactSpelling = true)]
private static extern int GetMessageTime();
[DllImport("gdi32.dll", ExactSpelling = true)]
private static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
[DllImport("gdi32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr CreateDC(string szdriver, string szdevice, string szoutput, IntPtr devmode);
[DllImport("gdi32.dll", ExactSpelling = true)]
private static extern bool DeleteDC(IntPtr hdc);
public static int ScreenBitDepth
{
get
{
IntPtr screenDC = CreateDC("DISPLAY", null, null, IntPtr.Zero);
int bitDepth = GetDeviceCaps(screenDC, 12);
bitDepth *= GetDeviceCaps(screenDC, 14);
DeleteDC(screenDC);
return bitDepth;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct WINMSG
{
public IntPtr hwnd;
public int message;
public IntPtr wParam;
public IntPtr lParam;
public int time;
public int x;
public int y;
}
} // class Twain
}
| |
// 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.IO;
using System.Net.Http.Headers;
using System.Net.Test.Common;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
// Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
// to separately Dispose (or have a 'using' statement) for the handler.
public class PostScenarioTest
{
private const string ExpectedContent = "Test contest";
private const string UserName = "user1";
private const string Password = "password1";
private readonly static Uri BasicAuthServerUri =
HttpTestServers.BasicAuthUriForCreds(false, UserName, Password);
private readonly static Uri SecureBasicAuthServerUri =
HttpTestServers.BasicAuthUriForCreds(true, UserName, Password);
private readonly ITestOutputHelper _output;
public readonly static object[][] EchoServers = HttpTestServers.EchoServers;
public readonly static object[][] BasicAuthEchoServers =
new object[][]
{
new object[] { BasicAuthServerUri },
new object[] { SecureBasicAuthServerUri }
};
public PostScenarioTest(ITestOutputHelper output)
{
_output = output;
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostNoContentUsingContentLengthSemantics_Success(Uri serverUri)
{
await PostHelper(serverUri, string.Empty, null,
useContentLengthUpload: true, useChunkedEncodingUpload: false);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostEmptyContentUsingContentLengthSemantics_Success(Uri serverUri)
{
await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
useContentLengthUpload: true, useChunkedEncodingUpload: false);
}
[ActiveIssue(5485, PlatformID.Windows)]
[Theory, MemberData(nameof(EchoServers))]
public async Task PostEmptyContentUsingChunkedEncoding_Success(Uri serverUri)
{
await PostHelper(serverUri, string.Empty, new StringContent(string.Empty),
useContentLengthUpload: false, useChunkedEncodingUpload: true);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostUsingContentLengthSemantics_Success(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
useContentLengthUpload: true, useChunkedEncodingUpload: false);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostUsingChunkedEncoding_Success(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
useContentLengthUpload: false, useChunkedEncodingUpload: true);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostSyncBlockingContentUsingChunkedEncoding_Success(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new SyncBlockingContent(ExpectedContent),
useContentLengthUpload: false, useChunkedEncodingUpload: true);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostRepeatedFlushContentUsingChunkedEncoding_Success(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new RepeatedFlushContent(ExpectedContent),
useContentLengthUpload: false, useChunkedEncodingUpload: true);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostUsingUsingConflictingSemantics_UsesChunkedSemantics(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
useContentLengthUpload: true, useChunkedEncodingUpload: true);
}
[Theory, MemberData(nameof(EchoServers))]
public async Task PostUsingNoSpecifiedSemantics_UsesChunkedSemantics(Uri serverUri)
{
await PostHelper(serverUri, ExpectedContent, new StringContent(ExpectedContent),
useContentLengthUpload: false, useChunkedEncodingUpload: false);
}
[Theory, MemberData(nameof(BasicAuthEchoServers))]
public async Task PostRewindableContentUsingAuth_NoPreAuthenticate_Success(Uri serverUri)
{
HttpContent content = CustomContent.Create(ExpectedContent, true);
var credential = new NetworkCredential(UserName, Password);
await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, false);
}
[Theory, MemberData(nameof(BasicAuthEchoServers))]
public async Task PostNonRewindableContentUsingAuth_NoPreAuthenticate_ThrowsInvalidOperationException(Uri serverUri)
{
HttpContent content = CustomContent.Create(ExpectedContent, false);
var credential = new NetworkCredential(UserName, Password);
await Assert.ThrowsAsync<InvalidOperationException>(() =>
PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: false));
}
[Theory, MemberData(nameof(BasicAuthEchoServers))]
public async Task PostNonRewindableContentUsingAuth_PreAuthenticate_Success(Uri serverUri)
{
HttpContent content = CustomContent.Create(ExpectedContent, false);
var credential = new NetworkCredential(UserName, Password);
await PostUsingAuthHelper(serverUri, ExpectedContent, content, credential, preAuthenticate: true);
}
private async Task PostHelper(
Uri serverUri,
string requestBody,
HttpContent requestContent,
bool useContentLengthUpload,
bool useChunkedEncodingUpload)
{
using (var client = new HttpClient())
{
if (!useContentLengthUpload && requestContent != null)
{
requestContent.Headers.ContentLength = null;
}
if (useChunkedEncodingUpload)
{
client.DefaultRequestHeaders.TransferEncodingChunked = true;
}
using (HttpResponseMessage response = await client.PostAsync(serverUri, requestContent))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
if (!useContentLengthUpload && !useChunkedEncodingUpload)
{
useChunkedEncodingUpload = true;
}
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
useChunkedEncodingUpload,
requestBody);
}
}
}
private async Task PostUsingAuthHelper(
Uri serverUri,
string requestBody,
HttpContent requestContent,
NetworkCredential credential,
bool preAuthenticate)
{
var handler = new HttpClientHandler();
handler.PreAuthenticate = preAuthenticate;
handler.Credentials = credential;
using (var client = new HttpClient(handler))
{
// Send HEAD request to help bypass the 401 auth challenge for the latter POST assuming
// that the authentication will be cached and re-used later when PreAuthenticate is true.
var request = new HttpRequestMessage(HttpMethod.Head, serverUri);
HttpResponseMessage response;
using (response = await client.SendAsync(request))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
// Now send POST request.
request = new HttpRequestMessage(HttpMethod.Post, serverUri);
request.Content = requestContent;
requestContent.Headers.ContentLength = null;
request.Headers.TransferEncodingChunked = true;
using (response = await client.PostAsync(serverUri, requestContent))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
true,
requestBody);
}
}
}
}
}
| |
// 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.Net.Http.Headers
{
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "This is not a collection")]
public sealed class HttpResponseHeaders : HttpHeaders
{
private static readonly Dictionary<string, HttpHeaderParser> s_parserStore;
private static readonly HashSet<string> s_invalidHeaders;
private HttpGeneralHeaders _generalHeaders;
private HttpHeaderValueCollection<string> _acceptRanges;
private HttpHeaderValueCollection<AuthenticationHeaderValue> _wwwAuthenticate;
private HttpHeaderValueCollection<AuthenticationHeaderValue> _proxyAuthenticate;
private HttpHeaderValueCollection<ProductInfoHeaderValue> _server;
private HttpHeaderValueCollection<string> _vary;
#region Response Headers
public HttpHeaderValueCollection<string> AcceptRanges
{
get
{
if (_acceptRanges == null)
{
_acceptRanges = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.AcceptRanges,
this, HeaderUtilities.TokenValidator);
}
return _acceptRanges;
}
}
public TimeSpan? Age
{
get { return HeaderUtilities.GetTimeSpanValue(HttpKnownHeaderNames.Age, this); }
set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Age, value); }
}
public EntityTagHeaderValue ETag
{
get { return (EntityTagHeaderValue)GetParsedValues(HttpKnownHeaderNames.ETag); }
set { SetOrRemoveParsedValue(HttpKnownHeaderNames.ETag, value); }
}
public Uri Location
{
get { return (Uri)GetParsedValues(HttpKnownHeaderNames.Location); }
set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Location, value); }
}
public HttpHeaderValueCollection<AuthenticationHeaderValue> ProxyAuthenticate
{
get
{
if (_proxyAuthenticate == null)
{
_proxyAuthenticate = new HttpHeaderValueCollection<AuthenticationHeaderValue>(
HttpKnownHeaderNames.ProxyAuthenticate, this);
}
return _proxyAuthenticate;
}
}
public RetryConditionHeaderValue RetryAfter
{
get { return (RetryConditionHeaderValue)GetParsedValues(HttpKnownHeaderNames.RetryAfter); }
set { SetOrRemoveParsedValue(HttpKnownHeaderNames.RetryAfter, value); }
}
public HttpHeaderValueCollection<ProductInfoHeaderValue> Server
{
get
{
if (_server == null)
{
_server = new HttpHeaderValueCollection<ProductInfoHeaderValue>(HttpKnownHeaderNames.Server, this);
}
return _server;
}
}
public HttpHeaderValueCollection<string> Vary
{
get
{
if (_vary == null)
{
_vary = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.Vary,
this, HeaderUtilities.TokenValidator);
}
return _vary;
}
}
public HttpHeaderValueCollection<AuthenticationHeaderValue> WwwAuthenticate
{
get
{
if (_wwwAuthenticate == null)
{
_wwwAuthenticate = new HttpHeaderValueCollection<AuthenticationHeaderValue>(
HttpKnownHeaderNames.WWWAuthenticate, this);
}
return _wwwAuthenticate;
}
}
#endregion
#region General Headers
public CacheControlHeaderValue CacheControl
{
get { return _generalHeaders.CacheControl; }
set { _generalHeaders.CacheControl = value; }
}
public HttpHeaderValueCollection<string> Connection
{
get { return _generalHeaders.Connection; }
}
public bool? ConnectionClose
{
get { return _generalHeaders.ConnectionClose; }
set { _generalHeaders.ConnectionClose = value; }
}
public DateTimeOffset? Date
{
get { return _generalHeaders.Date; }
set { _generalHeaders.Date = value; }
}
public HttpHeaderValueCollection<NameValueHeaderValue> Pragma
{
get { return _generalHeaders.Pragma; }
}
public HttpHeaderValueCollection<string> Trailer
{
get { return _generalHeaders.Trailer; }
}
public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding
{
get { return _generalHeaders.TransferEncoding; }
}
public bool? TransferEncodingChunked
{
get { return _generalHeaders.TransferEncodingChunked; }
set { _generalHeaders.TransferEncodingChunked = value; }
}
public HttpHeaderValueCollection<ProductHeaderValue> Upgrade
{
get { return _generalHeaders.Upgrade; }
}
public HttpHeaderValueCollection<ViaHeaderValue> Via
{
get { return _generalHeaders.Via; }
}
public HttpHeaderValueCollection<WarningHeaderValue> Warning
{
get { return _generalHeaders.Warning; }
}
#endregion
internal HttpResponseHeaders()
{
_generalHeaders = new HttpGeneralHeaders(this);
base.SetConfiguration(s_parserStore, s_invalidHeaders);
}
static HttpResponseHeaders()
{
s_parserStore = new Dictionary<string, HttpHeaderParser>(StringComparer.OrdinalIgnoreCase);
s_parserStore.Add(HttpKnownHeaderNames.AcceptRanges, GenericHeaderParser.TokenListParser);
s_parserStore.Add(HttpKnownHeaderNames.Age, TimeSpanHeaderParser.Parser);
s_parserStore.Add(HttpKnownHeaderNames.ETag, GenericHeaderParser.SingleValueEntityTagParser);
s_parserStore.Add(HttpKnownHeaderNames.Location, UriHeaderParser.RelativeOrAbsoluteUriParser);
s_parserStore.Add(HttpKnownHeaderNames.ProxyAuthenticate, GenericHeaderParser.MultipleValueAuthenticationParser);
s_parserStore.Add(HttpKnownHeaderNames.RetryAfter, GenericHeaderParser.RetryConditionParser);
s_parserStore.Add(HttpKnownHeaderNames.Server, ProductInfoHeaderParser.MultipleValueParser);
s_parserStore.Add(HttpKnownHeaderNames.Vary, GenericHeaderParser.TokenListParser);
s_parserStore.Add(HttpKnownHeaderNames.WWWAuthenticate, GenericHeaderParser.MultipleValueAuthenticationParser);
HttpGeneralHeaders.AddParsers(s_parserStore);
s_invalidHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
HttpContentHeaders.AddKnownHeaders(s_invalidHeaders);
// Note: Reserved request header names are allowed as custom response header names. Reserved request
// headers have no defined meaning or format when used on a response. This enables a client to accept
// any headers sent from the server as either content headers or response headers.
}
internal static void AddKnownHeaders(HashSet<string> headerSet)
{
Contract.Requires(headerSet != null);
headerSet.Add(HttpKnownHeaderNames.AcceptRanges);
headerSet.Add(HttpKnownHeaderNames.Age);
headerSet.Add(HttpKnownHeaderNames.ETag);
headerSet.Add(HttpKnownHeaderNames.Location);
headerSet.Add(HttpKnownHeaderNames.ProxyAuthenticate);
headerSet.Add(HttpKnownHeaderNames.RetryAfter);
headerSet.Add(HttpKnownHeaderNames.Server);
headerSet.Add(HttpKnownHeaderNames.Vary);
headerSet.Add(HttpKnownHeaderNames.WWWAuthenticate);
}
internal override void AddHeaders(HttpHeaders sourceHeaders)
{
base.AddHeaders(sourceHeaders);
HttpResponseHeaders sourceResponseHeaders = sourceHeaders as HttpResponseHeaders;
Debug.Assert(sourceResponseHeaders != null);
// Copy special values, but do not overwrite
_generalHeaders.AddSpecialsFrom(sourceResponseHeaders._generalHeaders);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Contoso.Core.PermissionListingWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the ConTurnoReserva class.
/// </summary>
[Serializable]
public partial class ConTurnoReservaCollection : ActiveList<ConTurnoReserva, ConTurnoReservaCollection>
{
public ConTurnoReservaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ConTurnoReservaCollection</returns>
public ConTurnoReservaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ConTurnoReserva o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CON_TurnoReserva table.
/// </summary>
[Serializable]
public partial class ConTurnoReserva : ActiveRecord<ConTurnoReserva>, IActiveRecord
{
#region .ctors and Default Settings
public ConTurnoReserva()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ConTurnoReserva(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ConTurnoReserva(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ConTurnoReserva(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_TurnoReserva", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdReserva = new TableSchema.TableColumn(schema);
colvarIdReserva.ColumnName = "idReserva";
colvarIdReserva.DataType = DbType.Int32;
colvarIdReserva.MaxLength = 0;
colvarIdReserva.AutoIncrement = true;
colvarIdReserva.IsNullable = false;
colvarIdReserva.IsPrimaryKey = true;
colvarIdReserva.IsForeignKey = false;
colvarIdReserva.IsReadOnly = false;
colvarIdReserva.DefaultSetting = @"";
colvarIdReserva.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdReserva);
TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema);
colvarIdUsuario.ColumnName = "idUsuario";
colvarIdUsuario.DataType = DbType.Int32;
colvarIdUsuario.MaxLength = 0;
colvarIdUsuario.AutoIncrement = false;
colvarIdUsuario.IsNullable = false;
colvarIdUsuario.IsPrimaryKey = false;
colvarIdUsuario.IsForeignKey = true;
colvarIdUsuario.IsReadOnly = false;
colvarIdUsuario.DefaultSetting = @"";
colvarIdUsuario.ForeignKeyTableName = "Sys_Usuario";
schema.Columns.Add(colvarIdUsuario);
TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema);
colvarIdPaciente.ColumnName = "idPaciente";
colvarIdPaciente.DataType = DbType.Int32;
colvarIdPaciente.MaxLength = 0;
colvarIdPaciente.AutoIncrement = false;
colvarIdPaciente.IsNullable = false;
colvarIdPaciente.IsPrimaryKey = false;
colvarIdPaciente.IsForeignKey = true;
colvarIdPaciente.IsReadOnly = false;
colvarIdPaciente.DefaultSetting = @"";
colvarIdPaciente.ForeignKeyTableName = "Sys_Paciente";
schema.Columns.Add(colvarIdPaciente);
TableSchema.TableColumn colvarIdTurno = new TableSchema.TableColumn(schema);
colvarIdTurno.ColumnName = "idTurno";
colvarIdTurno.DataType = DbType.Int32;
colvarIdTurno.MaxLength = 0;
colvarIdTurno.AutoIncrement = false;
colvarIdTurno.IsNullable = false;
colvarIdTurno.IsPrimaryKey = false;
colvarIdTurno.IsForeignKey = true;
colvarIdTurno.IsReadOnly = false;
colvarIdTurno.DefaultSetting = @"";
colvarIdTurno.ForeignKeyTableName = "CON_Turno";
schema.Columns.Add(colvarIdTurno);
TableSchema.TableColumn colvarReservaHasta = new TableSchema.TableColumn(schema);
colvarReservaHasta.ColumnName = "reservaHasta";
colvarReservaHasta.DataType = DbType.DateTime;
colvarReservaHasta.MaxLength = 0;
colvarReservaHasta.AutoIncrement = false;
colvarReservaHasta.IsNullable = false;
colvarReservaHasta.IsPrimaryKey = false;
colvarReservaHasta.IsForeignKey = false;
colvarReservaHasta.IsReadOnly = false;
colvarReservaHasta.DefaultSetting = @"";
colvarReservaHasta.ForeignKeyTableName = "";
schema.Columns.Add(colvarReservaHasta);
TableSchema.TableColumn colvarCofirmoTurno = new TableSchema.TableColumn(schema);
colvarCofirmoTurno.ColumnName = "cofirmoTurno";
colvarCofirmoTurno.DataType = DbType.Boolean;
colvarCofirmoTurno.MaxLength = 0;
colvarCofirmoTurno.AutoIncrement = false;
colvarCofirmoTurno.IsNullable = false;
colvarCofirmoTurno.IsPrimaryKey = false;
colvarCofirmoTurno.IsForeignKey = false;
colvarCofirmoTurno.IsReadOnly = false;
colvarCofirmoTurno.DefaultSetting = @"((0))";
colvarCofirmoTurno.ForeignKeyTableName = "";
schema.Columns.Add(colvarCofirmoTurno);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_TurnoReserva",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdReserva")]
[Bindable(true)]
public int IdReserva
{
get { return GetColumnValue<int>(Columns.IdReserva); }
set { SetColumnValue(Columns.IdReserva, value); }
}
[XmlAttribute("IdUsuario")]
[Bindable(true)]
public int IdUsuario
{
get { return GetColumnValue<int>(Columns.IdUsuario); }
set { SetColumnValue(Columns.IdUsuario, value); }
}
[XmlAttribute("IdPaciente")]
[Bindable(true)]
public int IdPaciente
{
get { return GetColumnValue<int>(Columns.IdPaciente); }
set { SetColumnValue(Columns.IdPaciente, value); }
}
[XmlAttribute("IdTurno")]
[Bindable(true)]
public int IdTurno
{
get { return GetColumnValue<int>(Columns.IdTurno); }
set { SetColumnValue(Columns.IdTurno, value); }
}
[XmlAttribute("ReservaHasta")]
[Bindable(true)]
public DateTime ReservaHasta
{
get { return GetColumnValue<DateTime>(Columns.ReservaHasta); }
set { SetColumnValue(Columns.ReservaHasta, value); }
}
[XmlAttribute("CofirmoTurno")]
[Bindable(true)]
public bool CofirmoTurno
{
get { return GetColumnValue<bool>(Columns.CofirmoTurno); }
set { SetColumnValue(Columns.CofirmoTurno, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a SysPaciente ActiveRecord object related to this ConTurnoReserva
///
/// </summary>
public DalSic.SysPaciente SysPaciente
{
get { return DalSic.SysPaciente.FetchByID(this.IdPaciente); }
set { SetColumnValue("idPaciente", value.IdPaciente); }
}
/// <summary>
/// Returns a SysUsuario ActiveRecord object related to this ConTurnoReserva
///
/// </summary>
public DalSic.SysUsuario SysUsuario
{
get { return DalSic.SysUsuario.FetchByID(this.IdUsuario); }
set { SetColumnValue("idUsuario", value.IdUsuario); }
}
/// <summary>
/// Returns a ConTurno ActiveRecord object related to this ConTurnoReserva
///
/// </summary>
public DalSic.ConTurno ConTurno
{
get { return DalSic.ConTurno.FetchByID(this.IdTurno); }
set { SetColumnValue("idTurno", value.IdTurno); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdUsuario,int varIdPaciente,int varIdTurno,DateTime varReservaHasta,bool varCofirmoTurno)
{
ConTurnoReserva item = new ConTurnoReserva();
item.IdUsuario = varIdUsuario;
item.IdPaciente = varIdPaciente;
item.IdTurno = varIdTurno;
item.ReservaHasta = varReservaHasta;
item.CofirmoTurno = varCofirmoTurno;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdReserva,int varIdUsuario,int varIdPaciente,int varIdTurno,DateTime varReservaHasta,bool varCofirmoTurno)
{
ConTurnoReserva item = new ConTurnoReserva();
item.IdReserva = varIdReserva;
item.IdUsuario = varIdUsuario;
item.IdPaciente = varIdPaciente;
item.IdTurno = varIdTurno;
item.ReservaHasta = varReservaHasta;
item.CofirmoTurno = varCofirmoTurno;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdReservaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdUsuarioColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdPacienteColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn IdTurnoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn ReservaHastaColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn CofirmoTurnoColumn
{
get { return Schema.Columns[5]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdReserva = @"idReserva";
public static string IdUsuario = @"idUsuario";
public static string IdPaciente = @"idPaciente";
public static string IdTurno = @"idTurno";
public static string ReservaHasta = @"reservaHasta";
public static string CofirmoTurno = @"cofirmoTurno";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.Management.DataLake.Store
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AccountOperations operations.
/// </summary>
internal partial class AccountOperations : IServiceOperations<DataLakeStoreAccountManagementClient>, IAccountOperations
{
/// <summary>
/// Tests the existence of the specified Data Lake Store firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account from which to test the firewall
/// rule's existence.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the firewall rule to test for existence.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> FirewallRuleExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (firewallRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "firewallRuleName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("firewallRuleName", firewallRuleName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetFirewallRule", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules/{firewallRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{firewallRuleName}", Uri.EscapeDataString(firewallRuleName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if(_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.ToLowerInvariant().Contains("resourcenotfound"))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests whether the specified Data Lake Store account exists.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to test existence of.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> ExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.ToLowerInvariant().Contains("resourcenotfound"))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = true;
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
namespace Tests.Framework
{
public class Auditor
{
public Func<VirtualizedCluster> Cluster { get; set; }
public Action<IConnectionPool> AssertPoolBeforeStartup { get; set; }
public Action<IConnectionPool> AssertPoolAfterStartup { get; set; }
public Action<IConnectionPool> AssertPoolBeforeCall { get; set; }
public Action<IConnectionPool> AssertPoolAfterCall { get; set; }
private VirtualizedCluster _cluster;
private VirtualizedCluster _clusterAsync;
private bool StartedUp { get; }
public Auditor(Func<VirtualizedCluster> setup) {
this.Cluster = setup;
}
private Auditor(VirtualizedCluster cluster, VirtualizedCluster clusterAsync)
{
_cluster = cluster;
_clusterAsync = clusterAsync;
this.StartedUp = true;
}
public IResponse Response { get; internal set; }
public IResponse ResponseAsync { get; internal set; }
public List<Audit> AsyncAuditTrail { get; set; }
public List<Audit> AuditTrail { get; set; }
public void ChangeTime(Func<DateTime, DateTime> selector)
{
this._cluster = _cluster ?? this.Cluster();
this._clusterAsync = _clusterAsync ?? this.Cluster();
this._cluster.ChangeTime(selector);
this._clusterAsync.ChangeTime(selector);
}
public async Task<Auditor> TraceStartup(ClientCall callTrace = null)
{
this._cluster = _cluster ?? this.Cluster();
if (!this.StartedUp) this.AssertPoolBeforeStartup?.Invoke(this._cluster.ConnectionPool);
this.AssertPoolBeforeCall?.Invoke(this._cluster.ConnectionPool);
this.Response = this._cluster.ClientCall(callTrace?.RequestOverrides);
this.AuditTrail = this.Response.ApiCall.AuditTrail;
if (!this.StartedUp) this.AssertPoolAfterStartup?.Invoke(this._cluster.ConnectionPool);
this.AssertPoolAfterCall?.Invoke(this._cluster.ConnectionPool);
this._clusterAsync = _clusterAsync ?? this.Cluster();
if (!this.StartedUp) this.AssertPoolBeforeStartup?.Invoke(this._clusterAsync.ConnectionPool);
this.AssertPoolBeforeCall?.Invoke(this._clusterAsync.ConnectionPool);
this.ResponseAsync = await this._clusterAsync.ClientCallAsync(callTrace?.RequestOverrides);
this.AsyncAuditTrail = this.ResponseAsync.ApiCall.AuditTrail;
if (!this.StartedUp) this.AssertPoolAfterStartup?.Invoke(this._clusterAsync.ConnectionPool);
this.AssertPoolAfterCall?.Invoke(this._clusterAsync.ConnectionPool);
return new Auditor(_cluster, _clusterAsync);
}
public async Task<Auditor> TraceCall(ClientCall callTrace, int nthCall = 0)
{
await this.TraceStartup(callTrace);
return AssertAuditTrails(callTrace, nthCall);
}
#pragma warning disable 1998 // Async method lacks 'await' operators and will run synchronously
private async Task TraceException<TException>(ClientCall callTrace, Action<TException> assert)
#pragma warning restore 1998 // Async method lacks 'await' operators and will run synchronously
where TException : ElasticsearchClientException
{
this._cluster = _cluster ?? this.Cluster();
this._cluster.ClientThrows(true);
this.AssertPoolBeforeCall?.Invoke(this._cluster.ConnectionPool);
Action call = () => this._cluster.ClientCall(callTrace?.RequestOverrides);
var exception = call.ShouldThrowExactly<TException>()
.Subject.First();
assert(exception);
this.AuditTrail = exception.AuditTrail;
this.AssertPoolAfterCall?.Invoke(this._cluster.ConnectionPool);
this._clusterAsync = _clusterAsync ?? this.Cluster();
this._clusterAsync.ClientThrows(true);
Func<Task> callAsync = async () => await this._clusterAsync.ClientCallAsync(callTrace?.RequestOverrides);
exception = callAsync.ShouldThrowExactly<TException>()
.Subject.First();
assert(exception);
this.AsyncAuditTrail = exception.AuditTrail;
this.AssertPoolAfterCall?.Invoke(this._clusterAsync.ConnectionPool);
}
public async Task<Auditor> TraceElasticsearchException(ClientCall callTrace, Action<ElasticsearchClientException> assert)
{
await this.TraceException(callTrace, assert);
var audit = new Auditor(_cluster, _clusterAsync);
return await audit.TraceElasticsearchExceptionOnResponse(callTrace, assert);
}
public async Task<Auditor> TraceUnexpectedElasticsearchException(ClientCall callTrace, Action<UnexpectedElasticsearchClientException> assert)
{
await this.TraceException(callTrace, assert);
return new Auditor(_cluster, _clusterAsync);
}
#pragma warning disable 1998
public async Task<Auditor> TraceElasticsearchExceptionOnResponse(ClientCall callTrace, Action<ElasticsearchClientException> assert)
#pragma warning restore 1998
{
this._cluster = _cluster ?? this.Cluster();
this._cluster.ClientThrows(false);
this.AssertPoolBeforeCall?.Invoke(this._cluster.ConnectionPool);
Action call = () => { this.Response = this._cluster.ClientCall(callTrace?.RequestOverrides); };
call.ShouldNotThrow();
this.Response.ShouldNotBeValid();
var exception = this.Response.ApiCall.OriginalException as ElasticsearchClientException;
exception.Should().NotBeNull("OriginalException on response is not expected ElasticsearchClientException");
assert(exception);
this.AuditTrail = exception.AuditTrail;
this.AssertPoolAfterCall?.Invoke(this._cluster.ConnectionPool);
this._clusterAsync = _clusterAsync ?? this.Cluster();
this._clusterAsync.ClientThrows(false);
Func<Task> callAsync = async () => { this.ResponseAsync = await this._clusterAsync.ClientCallAsync(callTrace?.RequestOverrides); };
callAsync.ShouldNotThrow();
this.ResponseAsync.ShouldNotBeValid();
exception = this.ResponseAsync.ApiCall.OriginalException as ElasticsearchClientException;
exception.Should().NotBeNull("OriginalException on response is not expected ElasticsearchClientException");
assert(exception);
this.AsyncAuditTrail = exception.AuditTrail;
this.AssertPoolAfterCall?.Invoke(this._clusterAsync.ConnectionPool);
var audit = new Auditor(_cluster, _clusterAsync);
return audit;
}
#pragma warning disable 1998
public async Task<Auditor> TraceUnexpectedException(ClientCall callTrace, Action<UnexpectedElasticsearchClientException> assert)
#pragma warning restore 1998
{
this._cluster = _cluster ?? this.Cluster();
this.AssertPoolBeforeCall?.Invoke(this._cluster.ConnectionPool);
Action call = () => this._cluster.ClientCall(callTrace?.RequestOverrides);
var exception = call.ShouldThrowExactly<UnexpectedElasticsearchClientException>()
.Subject.First();
assert(exception);
this.AuditTrail = exception.AuditTrail;
this.AssertPoolAfterCall?.Invoke(this._cluster.ConnectionPool);
this._clusterAsync = _clusterAsync ?? this.Cluster();
Func<Task> callAsync = async () => await this._clusterAsync.ClientCallAsync(callTrace?.RequestOverrides);
exception = callAsync.ShouldThrowExactly<UnexpectedElasticsearchClientException>()
.Subject.First();
assert(exception);
this.AsyncAuditTrail = exception.AuditTrail;
this.AssertPoolAfterCall?.Invoke(this._clusterAsync.ConnectionPool);
return new Auditor(_cluster, _clusterAsync);
}
private Auditor AssertAuditTrails(ClientCall callTrace, int nthCall)
{
this.AuditTrail.Count.Should()
.Be(this.AsyncAuditTrail.Count, "calling async should have the same audit trail length as the sync call");
AssertTrailOnResponse(callTrace, this.AuditTrail, true, nthCall);
AssertTrailOnResponse(callTrace, this.AuditTrail, false, nthCall);
callTrace?.AssertPoolAfterCall?.Invoke(this._cluster.ConnectionPool);
callTrace?.AssertPoolAfterCall?.Invoke(this._clusterAsync.ConnectionPool);
return new Auditor(_cluster, _clusterAsync);
}
public async Task<Auditor> TraceCalls(params ClientCall[] audits)
{
var auditor = this;
foreach (var a in audits.Select((a, i)=> new { a, i }))
{
auditor = await auditor.TraceCall(a.a, a.i);
}
return auditor;
}
private static void AssertTrailOnResponse(ClientCall callTrace, List<Audit> auditTrail, bool sync, int nthCall)
{
var typeOfTrail = (sync ? "synchronous" : "asynchronous") + " audit trail";
var nthClientCall = (nthCall + 1).ToOrdinal();
callTrace.Select(c=>c.Event).Should().ContainInOrder(auditTrail.Select(a=>a.Event), $"the {nthClientCall} client call's {typeOfTrail} should assert ALL audit trail items");
foreach (var t in auditTrail.Select((a, i) => new { a, i }))
{
var i = t.i;
var audit = t.a;
var nthAuditTrailItem = (i + 1).ToOrdinal();
var because = $"thats the {{0}} specified on the {nthAuditTrailItem} item in the {nthClientCall} client call's {typeOfTrail}";
var c = callTrace[i];
audit.Event.Should().Be(c.Event, string.Format(because, "event"));
if (c.Port.HasValue) audit.Node.Uri.Port.Should().Be(c.Port.Value, string.Format(because, "port"));
c.SimpleAssert?.Invoke(audit);
c.AssertWithBecause?.Invoke(string.Format(because, "custom assertion"), audit);
}
callTrace.Count.Should().Be(auditTrail.Count);
}
}
}
| |
// 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: Synchronizes access to a shared resource or region of code in a multi-threaded
** program.
**
**
=============================================================================*/
using System;
using System.Runtime;
using System.Runtime.Remoting;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
{
public static class Monitor
{
/*=========================================================================
** Obtain the monitor lock of obj. Will block if another thread holds the lock
** Will not block if the current thread holds the lock,
** however the caller must ensure that the same number of Exit
** calls are made as there were Enter calls.
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Enter(Object obj);
// Use a ref bool instead of out to ensure that unverifiable code must
// initialize this value to something. If we used out, the value
// could be uninitialized if we threw an exception in our prolog.
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void Enter(Object obj, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnter(obj, ref lockTaken);
Debug.Assert(lockTaken);
}
private static void ThrowLockTakenException()
{
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeFalse"), "lockTaken");
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnter(Object obj, ref bool lockTaken);
/*=========================================================================
** Release the monitor lock. If one or more threads are waiting to acquire the
** lock, and the current thread has executed as many Exits as
** Enters, one of the threads will be unblocked and allowed to proceed.
**
** Exceptions: ArgumentNullException if object is null.
** SynchronizationLockException if the current thread does not
** own the lock.
=========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Exit(Object obj);
/*=========================================================================
** Similar to Enter, but will never block. That is, if the current thread can
** acquire the monitor lock without blocking, it will do so and TRUE will
** be returned. Otherwise FALSE will be returned.
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
public static bool TryEnter(Object obj)
{
bool lockTaken = false;
TryEnter(obj, 0, ref lockTaken);
return lockTaken;
}
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void TryEnter(Object obj, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, 0, ref lockTaken);
}
/*=========================================================================
** Version of TryEnter that will block, but only up to a timeout period
** expressed in milliseconds. If timeout == Timeout.Infinite the method
** becomes equivalent to Enter.
**
** Exceptions: ArgumentNullException if object is null.
** ArgumentException if timeout < 0.
=========================================================================*/
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static bool TryEnter(Object obj, int millisecondsTimeout)
{
bool lockTaken = false;
TryEnter(obj, millisecondsTimeout, ref lockTaken);
return lockTaken;
}
private static int MillisecondsTimeoutFromTimeSpan(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
return (int)tm;
}
public static bool TryEnter(Object obj, TimeSpan timeout)
{
return TryEnter(obj, MillisecondsTimeoutFromTimeSpan(timeout));
}
// The JIT should inline this method to allow check of lockTaken argument to be optimized out
// in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM.
public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, millisecondsTimeout, ref lockTaken);
}
public static void TryEnter(Object obj, TimeSpan timeout, ref bool lockTaken)
{
if (lockTaken)
ThrowLockTakenException();
ReliableEnterTimeout(obj, MillisecondsTimeoutFromTimeSpan(timeout), ref lockTaken);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnterTimeout(Object obj, int timeout, ref bool lockTaken);
public static bool IsEntered(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
return IsEnteredNative(obj);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsEnteredNative(Object obj);
/*========================================================================
** Waits for notification from the object (via a Pulse/PulseAll).
** timeout indicates how long to wait before the method returns.
** This method acquires the monitor waithandle for the object
** If this thread holds the monitor lock for the object, it releases it.
** On exit from the method, it obtains the monitor lock back.
** If exitContext is true then the synchronization domain for the context
** (if in a synchronized context) is exited before the wait and reacquired
**
** Exceptions: ArgumentNullException if object is null.
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool ObjWait(bool exitContext, int millisecondsTimeout, Object obj);
public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext)
{
if (obj == null)
throw (new ArgumentNullException(nameof(obj)));
return ObjWait(exitContext, millisecondsTimeout, obj);
}
public static bool Wait(Object obj, TimeSpan timeout, bool exitContext)
{
return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), exitContext);
}
public static bool Wait(Object obj, int millisecondsTimeout)
{
return Wait(obj, millisecondsTimeout, false);
}
public static bool Wait(Object obj, TimeSpan timeout)
{
return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), false);
}
public static bool Wait(Object obj)
{
return Wait(obj, Timeout.Infinite, false);
}
/*========================================================================
** Sends a notification to a single waiting object.
* Exceptions: SynchronizationLockException if this method is not called inside
* a synchronized block of code.
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulse(Object obj);
public static void Pulse(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
ObjPulse(obj);
}
/*========================================================================
** Sends a notification to all waiting objects.
========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulseAll(Object obj);
public static void PulseAll(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
ObjPulseAll(obj);
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
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.Windows.Controls;
using Dynamo.Controls;
using Dynamo.Models;
using Dynamo.Wpf;
using ProtoCore.AST.AssociativeAST;
using Kodestruct.Common.CalculationLogger;
using Kodestruct.Dynamo.Common;
using Kodestruct.Loads.ASCE7.Entities;
using System.Xml;
using System.Windows.Input;
using KodestructDynamoUI.Views.Loads.ASCE7;
using GalaSoft.MvvmLight.Command;
using System.Reflection;
using Kodestruct.Dynamo.Common.Infra.TreeItems;
using System.Windows.Resources;
using System.Windows;
using System.IO;
using Kodestruct.Dynamo.UI.Common.TreeItems;
using Dynamo.Nodes;
using Dynamo.Graph.Nodes;
using Dynamo.Graph;
namespace Kodestruct.Loads.ASCE7.Gravity.Dead
{
/// <summary>
///Building component ID (name) used for calculation of dead weight
/// </summary>
[NodeName("Component ID selection")]
[NodeCategory("Kodestruct.Loads.ASCE7.Gravity.Dead")]
[NodeDescription("Building component ID (name) used for calculation of dead weight")]
[IsDesignScriptCompatible]
public class ComponentIdSelection : UiNodeBase
{
public ComponentIdSelection()
{
ReportEntry="";
ComponentId = "Deck3InLWFill";
ComponentOption1 = 1;
ComponentOption2 = 0;
ComponentValue = 0;
//OutPortData.Add(new PortData("ReportEntry", "calculation log entries (for reporting)"));
OutPortData.Add(new PortData("ComponentId", "building component id (name)"));
OutPortData.Add(new PortData("ComponentOption1", "building component subtype (option1)"));
OutPortData.Add(new PortData("ComponentOption2", "building component subtype (option2)"));
OutPortData.Add(new PortData("ComponentValue", "building component numerical value"));
RegisterAllPorts();
//PropertyChanged += NodePropertyChanged;
}
/// <summary>
/// Gets the type of this class, to be used in base class for reflection
/// </summary>
protected override Type GetModelType()
{
return GetType();
}
#region properties
#region InputProperties
#endregion
#region OutputProperties
#region ComponentIdProperty
/// <summary>
/// ComponentId property
/// </summary>
/// <value>building component id (name)</value>
public string _ComponentId;
public string ComponentId
{
get { return _ComponentId; }
set
{
_ComponentId = value;
OnNodeModified(true);
RaisePropertyChanged("ComponentId");
}
}
#endregion
#region ComponentOption1Property
/// <summary>
/// ComponentOption1 property
/// </summary>
/// <value>building component subtype (option1)</value>
public double _ComponentOption1;
public double ComponentOption1
{
get { return _ComponentOption1; }
set
{
_ComponentOption1 = value;
RaisePropertyChanged("ComponentOption1");
OnNodeModified(true);
}
}
#endregion
#region ComponentOption2Property
/// <summary>
/// ComponentOption2 property
/// </summary>
/// <value>building component subtype (option2)</value>
public double _ComponentOption2;
public double ComponentOption2
{
get { return _ComponentOption2; }
set
{
_ComponentOption2 = value;
RaisePropertyChanged("ComponentOption2");
OnNodeModified(true);
}
}
#endregion
#region ComponentValueProperty
/// <summary>
/// ComponentValue property
/// </summary>
/// <value>building component numerical value</value>
public double _ComponentValue;
public double ComponentValue
{
get { return _ComponentValue; }
set
{
_ComponentValue = value;
RaisePropertyChanged("ComponentValue");
OnNodeModified(true);
}
}
#endregion
#region ComponentDescriptionProperty
private string componentDescription;
public string ComponentDescription
{
get { return componentDescription; }
set
{
componentDescription = value;
RaisePropertyChanged("ComponentDescription");
}
}
#endregion
#region ReportEntryProperty
/// <summary>
/// log property
/// </summary>
/// <value>Calculation entries that can be converted into a report.</value>
public string reportEntry;
public string ReportEntry
{
get { return reportEntry; }
set
{
reportEntry = value;
RaisePropertyChanged("ReportEntry");
OnNodeModified(true);
}
}
#endregion
#endregion
#endregion
#region Serialization
/// <summary>
///Saves property values to be retained when opening the node
/// </summary>
protected override void SerializeCore(XmlElement nodeElement, SaveContext context)
{
base.SerializeCore(nodeElement, context);
nodeElement.SetAttribute("ComponentId", ComponentId);
nodeElement.SetAttribute("ComponentOption1", ComponentOption1.ToString());
nodeElement.SetAttribute("ComponentOption2", ComponentOption2.ToString());
nodeElement.SetAttribute("ComponentValue", ComponentValue.ToString());
}
/// <summary>
///Retrieved property values when opening the node
/// </summary>
protected override void DeserializeCore(XmlElement nodeElement, SaveContext context)
{
base.DeserializeCore(nodeElement, context);
var attribComponentId = nodeElement.Attributes["ComponentId"];
if (attribComponentId != null)
{
ComponentId = attribComponentId.Value;
SetComponentDescription();
}
var attribComponentOption1 = nodeElement.Attributes["ComponentOption1"];
var attribComponentOption2 = nodeElement.Attributes["ComponentOption2"];
var attribComponentValue = nodeElement.Attributes["ComponentValue"];
try
{
this.ComponentOption1 = double.Parse(attribComponentOption1.Value);
this.ComponentOption2 = double.Parse(attribComponentOption2.Value);
this.ComponentValue = double.Parse(attribComponentValue.Value);
}
catch (Exception)
{
}
}
public void UpdateSelectionEvents()
{
if (TreeViewControl != null)
{
TreeViewControl.SelectedItemChanged += OnTreeViewSelectionChanged;
}
}
private void OnTreeViewSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
OnSelectedItemChanged(e.NewValue);
}
private void SetComponentDescription()
{
Uri uri = new Uri("pack://application:,,,/KodestructDynamoUI;component/Views/Loads/ASCE7/Dead/ComponentDeadWeightTreeData.xml");
XmlTreeHelper treeHelper = new XmlTreeHelper();
treeHelper.ExamineXmlTreeFile(uri, new EvaluateXmlNodeDelegate(FindDescription));
}
private void FindDescription(XmlNode node)
{
if (null != node.Attributes["Tag"])
{
if (node.Attributes["Tag"].Value== ComponentId)
{
ComponentDescription = node.Attributes["Description"].Value;
}
}
}
#endregion
#region treeView elements
public TreeView TreeViewControl { get; set; }
private ICommand selectedItemChanged;
public ICommand SelectedItemChanged
{
get
{
if (ComponentDescription == null)
{
selectedItemChanged = new RelayCommand<object>((i) =>
{
OnSelectedItemChanged(i);
});
}
return selectedItemChanged;
}
}
public void DisplayComponentUI(XTreeItem selectedComponent)
{
if (selectedComponent != null && selectedComponent.Tag != "X" && selectedComponent.ResourcePath != null)
{
Assembly execAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(execAssembly.FullName);
string execAssemblyName = assemblyName.Name;
string typeStr =execAssemblyName +".Views.Loads.ASCE7." + selectedComponent.ResourcePath;
try
{
Type subMenuType = execAssembly.GetType(typeStr);
UserControl subMenu = (UserControl)Activator.CreateInstance(subMenuType);
AdditionalUI = subMenu;
if (selectedComponent.Id != "X") //parse default values
{
int ind1, ind2;
double numeric;
string DefaultValues = selectedComponent.Id;
string[] Vals = DefaultValues.Split(',');
if (Vals.Length == 3)
{
bool ind1Res = int.TryParse(Vals[0], out ind1); if (ind1Res == true) ComponentOption1 = ind1;
bool ind2Res = int.TryParse(Vals[1], out ind2); if (ind2Res == true) ComponentOption2 = ind2;
bool numRes = double.TryParse(Vals[2], out numeric); if (numRes == true) ComponentValue = numeric;
}
else
{
ComponentOption1 = -1;
ComponentOption2 = -1;
ComponentValue = 0;
}
}
}
catch (Exception)
{
AdditionalUI = null;
}
}
else
{
AdditionalUI = null;
}
}
private XTreeItem selectedItem;
public XTreeItem SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
}
}
private void OnSelectedItemChanged(object i)
{
XmlElement item = i as XmlElement;
XTreeItem xtreeItem = new XTreeItem()
{
Description = item.GetAttribute("Description"),
Header = item.GetAttribute("Header"),
Id = item.GetAttribute("Id"),
ResourcePath = item.GetAttribute("ResourcePath"),
Tag = item.GetAttribute("Tag"),
TemplateName = item.GetAttribute("TemplateName")
};
if (item != null)
{
//string id = item.GetAttribute("Tag");
string id =xtreeItem.Tag;
if (id != "X")
{
ComponentId = id;
//ComponentDescription = item.GetAttribute("Description");
ComponentDescription = xtreeItem.Description;
SelectedItem = xtreeItem;
DisplayComponentUI(xtreeItem);
}
}
}
#endregion
#region Additional UI
private UserControl additionalUI;
public UserControl AdditionalUI
{
get { return additionalUI; }
set
{
additionalUI = value;
RaisePropertyChanged("AdditionalUI");
}
}
#endregion
/// <summary>
///Customization of WPF view in Dynamo UI
/// </summary>
public class ComponentIdViewCustomization : UiNodeBaseViewCustomization,
INodeViewCustomization<ComponentIdSelection>
{
public void CustomizeView(ComponentIdSelection model, NodeView nodeView)
{
ComponentIdView control = new ComponentIdView();
control.DataContext = model;
TreeView tv = control.FindName("selectionTree") as TreeView;
if (tv!=null)
{
model.TreeViewControl = tv;
model.UpdateSelectionEvents();
}
nodeView.inputGrid.Children.Add(control);
base.CustomizeView(model, nodeView);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Xml;
using System.Collections.Generic;
namespace System.ServiceModel
{
// NOTE: This is a dynamic dictionary of XmlDictionaryStrings for the Binary Encoder to dynamically encode should
// the string not exist in the static cache.
// When adding or removing memebers please keep the capacity of the XmlDictionary field current.
internal static class DXD
{
private static AtomicTransactionExternal11Dictionary s_atomicTransactionExternal11Dictionary;
private static CoordinationExternal11Dictionary s_coordinationExternal11Dictionary;
private static SecureConversationDec2005Dictionary s_secureConversationDec2005Dictionary;
private static SecurityAlgorithmDec2005Dictionary s_securityAlgorithmDec2005Dictionary;
private static TrustDec2005Dictionary s_trustDec2005Dictionary;
private static Wsrm11Dictionary s_wsrm11Dictionary;
static DXD()
{
// Each string added to the XmlDictionary will keep a reference to the XmlDictionary so this class does
// not need to keep a reference.
XmlDictionary dictionary = new XmlDictionary(137);
// Each dictionaries' constructor should add strings to the XmlDictionary.
s_atomicTransactionExternal11Dictionary = new AtomicTransactionExternal11Dictionary(dictionary);
s_coordinationExternal11Dictionary = new CoordinationExternal11Dictionary(dictionary);
s_secureConversationDec2005Dictionary = new SecureConversationDec2005Dictionary(dictionary);
s_secureConversationDec2005Dictionary.PopulateSecureConversationDec2005();
s_securityAlgorithmDec2005Dictionary = new SecurityAlgorithmDec2005Dictionary(dictionary);
s_securityAlgorithmDec2005Dictionary.PopulateSecurityAlgorithmDictionaryString();
s_trustDec2005Dictionary = new TrustDec2005Dictionary(dictionary);
s_trustDec2005Dictionary.PopulateDec2005DictionaryStrings();
s_trustDec2005Dictionary.PopulateFeb2005DictionaryString();
s_wsrm11Dictionary = new Wsrm11Dictionary(dictionary);
}
static public AtomicTransactionExternal11Dictionary AtomicTransactionExternal11Dictionary
{
get { return s_atomicTransactionExternal11Dictionary; }
}
static public CoordinationExternal11Dictionary CoordinationExternal11Dictionary
{
get { return s_coordinationExternal11Dictionary; }
}
static public SecureConversationDec2005Dictionary SecureConversationDec2005Dictionary
{
get { return s_secureConversationDec2005Dictionary; }
}
static public SecurityAlgorithmDec2005Dictionary SecurityAlgorithmDec2005Dictionary
{
get { return s_securityAlgorithmDec2005Dictionary; }
}
static public TrustDec2005Dictionary TrustDec2005Dictionary
{
get { return s_trustDec2005Dictionary; }
}
static public Wsrm11Dictionary Wsrm11Dictionary
{
get { return s_wsrm11Dictionary; }
}
}
internal class AtomicTransactionExternal11Dictionary
{
public XmlDictionaryString Namespace;
public XmlDictionaryString CompletionUri;
public XmlDictionaryString Durable2PCUri;
public XmlDictionaryString Volatile2PCUri;
public XmlDictionaryString CommitAction;
public XmlDictionaryString RollbackAction;
public XmlDictionaryString CommittedAction;
public XmlDictionaryString AbortedAction;
public XmlDictionaryString PrepareAction;
public XmlDictionaryString PreparedAction;
public XmlDictionaryString ReadOnlyAction;
public XmlDictionaryString ReplayAction;
public XmlDictionaryString FaultAction;
public XmlDictionaryString UnknownTransaction;
public AtomicTransactionExternal11Dictionary(XmlDictionary dictionary)
{
this.Namespace = dictionary.Add(AtomicTransactionExternal11Strings.Namespace);
this.CompletionUri = dictionary.Add(AtomicTransactionExternal11Strings.CompletionUri);
this.Durable2PCUri = dictionary.Add(AtomicTransactionExternal11Strings.Durable2PCUri);
this.Volatile2PCUri = dictionary.Add(AtomicTransactionExternal11Strings.Volatile2PCUri);
this.CommitAction = dictionary.Add(AtomicTransactionExternal11Strings.CommitAction);
this.RollbackAction = dictionary.Add(AtomicTransactionExternal11Strings.RollbackAction);
this.CommittedAction = dictionary.Add(AtomicTransactionExternal11Strings.CommittedAction);
this.AbortedAction = dictionary.Add(AtomicTransactionExternal11Strings.AbortedAction);
this.PrepareAction = dictionary.Add(AtomicTransactionExternal11Strings.PrepareAction);
this.PreparedAction = dictionary.Add(AtomicTransactionExternal11Strings.PreparedAction);
this.ReadOnlyAction = dictionary.Add(AtomicTransactionExternal11Strings.ReadOnlyAction);
this.ReplayAction = dictionary.Add(AtomicTransactionExternal11Strings.ReplayAction);
this.FaultAction = dictionary.Add(AtomicTransactionExternal11Strings.FaultAction);
this.UnknownTransaction = dictionary.Add(AtomicTransactionExternal11Strings.UnknownTransaction);
}
}
internal class CoordinationExternal11Dictionary
{
public XmlDictionaryString Namespace;
public XmlDictionaryString CreateCoordinationContextAction;
public XmlDictionaryString CreateCoordinationContextResponseAction;
public XmlDictionaryString RegisterAction;
public XmlDictionaryString RegisterResponseAction;
public XmlDictionaryString FaultAction;
public XmlDictionaryString CannotCreateContext;
public XmlDictionaryString CannotRegisterParticipant;
public CoordinationExternal11Dictionary(XmlDictionary dictionary)
{
this.Namespace = dictionary.Add(CoordinationExternal11Strings.Namespace);
this.CreateCoordinationContextAction = dictionary.Add(CoordinationExternal11Strings.CreateCoordinationContextAction);
this.CreateCoordinationContextResponseAction = dictionary.Add(CoordinationExternal11Strings.CreateCoordinationContextResponseAction);
this.RegisterAction = dictionary.Add(CoordinationExternal11Strings.RegisterAction);
this.RegisterResponseAction = dictionary.Add(CoordinationExternal11Strings.RegisterResponseAction);
this.FaultAction = dictionary.Add(CoordinationExternal11Strings.FaultAction);
this.CannotCreateContext = dictionary.Add(CoordinationExternal11Strings.CannotCreateContext);
this.CannotRegisterParticipant = dictionary.Add(CoordinationExternal11Strings.CannotRegisterParticipant);
}
}
internal class SecureConversationDec2005Dictionary : SecureConversationDictionary
{
public XmlDictionaryString RequestSecurityContextRenew;
public XmlDictionaryString RequestSecurityContextRenewResponse;
public XmlDictionaryString RequestSecurityContextClose;
public XmlDictionaryString RequestSecurityContextCloseResponse;
public XmlDictionaryString Instance;
public List<XmlDictionaryString> SecureConversationDictionaryStrings = new List<XmlDictionaryString>();
public SecureConversationDec2005Dictionary(XmlDictionary dictionary)
{
this.SecurityContextToken = dictionary.Add(SecureConversationDec2005Strings.SecurityContextToken);
this.AlgorithmAttribute = dictionary.Add(SecureConversationDec2005Strings.AlgorithmAttribute);
this.Generation = dictionary.Add(SecureConversationDec2005Strings.Generation);
this.Label = dictionary.Add(SecureConversationDec2005Strings.Label);
this.Offset = dictionary.Add(SecureConversationDec2005Strings.Offset);
this.Properties = dictionary.Add(SecureConversationDec2005Strings.Properties);
this.Identifier = dictionary.Add(SecureConversationDec2005Strings.Identifier);
this.Cookie = dictionary.Add(SecureConversationDec2005Strings.Cookie);
this.RenewNeededFaultCode = dictionary.Add(SecureConversationDec2005Strings.RenewNeededFaultCode);
this.BadContextTokenFaultCode = dictionary.Add(SecureConversationDec2005Strings.BadContextTokenFaultCode);
this.Prefix = dictionary.Add(SecureConversationDec2005Strings.Prefix);
this.DerivedKeyTokenType = dictionary.Add(SecureConversationDec2005Strings.DerivedKeyTokenType);
this.SecurityContextTokenType = dictionary.Add(SecureConversationDec2005Strings.SecurityContextTokenType);
this.SecurityContextTokenReferenceValueType = dictionary.Add(SecureConversationDec2005Strings.SecurityContextTokenReferenceValueType);
this.RequestSecurityContextIssuance = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextIssuance);
this.RequestSecurityContextIssuanceResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextIssuanceResponse);
this.RequestSecurityContextRenew = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextRenew);
this.RequestSecurityContextRenewResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextRenewResponse);
this.RequestSecurityContextClose = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextClose);
this.RequestSecurityContextCloseResponse = dictionary.Add(SecureConversationDec2005Strings.RequestSecurityContextCloseResponse);
this.Namespace = dictionary.Add(SecureConversationDec2005Strings.Namespace);
this.DerivedKeyToken = dictionary.Add(SecureConversationDec2005Strings.DerivedKeyToken);
this.Nonce = dictionary.Add(SecureConversationDec2005Strings.Nonce);
this.Length = dictionary.Add(SecureConversationDec2005Strings.Length);
this.Instance = dictionary.Add(SecureConversationDec2005Strings.Instance);
}
public void PopulateSecureConversationDec2005()
{
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextToken);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.AlgorithmAttribute);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Generation);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Label);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Offset);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Properties);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Identifier);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Cookie);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RenewNeededFaultCode);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.BadContextTokenFaultCode);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Prefix);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.DerivedKeyTokenType);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextTokenType);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.SecurityContextTokenReferenceValueType);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextIssuance);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextIssuanceResponse);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextRenew);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextRenewResponse);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextClose);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.RequestSecurityContextCloseResponse);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Namespace);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.DerivedKeyToken);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Nonce);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Length);
SecureConversationDictionaryStrings.Add(DXD.SecureConversationDec2005Dictionary.Instance);
}
}
internal class SecurityAlgorithmDec2005Dictionary
{
public XmlDictionaryString Psha1KeyDerivationDec2005;
public List<XmlDictionaryString> SecurityAlgorithmDictionaryStrings = new List<XmlDictionaryString>();
public SecurityAlgorithmDec2005Dictionary(XmlDictionary dictionary)
{
this.Psha1KeyDerivationDec2005 = dictionary.Add(SecurityAlgorithmDec2005Strings.Psha1KeyDerivationDec2005);
}
public void PopulateSecurityAlgorithmDictionaryString()
{
SecurityAlgorithmDictionaryStrings.Add(DXD.SecurityAlgorithmDec2005Dictionary.Psha1KeyDerivationDec2005);
}
}
internal class TrustDec2005Dictionary : TrustDictionary
{
public XmlDictionaryString AsymmetricKeyBinarySecret;
public XmlDictionaryString RequestSecurityTokenCollectionIssuanceFinalResponse;
public XmlDictionaryString RequestSecurityTokenRenewal;
public XmlDictionaryString RequestSecurityTokenRenewalResponse;
public XmlDictionaryString RequestSecurityTokenCollectionRenewalFinalResponse;
public XmlDictionaryString RequestSecurityTokenCancellation;
public XmlDictionaryString RequestSecurityTokenCancellationResponse;
public XmlDictionaryString RequestSecurityTokenCollectionCancellationFinalResponse;
public XmlDictionaryString KeyWrapAlgorithm;
public XmlDictionaryString BearerKeyType;
public XmlDictionaryString SecondaryParameters;
public XmlDictionaryString Dialect;
public XmlDictionaryString DialectType;
public List<XmlDictionaryString> Feb2005DictionaryStrings = new List<XmlDictionaryString>();
public List<XmlDictionaryString> Dec2005DictionaryString = new List<XmlDictionaryString>();
public TrustDec2005Dictionary(XmlDictionary dictionary)
{
this.CombinedHashLabel = dictionary.Add(TrustDec2005Strings.CombinedHashLabel);
this.RequestSecurityTokenResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenResponse);
this.TokenType = dictionary.Add(TrustDec2005Strings.TokenType);
this.KeySize = dictionary.Add(TrustDec2005Strings.KeySize);
this.RequestedTokenReference = dictionary.Add(TrustDec2005Strings.RequestedTokenReference);
this.AppliesTo = dictionary.Add(TrustDec2005Strings.AppliesTo);
this.Authenticator = dictionary.Add(TrustDec2005Strings.Authenticator);
this.CombinedHash = dictionary.Add(TrustDec2005Strings.CombinedHash);
this.BinaryExchange = dictionary.Add(TrustDec2005Strings.BinaryExchange);
this.Lifetime = dictionary.Add(TrustDec2005Strings.Lifetime);
this.RequestedSecurityToken = dictionary.Add(TrustDec2005Strings.RequestedSecurityToken);
this.Entropy = dictionary.Add(TrustDec2005Strings.Entropy);
this.RequestedProofToken = dictionary.Add(TrustDec2005Strings.RequestedProofToken);
this.ComputedKey = dictionary.Add(TrustDec2005Strings.ComputedKey);
this.RequestSecurityToken = dictionary.Add(TrustDec2005Strings.RequestSecurityToken);
this.RequestType = dictionary.Add(TrustDec2005Strings.RequestType);
this.Context = dictionary.Add(TrustDec2005Strings.Context);
this.BinarySecret = dictionary.Add(TrustDec2005Strings.BinarySecret);
this.Type = dictionary.Add(TrustDec2005Strings.Type);
this.SpnegoValueTypeUri = dictionary.Add(TrustDec2005Strings.SpnegoValueTypeUri);
this.TlsnegoValueTypeUri = dictionary.Add(TrustDec2005Strings.TlsnegoValueTypeUri);
this.Prefix = dictionary.Add(TrustDec2005Strings.Prefix);
this.RequestSecurityTokenIssuance = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenIssuance);
this.RequestSecurityTokenIssuanceResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenIssuanceResponse);
this.RequestTypeIssue = dictionary.Add(TrustDec2005Strings.RequestTypeIssue);
this.AsymmetricKeyBinarySecret = dictionary.Add(TrustDec2005Strings.AsymmetricKeyBinarySecret);
this.SymmetricKeyBinarySecret = dictionary.Add(TrustDec2005Strings.SymmetricKeyBinarySecret);
this.NonceBinarySecret = dictionary.Add(TrustDec2005Strings.NonceBinarySecret);
this.Psha1ComputedKeyUri = dictionary.Add(TrustDec2005Strings.Psha1ComputedKeyUri);
this.KeyType = dictionary.Add(TrustDec2005Strings.KeyType);
this.SymmetricKeyType = dictionary.Add(TrustDec2005Strings.SymmetricKeyType);
this.PublicKeyType = dictionary.Add(TrustDec2005Strings.PublicKeyType);
this.Claims = dictionary.Add(TrustDec2005Strings.Claims);
this.InvalidRequestFaultCode = dictionary.Add(TrustDec2005Strings.InvalidRequestFaultCode);
this.FailedAuthenticationFaultCode = dictionary.Add(TrustDec2005Strings.FailedAuthenticationFaultCode);
this.UseKey = dictionary.Add(TrustDec2005Strings.UseKey);
this.SignWith = dictionary.Add(TrustDec2005Strings.SignWith);
this.EncryptWith = dictionary.Add(TrustDec2005Strings.EncryptWith);
this.EncryptionAlgorithm = dictionary.Add(TrustDec2005Strings.EncryptionAlgorithm);
this.CanonicalizationAlgorithm = dictionary.Add(TrustDec2005Strings.CanonicalizationAlgorithm);
this.ComputedKeyAlgorithm = dictionary.Add(TrustDec2005Strings.ComputedKeyAlgorithm);
this.RequestSecurityTokenResponseCollection = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenResponseCollection);
this.Namespace = dictionary.Add(TrustDec2005Strings.Namespace);
this.BinarySecretClauseType = dictionary.Add(TrustDec2005Strings.BinarySecretClauseType);
this.RequestSecurityTokenCollectionIssuanceFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionIssuanceFinalResponse);
this.RequestSecurityTokenRenewal = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenRenewal);
this.RequestSecurityTokenRenewalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenRenewalResponse);
this.RequestSecurityTokenCollectionRenewalFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionRenewalFinalResponse);
this.RequestSecurityTokenCancellation = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCancellation);
this.RequestSecurityTokenCancellationResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCancellationResponse);
this.RequestSecurityTokenCollectionCancellationFinalResponse = dictionary.Add(TrustDec2005Strings.RequestSecurityTokenCollectionCancellationFinalResponse);
this.RequestTypeRenew = dictionary.Add(TrustDec2005Strings.RequestTypeRenew);
this.RequestTypeClose = dictionary.Add(TrustDec2005Strings.RequestTypeClose);
this.RenewTarget = dictionary.Add(TrustDec2005Strings.RenewTarget);
this.CloseTarget = dictionary.Add(TrustDec2005Strings.CloseTarget);
this.RequestedTokenClosed = dictionary.Add(TrustDec2005Strings.RequestedTokenClosed);
this.RequestedAttachedReference = dictionary.Add(TrustDec2005Strings.RequestedAttachedReference);
this.RequestedUnattachedReference = dictionary.Add(TrustDec2005Strings.RequestedUnattachedReference);
this.IssuedTokensHeader = dictionary.Add(TrustDec2005Strings.IssuedTokensHeader);
this.KeyWrapAlgorithm = dictionary.Add(TrustDec2005Strings.KeyWrapAlgorithm);
this.BearerKeyType = dictionary.Add(TrustDec2005Strings.BearerKeyType);
this.SecondaryParameters = dictionary.Add(TrustDec2005Strings.SecondaryParameters);
this.Dialect = dictionary.Add(TrustDec2005Strings.Dialect);
this.DialectType = dictionary.Add(TrustDec2005Strings.DialectType);
}
public void PopulateFeb2005DictionaryString()
{
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenResponseCollection);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Namespace);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinarySecretClauseType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CombinedHashLabel);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenResponse);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.TokenType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.KeySize);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedTokenReference);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.AppliesTo);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Authenticator);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CombinedHash);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinaryExchange);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Lifetime);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedSecurityToken);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Entropy);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedProofToken);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.ComputedKey);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityToken);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Context);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.BinarySecret);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Type);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SpnegoValueTypeUri);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.TlsnegoValueTypeUri);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Prefix);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenIssuance);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestSecurityTokenIssuanceResponse);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeIssue);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SymmetricKeyBinarySecret);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Psha1ComputedKeyUri);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.NonceBinarySecret);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RenewTarget);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CloseTarget);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedTokenClosed);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedAttachedReference);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestedUnattachedReference);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.IssuedTokensHeader);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeRenew);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.RequestTypeClose);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.KeyType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SymmetricKeyType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.PublicKeyType);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.Claims);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.InvalidRequestFaultCode);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.FailedAuthenticationFaultCode);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.UseKey);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.SignWith);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.EncryptWith);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.EncryptionAlgorithm);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.CanonicalizationAlgorithm);
Feb2005DictionaryStrings.Add(XD.TrustFeb2005Dictionary.ComputedKeyAlgorithm);
}
public void PopulateDec2005DictionaryStrings()
{
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CombinedHashLabel);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.TokenType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeySize);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedTokenReference);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.AppliesTo);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Authenticator);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CombinedHash);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinaryExchange);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Lifetime);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedSecurityToken);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Entropy);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedProofToken);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.ComputedKey);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityToken);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Context);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinarySecret);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Type);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SpnegoValueTypeUri);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.TlsnegoValueTypeUri);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Prefix);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenIssuance);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenIssuanceResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeIssue);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.AsymmetricKeyBinarySecret);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SymmetricKeyBinarySecret);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.NonceBinarySecret);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Psha1ComputedKeyUri);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeyType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SymmetricKeyType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.PublicKeyType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Claims);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.InvalidRequestFaultCode);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.FailedAuthenticationFaultCode);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.UseKey);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SignWith);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.EncryptWith);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.EncryptionAlgorithm);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CanonicalizationAlgorithm);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.ComputedKeyAlgorithm);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenResponseCollection);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Namespace);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BinarySecretClauseType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionIssuanceFinalResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenRenewal);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenRenewalResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionRenewalFinalResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCancellation);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCancellationResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestSecurityTokenCollectionCancellationFinalResponse);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeRenew);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestTypeClose);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RenewTarget);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.CloseTarget);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedTokenClosed);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedAttachedReference);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.RequestedUnattachedReference);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.IssuedTokensHeader);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.KeyWrapAlgorithm);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.BearerKeyType);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.SecondaryParameters);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.Dialect);
Dec2005DictionaryString.Add(DXD.TrustDec2005Dictionary.DialectType);
}
}
internal class Wsrm11Dictionary
{
public XmlDictionaryString AckRequestedAction;
public XmlDictionaryString CloseSequence;
public XmlDictionaryString CloseSequenceAction;
public XmlDictionaryString CloseSequenceResponse;
public XmlDictionaryString CloseSequenceResponseAction;
public XmlDictionaryString CreateSequenceAction;
public XmlDictionaryString CreateSequenceResponseAction;
public XmlDictionaryString DiscardFollowingFirstGap;
public XmlDictionaryString Endpoint;
public XmlDictionaryString FaultAction;
public XmlDictionaryString Final;
public XmlDictionaryString IncompleteSequenceBehavior;
public XmlDictionaryString LastMsgNumber;
public XmlDictionaryString MaxMessageNumber;
public XmlDictionaryString Namespace;
public XmlDictionaryString NoDiscard;
public XmlDictionaryString None;
public XmlDictionaryString SequenceAcknowledgementAction;
public XmlDictionaryString SequenceClosed;
public XmlDictionaryString TerminateSequenceAction;
public XmlDictionaryString TerminateSequenceResponse;
public XmlDictionaryString TerminateSequenceResponseAction;
public XmlDictionaryString UsesSequenceSSL;
public XmlDictionaryString UsesSequenceSTR;
public XmlDictionaryString WsrmRequired;
public Wsrm11Dictionary(XmlDictionary dictionary)
{
this.AckRequestedAction = dictionary.Add(Wsrm11Strings.AckRequestedAction);
this.CloseSequence = dictionary.Add(Wsrm11Strings.CloseSequence);
this.CloseSequenceAction = dictionary.Add(Wsrm11Strings.CloseSequenceAction);
this.CloseSequenceResponse = dictionary.Add(Wsrm11Strings.CloseSequenceResponse);
this.CloseSequenceResponseAction = dictionary.Add(Wsrm11Strings.CloseSequenceResponseAction);
this.CreateSequenceAction = dictionary.Add(Wsrm11Strings.CreateSequenceAction);
this.CreateSequenceResponseAction = dictionary.Add(Wsrm11Strings.CreateSequenceResponseAction);
this.DiscardFollowingFirstGap = dictionary.Add(Wsrm11Strings.DiscardFollowingFirstGap);
this.Endpoint = dictionary.Add(Wsrm11Strings.Endpoint);
this.FaultAction = dictionary.Add(Wsrm11Strings.FaultAction);
this.Final = dictionary.Add(Wsrm11Strings.Final);
this.IncompleteSequenceBehavior = dictionary.Add(Wsrm11Strings.IncompleteSequenceBehavior);
this.LastMsgNumber = dictionary.Add(Wsrm11Strings.LastMsgNumber);
this.MaxMessageNumber = dictionary.Add(Wsrm11Strings.MaxMessageNumber);
this.Namespace = dictionary.Add(Wsrm11Strings.Namespace);
this.NoDiscard = dictionary.Add(Wsrm11Strings.NoDiscard);
this.None = dictionary.Add(Wsrm11Strings.None);
this.SequenceAcknowledgementAction = dictionary.Add(Wsrm11Strings.SequenceAcknowledgementAction);
this.SequenceClosed = dictionary.Add(Wsrm11Strings.SequenceClosed);
this.TerminateSequenceAction = dictionary.Add(Wsrm11Strings.TerminateSequenceAction);
this.TerminateSequenceResponse = dictionary.Add(Wsrm11Strings.TerminateSequenceResponse);
this.TerminateSequenceResponseAction = dictionary.Add(Wsrm11Strings.TerminateSequenceResponseAction);
this.UsesSequenceSSL = dictionary.Add(Wsrm11Strings.UsesSequenceSSL);
this.UsesSequenceSTR = dictionary.Add(Wsrm11Strings.UsesSequenceSTR);
this.WsrmRequired = dictionary.Add(Wsrm11Strings.WsrmRequired);
}
}
internal static class AtomicTransactionExternal11Strings
{
// dictionary strings
public const string Namespace = "http://docs.oasis-open.org/ws-tx/wsat/2006/06";
public const string CompletionUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Completion";
public const string Durable2PCUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Durable2PC";
public const string Volatile2PCUri = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Volatile2PC";
public const string CommitAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Commit";
public const string RollbackAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Rollback";
public const string CommittedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Committed";
public const string AbortedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Aborted";
public const string PrepareAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Prepare";
public const string PreparedAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Prepared";
public const string ReadOnlyAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/ReadOnly";
public const string ReplayAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/Replay";
public const string FaultAction = "http://docs.oasis-open.org/ws-tx/wsat/2006/06/fault";
public const string UnknownTransaction = "UnknownTransaction";
}
internal static class CoordinationExternal11Strings
{
// dictionary strings
public const string Namespace = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06";
public const string CreateCoordinationContextAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/CreateCoordinationContext";
public const string CreateCoordinationContextResponseAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/CreateCoordinationContextResponse";
public const string RegisterAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/Register";
public const string RegisterResponseAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/RegisterResponse";
public const string FaultAction = "http://docs.oasis-open.org/ws-tx/wscoor/2006/06/fault";
public const string CannotCreateContext = "CannotCreateContext";
public const string CannotRegisterParticipant = "CannotRegisterParticipant";
}
internal static class SecureConversationDec2005Strings
{
// dictionary strings
public const string SecurityContextToken = "SecurityContextToken";
public const string AlgorithmAttribute = "Algorithm";
public const string Generation = "Generation";
public const string Label = "Label";
public const string Offset = "Offset";
public const string Properties = "Properties";
public const string Identifier = "Identifier";
public const string Cookie = "Cookie";
public const string RenewNeededFaultCode = "RenewNeeded";
public const string BadContextTokenFaultCode = "BadContextToken";
public const string Prefix = "sc";
public const string DerivedKeyTokenType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk";
public const string SecurityContextTokenType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct";
public const string SecurityContextTokenReferenceValueType = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct";
public const string RequestSecurityContextIssuance = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT";
public const string RequestSecurityContextIssuanceResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT";
public const string RequestSecurityContextRenew = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Renew";
public const string RequestSecurityContextRenewResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Renew";
public const string RequestSecurityContextClose = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Cancel";
public const string RequestSecurityContextCloseResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Cancel";
public const string Namespace = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512";
public const string DerivedKeyToken = "DerivedKeyToken";
public const string Nonce = "Nonce";
public const string Length = "Length";
public const string Instance = "Instance";
}
internal static class SecurityAlgorithmDec2005Strings
{
// dictionary strings
public const string Psha1KeyDerivationDec2005 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk/p_sha1";
}
internal static class TrustDec2005Strings
{
// dictionary strings
public const string CombinedHashLabel = "AUTH-HASH";
public const string RequestSecurityTokenResponse = "RequestSecurityTokenResponse";
public const string TokenType = "TokenType";
public const string KeySize = "KeySize";
public const string RequestedTokenReference = "RequestedTokenReference";
public const string AppliesTo = "AppliesTo";
public const string Authenticator = "Authenticator";
public const string CombinedHash = "CombinedHash";
public const string BinaryExchange = "BinaryExchange";
public const string Lifetime = "Lifetime";
public const string RequestedSecurityToken = "RequestedSecurityToken";
public const string Entropy = "Entropy";
public const string RequestedProofToken = "RequestedProofToken";
public const string ComputedKey = "ComputedKey";
public const string RequestSecurityToken = "RequestSecurityToken";
public const string RequestType = "RequestType";
public const string Context = "Context";
public const string BinarySecret = "BinarySecret";
public const string Type = "Type";
public const string SpnegoValueTypeUri = "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego";
public const string TlsnegoValueTypeUri = "http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego";
public const string Prefix = "trust";
public const string RequestSecurityTokenIssuance = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue";
public const string RequestSecurityTokenIssuanceResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Issue";
public const string RequestTypeIssue = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";
public const string AsymmetricKeyBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/AsymmetricKey";
public const string SymmetricKeyBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey";
public const string NonceBinarySecret = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Nonce";
public const string Psha1ComputedKeyUri = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/CK/PSHA1";
public const string KeyType = "KeyType";
public const string SymmetricKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey";
public const string PublicKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
public const string Claims = "Claims";
public const string InvalidRequestFaultCode = "InvalidRequest";
public const string FailedAuthenticationFaultCode = "FailedAuthentication";
public const string UseKey = "UseKey";
public const string SignWith = "SignWith";
public const string EncryptWith = "EncryptWith";
public const string EncryptionAlgorithm = "EncryptionAlgorithm";
public const string CanonicalizationAlgorithm = "CanonicalizationAlgorithm";
public const string ComputedKeyAlgorithm = "ComputedKeyAlgorithm";
public const string RequestSecurityTokenResponseCollection = "RequestSecurityTokenResponseCollection";
public const string Namespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512";
public const string BinarySecretClauseType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512#BinarySecret";
public const string RequestSecurityTokenCollectionIssuanceFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTRC/IssueFinal";
public const string RequestSecurityTokenRenewal = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Renew";
public const string RequestSecurityTokenRenewalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Renew";
public const string RequestSecurityTokenCollectionRenewalFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/RenewFinal";
public const string RequestSecurityTokenCancellation = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Cancel";
public const string RequestSecurityTokenCancellationResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Cancel";
public const string RequestSecurityTokenCollectionCancellationFinalResponse = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/CancelFinal";
public const string RequestTypeRenew = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew";
public const string RequestTypeClose = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel";
public const string RenewTarget = "RenewTarget";
public const string CloseTarget = "CancelTarget";
public const string RequestedTokenClosed = "RequestedTokenCancelled";
public const string RequestedAttachedReference = "RequestedAttachedReference";
public const string RequestedUnattachedReference = "RequestedUnattachedReference";
public const string IssuedTokensHeader = "IssuedTokens";
public const string KeyWrapAlgorithm = "KeyWrapAlgorithm";
public const string BearerKeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
public const string SecondaryParameters = "SecondaryParameters";
public const string Dialect = "Dialect";
public const string DialectType = "http://schemas.xmlsoap.org/ws/2005/05/identity";
}
internal static class Wsrm11Strings
{
// dictionary strings
public const string AckRequestedAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/AckRequested";
public const string CloseSequence = "CloseSequence";
public const string CloseSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequence";
public const string CloseSequenceResponse = "CloseSequenceResponse";
public const string CloseSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequenceResponse";
public const string CreateSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CreateSequence";
public const string CreateSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/CreateSequenceResponse";
public const string DiscardFollowingFirstGap = "DiscardFollowingFirstGap";
public const string Endpoint = "Endpoint";
public const string FaultAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/fault";
public const string Final = "Final";
public const string IncompleteSequenceBehavior = "IncompleteSequenceBehavior";
public const string LastMsgNumber = "LastMsgNumber";
public const string MaxMessageNumber = "MaxMessageNumber";
public const string Namespace = "http://docs.oasis-open.org/ws-rx/wsrm/200702";
public const string NoDiscard = "NoDiscard";
public const string None = "None";
public const string SequenceAcknowledgementAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/SequenceAcknowledgement";
public const string SequenceClosed = "SequenceClosed";
public const string TerminateSequenceAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/TerminateSequence";
public const string TerminateSequenceResponse = "TerminateSequenceResponse";
public const string TerminateSequenceResponseAction = "http://docs.oasis-open.org/ws-rx/wsrm/200702/TerminateSequenceResponse";
public const string UsesSequenceSSL = "UsesSequenceSSL";
public const string UsesSequenceSTR = "UsesSequenceSTR";
public const string WsrmRequired = "WsrmRequired";
// string constants
public const string DiscardEntireSequence = "DiscardEntireSequence";
}
}
| |
//
// Server.cs: Accepts connections.
//
// Author:
// Brian Nickel (brian.nickel@gmail.com)
//
// Copyright (C) 2007 Brian Nickel
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Mono.WebServer.FastCgi;
using Mono.WebServer.Log;
namespace Mono.FastCgi {
public class Server
{
public BufferManager BigBufferManager { get; private set; }
public BufferManager SmallBufferManager { get; private set; }
#region Private Fields
readonly IGenericServer<ConnectionProxy> backend;
int max_requests = Int32.MaxValue;
Type responder_type;
#endregion
#region Constructors
public Server (Socket socket)
{
if (socket == null)
throw new ArgumentNullException ("socket");
BigBufferManager = new BufferManager (4 * 1024); //4k
SmallBufferManager = new BufferManager (8);
backend = new GenericServer<ConnectionProxy> (socket, new ServerProxy (this));
backend.RequestReceived += RequestReceived;
}
public Server (IGenericServer<ConnectionProxy> backend)
{
if (backend == null)
throw new ArgumentNullException ("backend");
BigBufferManager = new BufferManager (4 * 1024); //4k
SmallBufferManager = new BufferManager (8);
this.backend = backend;
backend.RequestReceived += RequestReceived;
}
#endregion
#region Public Properties
public event EventHandler RequestReceived;
public int MaxConnections {
get { return backend.MaxConnections; }
set { backend.MaxConnections = value; }
}
public int MaxRequests {
get {return max_requests;}
set {
if (value < 1)
throw new ArgumentOutOfRangeException (
"value",
Strings.Server_MaxReqsOutOfRange);
max_requests = value;
}
}
public bool MultiplexConnections { get; set; }
public bool CanAccept {
get {return backend.CanAccept; }
}
public bool CanRequest {
get {return backend.Started && RequestCount < max_requests;}
}
public int ConnectionCount {
get {
return backend.ConnectionCount;
}
}
public int RequestCount {
get {
return backend.Connections.Sum(c => c.RequestCount);
}
}
#endregion
#region Public Methods
internal ConnectionProxy OnAccept (Socket socket)
{
return new ConnectionProxy (new Connection (socket, this));
}
[Obsolete]
public void Start (bool background)
{
Start (background, 500);
}
public void Start (bool background, int backlog)
{
backend.Start (background, backlog);
}
/// <summary>
/// Stop this instance. Calling Stop multiple times is a no-op.
/// </summary>
public void Stop ()
{
backend.Stop ();
}
public void EndConnection (Connection connection)
{
backend.EndConnection (new ConnectionProxy (connection));
}
public IDictionary<string,string> GetValues (IEnumerable<string> names)
{
if (names == null)
throw new ArgumentNullException ("names");
var pairs = new Dictionary<string,string> ();
foreach (string name in names) {
// We can't handle null values and we don't need
// to store the same value twice.
if (name == null || pairs.ContainsKey (name))
continue;
string value = null;
switch (name)
{
case "FCGI_MAX_CONNS":
value = backend.MaxConnections.ToString (CultureInfo.InvariantCulture);
break;
case "FCGI_MAX_REQS":
value = max_requests.ToString (
CultureInfo.InvariantCulture);
break;
case "FCGI_MPXS_CONNS":
value = MultiplexConnections ? "1" : "0";
break;
}
if (value == null) {
Logger.Write (LogLevel.Warning,
Strings.Server_ValueUnknown,
name);
continue;
}
pairs.Add (name, value);
}
return pairs;
}
[Obsolete("Use BigBufferManager or SmallBufferManager instead.")]
public void AllocateBuffers (out byte [] buffer1,
out byte [] buffer2)
{
buffer1 = new byte[Record.SuggestedBufferSize];
buffer2 = new byte[Record.SuggestedBufferSize];
}
[Obsolete("Use BigBufferManager or SmallBufferManager instead.")]
public void ReleaseBuffers (byte [] buffer1, byte [] buffer2)
{
}
#endregion
#region Responder Management
public void SetResponder (Type responder)
{
if (responder == null)
throw new ArgumentNullException ("responder");
if (!typeof (IResponder).IsAssignableFrom (responder))
throw new ArgumentException (
Strings.Server_ResponderDoesNotImplement,
"responder");
// Checks that the correct constructor is available.
if (responder.GetConstructor (new[]
{typeof (ResponderRequest)}) == null) {
string msg = String.Format (
CultureInfo.CurrentCulture,
Strings.Server_ResponderLacksProperConstructor,
responder);
throw new ArgumentException (msg, "responder");
}
responder_type = responder;
}
public IResponder CreateResponder (ResponderRequest request)
{
if (!SupportsResponder)
throw new InvalidOperationException (
Strings.Server_ResponderNotSupported);
return (IResponder) Activator.CreateInstance
(responder_type, new object [] {request});
}
public bool SupportsResponder {
get {return responder_type != null;}
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
namespace Umbraco.Core
{
/// <summary>
/// Provides extension methods to <see cref="Uri"/>.
/// </summary>
public static class UriExtensions
{
/// <summary>
/// Checks if the current uri is a back office request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsBackOfficeRequest(this Uri url)
{
var authority = url.GetLeftPart(UriPartial.Authority);
var afterAuthority = url.GetLeftPart(UriPartial.Query)
.TrimStart(authority)
.TrimStart("/");
//check if this is in the umbraco back office
return afterAuthority.InvariantStartsWith(GlobalSettings.Path.TrimStart("/"));
}
/// <summary>
/// Checks if the current uri is an install request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsInstallerRequest(this Uri url)
{
var authority = url.GetLeftPart(UriPartial.Authority);
var afterAuthority = url.GetLeftPart(UriPartial.Query)
.TrimStart(authority)
.TrimStart("/");
//check if this is in the umbraco back office
return afterAuthority.InvariantStartsWith(IOHelper.ResolveUrl("~/install").TrimStart("/"));
}
/// <summary>
/// This is a performance tweak to check if this is a .css, .js or .ico, .jpg, .jpeg, .png, .gif file request since
/// .Net will pass these requests through to the module when in integrated mode.
/// We want to ignore all of these requests immediately.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
internal static bool IsClientSideRequest(this Uri url)
{
// fixme - but really, is this OK? we should accept either no url, or .aspx, and everything else is out
var toIgnore = new[] { ".js", ".css", ".ico", ".png", ".jpg", ".jpeg", ".gif", ".html", ".svg" };
return toIgnore.Any(x => Path.GetExtension(url.LocalPath).InvariantEquals(x));
}
/// <summary>
/// Rewrites the path of uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <param name="path">The new path, which must begin with a slash.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged, except for the fragment which is removed.</remarks>
public static Uri Rewrite(this Uri uri, string path)
{
if (path.StartsWith("/") == false)
throw new ArgumentException("Path must start with a slash.", "path");
return uri.IsAbsoluteUri
? new Uri(uri.GetLeftPart(UriPartial.Authority) + path + uri.Query)
: new Uri(path + uri.GetSafeQuery(), UriKind.Relative);
}
/// <summary>
/// Rewrites the path and query of a uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <param name="path">The new path, which must begin with a slash.</param>
/// <param name="query">The new query, which must be empty or begin with a question mark.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged, except for the fragment which is removed.</remarks>
public static Uri Rewrite(this Uri uri, string path, string query)
{
if (path.StartsWith("/") == false)
throw new ArgumentException("Path must start with a slash.", "path");
if (query.Length > 0 && query.StartsWith("?") == false)
throw new ArgumentException("Query must start with a question mark.", "query");
if (query == "?")
query = "";
return uri.IsAbsoluteUri
? new Uri(uri.GetLeftPart(UriPartial.Authority) + path + query)
: new Uri(path + query, UriKind.Relative);
}
/// <summary>
/// Gets the absolute path of the uri, even if the uri is relative.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Default uri.AbsolutePath does not support relative uris.</remarks>
public static string GetSafeAbsolutePath(this Uri uri)
{
if (uri.IsAbsoluteUri)
return uri.AbsolutePath;
// cannot get .AbsolutePath on relative uri (InvalidOperation)
var s = uri.OriginalString;
var posq = s.IndexOf("?", StringComparison.Ordinal);
var posf = s.IndexOf("#", StringComparison.Ordinal);
var pos = posq > 0 ? posq : (posf > 0 ? posf : 0);
var path = pos > 0 ? s.Substring(0, pos) : s;
return path;
}
/// <summary>
/// Gets the decoded, absolute path of the uri.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Only for absolute uris.</remarks>
public static string GetAbsolutePathDecoded(this Uri uri)
{
return System.Web.HttpUtility.UrlDecode(uri.AbsolutePath);
}
/// <summary>
/// Gets the decoded, absolute path of the uri, even if the uri is relative.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The absolute path of the uri.</returns>
/// <remarks>Default uri.AbsolutePath does not support relative uris.</remarks>
public static string GetSafeAbsolutePathDecoded(this Uri uri)
{
return System.Web.HttpUtility.UrlDecode(uri.GetSafeAbsolutePath());
}
/// <summary>
/// Rewrites the path of the uri so it ends with a slash.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged.</remarks>
public static Uri EndPathWithSlash(this Uri uri)
{
var path = uri.GetSafeAbsolutePath();
if (uri.IsAbsoluteUri)
{
if (path != "/" && path.EndsWith("/") == false)
uri = new Uri(uri.GetLeftPart(UriPartial.Authority) + path + "/" + uri.Query);
return uri;
}
if (path != "/" && path.EndsWith("/") == false)
uri = new Uri(path + "/" + uri.Query, UriKind.Relative);
return uri;
}
/// <summary>
/// Rewrites the path of the uri so it does not end with a slash.
/// </summary>
/// <param name="uri">The uri.</param>
/// <returns>The rewritten uri.</returns>
/// <remarks>Everything else remains unchanged.</remarks>
public static Uri TrimPathEndSlash(this Uri uri)
{
var path = uri.GetSafeAbsolutePath();
if (uri.IsAbsoluteUri)
{
if (path != "/")
uri = new Uri(uri.GetLeftPart(UriPartial.Authority) + path.TrimEnd('/') + uri.Query);
}
else
{
if (path != "/")
uri = new Uri(path.TrimEnd('/') + uri.Query, UriKind.Relative);
}
return uri;
}
/// <summary>
/// Transforms a relative uri into an absolute uri.
/// </summary>
/// <param name="uri">The relative uri.</param>
/// <param name="baseUri">The base absolute uri.</param>
/// <returns>The absolute uri.</returns>
public static Uri MakeAbsolute(this Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri)
throw new ArgumentException("Uri is already absolute.", "uri");
return new Uri(baseUri.GetLeftPart(UriPartial.Authority) + uri.GetSafeAbsolutePath() + uri.GetSafeQuery());
}
static string GetSafeQuery(this Uri uri)
{
if (uri.IsAbsoluteUri)
return uri.Query;
// cannot get .Query on relative uri (InvalidOperation)
var s = uri.OriginalString;
var posq = s.IndexOf("?", StringComparison.Ordinal);
var posf = s.IndexOf("#", StringComparison.Ordinal);
var query = posq < 0 ? null : (posf < 0 ? s.Substring(posq) : s.Substring(posq, posf - posq));
return query;
}
}
}
| |
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 WebApiAuthSample.Areas.HelpPage.ModelDescriptions;
using WebApiAuthSample.Areas.HelpPage.Models;
namespace WebApiAuthSample.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);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
namespace System.Collections.Specialized.Tests
{
public class GetKeysTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
const int BIG_LENGTH = 100;
HybridDictionary hd;
// simple string values
string[] valuesShort =
{
"",
" ",
"$%^#",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keysShort =
{
Int32.MaxValue.ToString(),
" ",
System.DateTime.Today.ToString(),
"",
"$%^#"
};
string[] valuesLong = new string[BIG_LENGTH];
string[] keysLong = new string[BIG_LENGTH];
Array arr;
ICollection ks; // Keys collection
int ind;
for (int i = 0; i < BIG_LENGTH; i++)
{
valuesLong[i] = "Item" + i;
keysLong[i] = "keY" + i;
}
// [] HybridDictionary is constructed as expected
//-----------------------------------------------------------------
hd = new HybridDictionary();
// [] on empty dictionary
//
if (hd.Count > 0)
hd.Clear();
if (hd.Keys.Count != 0)
{
Assert.False(true, string.Format("Error, returned Keys.Count = {0}", hd.Keys.Count));
}
// [] on short filled dictionary
//
int len = valuesShort.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
ks = hd.Keys;
if (ks.Count != len)
{
Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
}
arr = Array.CreateInstance(typeof(Object), len);
ks.CopyTo(arr, 0);
for (int i = 0; i < len; i++)
{
ind = Array.IndexOf(arr, keysShort[i]);
if (ind < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key. Search result: {2}", i, keysShort[i], ind));
}
}
// [] on long filled dictionary
//
len = valuesLong.Length;
hd.Clear();
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
ks = hd.Keys;
if (ks.Count != len)
{
Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
}
arr = Array.CreateInstance(typeof(Object), len);
ks.CopyTo(arr, 0);
for (int i = 0; i < len; i++)
{
ind = Array.IndexOf(arr, keysLong[i]);
if (ind < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key. Search result: {2}", i, keysLong[i], ind));
}
}
//
// [] get Keys on dictionary with different_in_casing_only keys - list
//
hd.Clear();
string intlStr = "intlStr";
hd.Add("keykey", intlStr); // 1st key
hd.Add("keyKey", intlStr); // 2nd key
if (hd.Count != 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, 2));
}
// get Keys
//
ks = hd.Keys;
if (ks.Count != hd.Count)
{
Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
}
arr = Array.CreateInstance(typeof(Object), 2);
ks.CopyTo(arr, 0);
ind = Array.IndexOf(arr, "keykey");
if (ind < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain {0} value", "keykey"));
}
ind = Array.IndexOf(arr, "keyKey");
if (ind < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain {0} value", "keyKey"));
}
//
// [] get Keys on dictionary with different_in_casing_only keys - hashtable
//
hd.Clear();
hd.Add("keykey", intlStr); // 1st key
for (int i = 0; i < BIG_LENGTH; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
hd.Add("keyKey", intlStr); // 2nd key
if (hd.Count != BIG_LENGTH + 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, BIG_LENGTH + 2));
}
// get Keys
//
ks = hd.Keys;
if (ks.Count != hd.Count)
{
Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
}
arr = Array.CreateInstance(typeof(Object), BIG_LENGTH + 2);
ks.CopyTo(arr, 0);
for (int i = 0; i < BIG_LENGTH; i++)
{
if (Array.IndexOf(arr, keysLong[i]) < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain {0} key", keysLong[i], i));
}
}
ind = Array.IndexOf(arr, "keykey");
if (ind < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain {0} key", "keykey"));
}
ind = Array.IndexOf(arr, "keyKey");
if (ind < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain {0} key", "keyKey"));
}
//
// Change dictionary
// [] change long dictionary and check Keys
hd.Clear();
len = valuesLong.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysLong[i], valuesLong[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
ks = hd.Keys;
if (ks.Count != len)
{
Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
}
hd.Remove(keysLong[0]);
if (hd.Count != len - 1)
{
Assert.False(true, string.Format("Error, didn't remove element"));
}
if (ks.Count != len - 1)
{
Assert.False(true, string.Format("Error, Keys were not updated after removal"));
}
arr = Array.CreateInstance(typeof(Object), hd.Count);
ks.CopyTo(arr, 0);
ind = Array.IndexOf(arr, keysLong[0]);
if (ind >= 0)
{
Assert.False(true, string.Format("Error, Keys still contains removed value " + ind));
}
hd.Add(keysLong[0], "new item");
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, didn't add element"));
}
if (ks.Count != len)
{
Assert.False(true, string.Format("Error, Keys were not updated after addition"));
}
arr = Array.CreateInstance(typeof(Object), hd.Count);
ks.CopyTo(arr, 0);
ind = Array.IndexOf(arr, keysLong[0]);
if (ind < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain added value "));
}
//
// [] change short dictionary and check Keys
//
hd.Clear();
len = valuesShort.Length;
for (int i = 0; i < len; i++)
{
hd.Add(keysShort[i], valuesShort[i]);
}
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", hd.Count, len));
}
ks = hd.Keys;
if (ks.Count != len)
{
Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count));
}
hd.Remove(keysShort[0]);
if (hd.Count != len - 1)
{
Assert.False(true, string.Format("Error, didn't remove element"));
}
if (ks.Count != len - 1)
{
Assert.False(true, string.Format("Error, Keys were not updated after removal"));
}
arr = Array.CreateInstance(typeof(Object), hd.Count);
ks.CopyTo(arr, 0);
ind = Array.IndexOf(arr, keysShort[0]);
if (ind >= 0)
{
Assert.False(true, string.Format("Error, Keys still contains removed value " + ind));
}
hd.Add(keysShort[0], "new item");
if (hd.Count != len)
{
Assert.False(true, string.Format("Error, didn't add element"));
}
if (ks.Count != len)
{
Assert.False(true, string.Format("Error, Keys were not updated after addition"));
}
arr = Array.CreateInstance(typeof(Object), hd.Count);
ks.CopyTo(arr, 0);
ind = Array.IndexOf(arr, keysShort[0]);
if (ind < 0)
{
Assert.False(true, string.Format("Error, Keys doesn't contain added value "));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEngine;
namespace UnityTest
{
public class MemberResolver
{
private object m_CallingObjectRef;
private MemberInfo[] m_Callstack;
private readonly GameObject m_GameObject;
private readonly string m_Path;
public MemberResolver(GameObject gameObject, string path)
{
path = path.Trim();
ValidatePath(path);
m_GameObject = gameObject;
m_Path = path.Trim();
}
public object GetValue(bool useCache)
{
if (useCache && m_CallingObjectRef != null)
{
object val = m_CallingObjectRef;
for (int i = 0; i < m_Callstack.Length; i++)
val = GetValueFromMember(val, m_Callstack[i]);
return val;
}
object result = GetBaseObject();
var fullCallStack = GetCallstack();
m_CallingObjectRef = result;
var tempCallstack = new List<MemberInfo>();
for (int i = 0; i < fullCallStack.Length; i++)
{
var member = fullCallStack[i];
result = GetValueFromMember(result, member);
tempCallstack.Add(member);
if (result == null) return null;
var type = result.GetType();
//String is not a value type but we don't want to cache it
if (!IsValueType(type) && type != typeof(System.String))
{
tempCallstack.Clear();
m_CallingObjectRef = result;
}
}
m_Callstack = tempCallstack.ToArray();
return result;
}
public Type GetMemberType()
{
var callstack = GetCallstack();
if (callstack.Length == 0) return GetBaseObject().GetType();
var member = callstack[callstack.Length - 1];
if (member is FieldInfo)
return (member as FieldInfo).FieldType;
if (member is MethodInfo)
return (member as MethodInfo).ReturnType;
return null;
}
#region Static wrappers
public static bool TryGetMemberType(GameObject gameObject, string path, out Type value)
{
try
{
var mr = new MemberResolver(gameObject, path);
value = mr.GetMemberType();
return true;
}
catch (InvalidPathException)
{
value = null;
return false;
}
}
public static bool TryGetValue(GameObject gameObject, string path, out object value)
{
try
{
var mr = new MemberResolver(gameObject, path);
value = mr.GetValue(false);
return true;
}
catch (InvalidPathException)
{
value = null;
return false;
}
}
#endregion
private object GetValueFromMember(object obj, MemberInfo memberInfo)
{
if (memberInfo is FieldInfo)
return (memberInfo as FieldInfo).GetValue(obj);
if (memberInfo is MethodInfo)
return (memberInfo as MethodInfo).Invoke(obj, null);
throw new InvalidPathException(memberInfo.Name);
}
private object GetBaseObject()
{
if (string.IsNullOrEmpty(m_Path)) return m_GameObject;
var firstElement = m_Path.Split('.')[0];
var comp = m_GameObject.GetComponent(firstElement);
if (comp != null)
return comp;
return m_GameObject;
}
private MemberInfo[] GetCallstack()
{
if (m_Path == "") return new MemberInfo[0];
var propsQueue = new Queue<string>(m_Path.Split('.'));
Type type = GetBaseObject().GetType();
if (type != typeof(GameObject))
propsQueue.Dequeue();
PropertyInfo propertyTemp;
FieldInfo fieldTemp;
var list = new List<MemberInfo>();
while (propsQueue.Count != 0)
{
var nameToFind = propsQueue.Dequeue();
fieldTemp = GetField(type, nameToFind);
if (fieldTemp != null)
{
type = fieldTemp.FieldType;
list.Add(fieldTemp);
continue;
}
propertyTemp = GetProperty(type, nameToFind);
if (propertyTemp != null)
{
type = propertyTemp.PropertyType;
var getMethod = GetGetMethod(propertyTemp);
list.Add(getMethod);
continue;
}
throw new InvalidPathException(nameToFind);
}
return list.ToArray();
}
private void ValidatePath(string path)
{
bool invalid = false;
if (path.StartsWith(".") || path.EndsWith("."))
invalid = true;
if (path.IndexOf("..") >= 0)
invalid = true;
if (Regex.IsMatch(path, @"\s"))
invalid = true;
if (invalid)
throw new InvalidPathException(path);
}
private static bool IsValueType(Type type)
{
#if !UNITY_METRO
return type.IsValueType;
#else
return false;
#endif
}
private static FieldInfo GetField(Type type, string fieldName)
{
#if !UNITY_METRO
return type.GetField(fieldName);
#else
return null;
#endif
}
private static PropertyInfo GetProperty(Type type, string propertyName)
{
#if !UNITY_METRO
return type.GetProperty(propertyName);
#else
return null;
#endif
}
private static MethodInfo GetGetMethod(PropertyInfo propertyInfo)
{
#if !UNITY_METRO
return propertyInfo.GetGetMethod();
#else
return null;
#endif
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// What kind of "player" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
// These override the values set in core/scripts/server/spawn.cs
//-----------------------------------------------------------------------------
// Leave $Game::defaultPlayerClass and $Game::defaultPlayerDataBlock as empty strings ("")
// to spawn a the $Game::defaultCameraClass as the control object.
$Game::DefaultPlayerClass = "";
$Game::DefaultPlayerDataBlock = "";
$Game::DefaultPlayerSpawnGroups = "CameraSpawnPoints PlayerSpawnPoints PlayerDropPoints";
//-----------------------------------------------------------------------------
// What kind of "camera" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
// These override the values set in core/scripts/server/spawn.cs
//-----------------------------------------------------------------------------
$Game::DefaultCameraClass = "Camera";
$Game::DefaultCameraDataBlock = "Observer";
$Game::DefaultCameraSpawnGroups = "CameraSpawnPoints PlayerSpawnPoints PlayerDropPoints";
// Global movement speed that affects all Cameras
$Camera::MovementSpeed = 30;
//-----------------------------------------------------------------------------
// GameConnection manages the communication between the server's world and the
// client's simulation. These functions are responsible for maintaining the
// client's camera and player objects.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// This is the main entry point for spawning a control object for the client.
// The control object is the actual game object that the client is responsible
// for controlling in the client and server simulations. We also spawn a
// convenient camera object for use as an alternate control object. We do not
// have to spawn this camera object in order to function in the simulation.
//
// Called for each client after it's finished downloading the mission and is
// ready to start playing.
//-----------------------------------------------------------------------------
function GameConnection::onClientEnterGame(%this)
{
// This function currently relies on some helper functions defined in
// core/scripts/spawn.cs. For custom spawn behaviors one can either
// override the properties on the SpawnSphere's or directly override the
// functions themselves.
// Find a spawn point for the camera
%cameraSpawnPoint = pickCameraSpawnPoint($Game::DefaultCameraSpawnGroups);
// Spawn a camera for this client using the found %spawnPoint
%this.spawnCamera(%cameraSpawnPoint);
// Find a spawn point for the player
%playerSpawnPoint = pickPlayerSpawnPoint($Game::DefaultPlayerSpawnGroups);
// Spawn a camera for this client using the found %spawnPoint
%this.spawnPlayer(%playerSpawnPoint);
}
//-----------------------------------------------------------------------------
// Clean up the client's control objects
//-----------------------------------------------------------------------------
function GameConnection::onClientLeaveGame(%this)
{
// Cleanup the camera
if (isObject(%this.camera))
%this.camera.delete();
// Cleanup the player
if (isObject(%this.player))
%this.player.delete();
}
//-----------------------------------------------------------------------------
// Handle a player's death
//-----------------------------------------------------------------------------
function GameConnection::onDeath(%this, %sourceObject, %sourceClient, %damageType, %damLoc)
{
// Clear out the name on the corpse
if (isObject(%this.player))
{
if (%this.player.isMethod("setShapeName"))
%this.player.setShapeName("");
}
// Switch the client over to the death cam
if (isObject(%this.camera) && isObject(%this.player))
{
%this.camera.setMode("Corpse", %this.player);
%this.setControlObject(%this.camera);
}
// Unhook the player object
%this.player = 0;
}
//-----------------------------------------------------------------------------
// Server, mission, and game management
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// The server has started up so do some game start up
//-----------------------------------------------------------------------------
function onServerCreated()
{
// Server::GameType is sent to the master server.
// This variable should uniquely identify your game and/or mod.
$Server::GameType = "Torque 3D";
// Server::MissionType sent to the master server. Clients can
// filter servers based on mission type.
$Server::MissionType = "pureLIGHT";
// GameStartTime is the sim time the game started. Used to calculated
// game elapsed time.
$Game::StartTime = 0;
// Create the server physics world.
physicsInitWorld( "server" );
// Load up any objects or datablocks saved to the editor managed scripts
%datablockFiles = new ArrayObject();
%datablockFiles.add( "art/particles/managedParticleData.cs" );
%datablockFiles.add( "art/particles/managedParticleEmitterData.cs" );
%datablockFiles.add( "art/decals/managedDecalData.cs" );
%datablockFiles.add( "art/datablocks/managedDatablocks.cs" );
%datablockFiles.add( "art/forest/managedItemData.cs" );
%datablockFiles.add( "art/datablocks/datablockExec.cs" );
loadDatablockFiles( %datablockFiles, true );
// Run the other gameplay scripts in this folder
exec("./scriptExec.cs");
// Keep track of when the game started
$Game::StartTime = $Sim::Time;
}
//-----------------------------------------------------------------------------
// This function is called as part of a server shutdown
//-----------------------------------------------------------------------------
function onServerDestroyed()
{
// Destroy the server physcis world
physicsDestroyWorld( "server" );
}
//-----------------------------------------------------------------------------
// Called by loadMission() once the mission is finished loading
//-----------------------------------------------------------------------------
function onMissionLoaded()
{
// Start the server side physics simulation
physicsStartSimulation( "server" );
// Nothing special for now, just start up the game play
startGame();
}
//-----------------------------------------------------------------------------
// Called by endMission(), right before the mission is destroyed
//-----------------------------------------------------------------------------
function onMissionEnded()
{
// Stop the server physics simulation
physicsStopSimulation( "server" );
// Normally the game should be ended first before the next
// mission is loaded, this is here in case loadMission has been
// called directly. The mission will be ended if the server
// is destroyed, so we only need to cleanup here.
$Game::Running = false;
}
//-----------------------------------------------------------------------------
// Called once the game has started
//-----------------------------------------------------------------------------
function startGame()
{
if ($Game::Running)
{
error("startGame(): End the game first!");
return;
}
$Game::Running = true;
}
//-----------------------------------------------------------------------------
// Called once the game has ended
//-----------------------------------------------------------------------------
function endGame()
{
if (!$Game::Running)
{
error("endGame(): No game running!");
return;
}
// Inform the client the game is over
for( %clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++ )
{
%cl = ClientGroup.getObject( %clientIndex );
commandToClient(%cl, 'GameEnd');
}
// Delete all the temporary mission objects
resetMission();
$Game::Running = false;
}
| |
namespace StockSharp.Algo.Storages
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.Logging;
using StockSharp.Messages;
/// <summary>
/// Security identifier mappings storage.
/// </summary>
public interface ISecurityMappingStorage
{
/// <summary>
/// The new native security identifier added to storage.
/// </summary>
event Action<string, SecurityIdMapping> Changed;
/// <summary>
/// Initialize the storage.
/// </summary>
/// <returns>Possible errors with storage names. Empty dictionary means initialization without any issues.</returns>
IDictionary<string, Exception> Init();
/// <summary>
/// Get storage names.
/// </summary>
/// <returns>Storage names.</returns>
IEnumerable<string> GetStorageNames();
/// <summary>
/// Get security identifier mappings for storage.
/// </summary>
/// <param name="storageName">Storage name.</param>
/// <returns>Security identifiers mapping.</returns>
IEnumerable<SecurityIdMapping> Get(string storageName);
/// <summary>
/// Save security identifier mapping.
/// </summary>
/// <param name="storageName">Storage name.</param>
/// <param name="mapping">Security identifier mapping.</param>
/// <returns><see langword="true"/> if security mapping was added. If was changed, <see langword="false" />.</returns>
bool Save(string storageName, SecurityIdMapping mapping);
/// <summary>
/// Remove security mapping.
/// </summary>
/// <param name="storageName">Storage name.</param>
/// <param name="stockSharpId">StockSharp format.</param>
/// <returns><see langword="true"/> if mapping was added. Otherwise, <see langword="false" />.</returns>
bool Remove(string storageName, SecurityId stockSharpId);
/// <summary>
/// Try get <see cref="SecurityIdMapping.StockSharpId"/>.
/// </summary>
/// <param name="storageName">Storage name.</param>
/// <param name="adapterId">Adapter format.</param>
/// <returns><see cref="SecurityIdMapping.StockSharpId"/> if identifier exists. Otherwise, <see langword="null" />.</returns>
SecurityId? TryGetStockSharpId(string storageName, SecurityId adapterId);
/// <summary>
/// Try get <see cref="SecurityIdMapping.AdapterId"/>.
/// </summary>
/// <param name="storageName">Storage name.</param>
/// <param name="stockSharpId">StockSharp format.</param>
/// <returns><see cref="SecurityIdMapping.AdapterId"/> if identifier exists. Otherwise, <see langword="null" />.</returns>
SecurityId? TryGetAdapterId(string storageName, SecurityId stockSharpId);
}
/// <summary>
/// In memory security identifier mappings storage.
/// </summary>
public class InMemorySecurityMappingStorage : ISecurityMappingStorage
{
private readonly SynchronizedDictionary<string, PairSet<SecurityId, SecurityId>> _mappings = new(StringComparer.InvariantCultureIgnoreCase);
private Action<string, SecurityIdMapping> _changed;
event Action<string, SecurityIdMapping> ISecurityMappingStorage.Changed
{
add => _changed += value;
remove => _changed -= value;
}
IDictionary<string, Exception> ISecurityMappingStorage.Init()
{
return new Dictionary<string, Exception>();
}
IEnumerable<string> ISecurityMappingStorage.GetStorageNames()
{
lock (_mappings.SyncRoot)
return _mappings.Keys.ToArray();
}
IEnumerable<SecurityIdMapping> ISecurityMappingStorage.Get(string storageName)
{
if (storageName.IsEmpty())
throw new ArgumentNullException(nameof(storageName));
lock (_mappings.SyncRoot)
return _mappings.TryGetValue(storageName)?.Select(p => (SecurityIdMapping)p).ToArray() ?? Enumerable.Empty<SecurityIdMapping>();
}
bool ISecurityMappingStorage.Save(string storageName, SecurityIdMapping mapping)
{
return Save(storageName, mapping, out _);
}
internal bool Save(string storageName, SecurityIdMapping mapping, out IEnumerable<SecurityIdMapping> all)
{
if (storageName.IsEmpty())
throw new ArgumentNullException(nameof(storageName));
if (mapping.IsDefault())
throw new ArgumentNullException(nameof(mapping));
var added = false;
lock (_mappings.SyncRoot)
{
var mappings = _mappings.SafeAdd(storageName);
var stockSharpId = mapping.StockSharpId;
var adapterId = mapping.AdapterId;
if (mappings.ContainsKey(stockSharpId))
{
mappings.Remove(stockSharpId);
}
else if (mappings.ContainsValue(adapterId))
{
mappings.RemoveByValue(adapterId);
}
else
added = true;
mappings.Add(stockSharpId, adapterId);
all = added ? null : mappings.Select(p => (SecurityIdMapping)p).ToArray();
}
_changed?.Invoke(storageName, mapping);
return added;
}
bool ISecurityMappingStorage.Remove(string storageName, SecurityId stockSharpId)
{
return Remove(storageName, stockSharpId, out _);
}
SecurityId? ISecurityMappingStorage.TryGetStockSharpId(string storageName, SecurityId adapterId)
{
lock (_mappings.SyncRoot)
{
if (!_mappings.TryGetValue(storageName, out var mappings))
return null;
if (!mappings.TryGetKey(adapterId, out var stockSharpId))
return null;
return stockSharpId;
}
}
SecurityId? ISecurityMappingStorage.TryGetAdapterId(string storageName, SecurityId stockSharpId)
{
lock (_mappings.SyncRoot)
{
if (!_mappings.TryGetValue(storageName, out var mappings))
return null;
if (!mappings.TryGetValue(stockSharpId, out var adapterId))
return null;
return adapterId;
}
}
internal bool Remove(string storageName, SecurityId stockSharpId, out IEnumerable<SecurityIdMapping> all)
{
if (storageName.IsEmpty())
throw new ArgumentNullException(nameof(storageName));
if (stockSharpId.IsDefault())
throw new ArgumentNullException(nameof(storageName));
all = null;
lock (_mappings.SyncRoot)
{
var mappings = _mappings.TryGetValue(storageName);
if (mappings == null)
return false;
var removed = mappings.Remove(stockSharpId);
if (!removed)
return false;
all = mappings.Select(p => (SecurityIdMapping)p).ToArray();
}
_changed?.Invoke(storageName, new SecurityIdMapping { StockSharpId = stockSharpId });
return true;
}
internal void Load(string storageName, List<Tuple<SecurityId, SecurityId>> pairs)
{
if (storageName.IsEmpty())
throw new ArgumentNullException(nameof(storageName));
if (pairs == null)
throw new ArgumentNullException(nameof(pairs));
lock (_mappings.SyncRoot)
{
var mappings = _mappings.SafeAdd(storageName);
foreach (var tuple in pairs)
mappings.Add(tuple.Item1, tuple.Item2);
}
}
}
/// <summary>
/// CSV security identifier mappings storage.
/// </summary>
public sealed class CsvSecurityMappingStorage : ISecurityMappingStorage
{
private readonly ISecurityMappingStorage _inMemory = new InMemorySecurityMappingStorage();
private readonly string _path;
private DelayAction _delayAction;
/// <summary>
/// The time delayed action.
/// </summary>
public DelayAction DelayAction
{
get => _delayAction;
set => _delayAction = value ?? throw new ArgumentNullException(nameof(value));
}
/// <inheritdoc />
public event Action<string, SecurityIdMapping> Changed;
/// <summary>
/// Initializes a new instance of the <see cref="CsvSecurityMappingStorage"/>.
/// </summary>
/// <param name="path">Path to storage.</param>
public CsvSecurityMappingStorage(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
_path = path.ToFullPath();
_delayAction = new DelayAction(ex => ex.LogError());
}
/// <inheritdoc />
public IDictionary<string, Exception> Init()
{
Directory.CreateDirectory(_path);
var errors = _inMemory.Init();
var files = Directory.GetFiles(_path, "*.csv");
foreach (var fileName in files)
{
try
{
LoadFile(fileName);
}
catch (Exception ex)
{
errors.Add(fileName, ex);
}
}
return errors;
}
/// <inheritdoc />
public IEnumerable<string> GetStorageNames() => _inMemory.GetStorageNames();
/// <inheritdoc />
public IEnumerable<SecurityIdMapping> Get(string storageName) => _inMemory.Get(storageName);
/// <inheritdoc />
public bool Save(string storageName, SecurityIdMapping mapping)
{
if (storageName.IsEmpty())
throw new ArgumentNullException(nameof(storageName));
if (mapping.IsDefault())
throw new ArgumentNullException(nameof(mapping));
var added = ((InMemorySecurityMappingStorage)_inMemory).Save(storageName, mapping, out var all);
if (added)
Save(storageName, false, new[] { mapping });
else
Save(storageName, true, all);
Changed?.Invoke(storageName, mapping);
return added;
}
/// <inheritdoc />
public bool Remove(string storageName, SecurityId stockSharpId)
{
if (!((InMemorySecurityMappingStorage)_inMemory).Remove(storageName, stockSharpId, out var all))
return false;
Save(storageName, true, all);
Changed?.Invoke(storageName, new SecurityIdMapping { StockSharpId = stockSharpId });
return true;
}
/// <inheritdoc />
public SecurityId? TryGetStockSharpId(string storageName, SecurityId adapterId)
{
return _inMemory.TryGetStockSharpId(storageName, adapterId);
}
/// <inheritdoc />
public SecurityId? TryGetAdapterId(string storageName, SecurityId stockSharpId)
{
return _inMemory.TryGetAdapterId(storageName, stockSharpId);
}
private void LoadFile(string fileName)
{
Do.Invariant(() =>
{
if (!File.Exists(fileName))
return;
var pairs = new List<Tuple<SecurityId, SecurityId>>();
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
var reader = new FastCsvReader(stream, Encoding.UTF8);
reader.NextLine();
while (reader.NextLine())
{
var securityId = new SecurityId
{
SecurityCode = reader.ReadString(),
BoardCode = reader.ReadString()
};
var adapterId = new SecurityId
{
SecurityCode = reader.ReadString(),
BoardCode = reader.ReadString()
};
pairs.Add(Tuple.Create(securityId, adapterId));
}
}
((InMemorySecurityMappingStorage)_inMemory).Load(Path.GetFileNameWithoutExtension(fileName), pairs);
});
}
private void Save(string name, bool overwrite, IEnumerable<SecurityIdMapping> mappings)
{
DelayAction.DefaultGroup.Add(() =>
{
var fileName = Path.Combine(_path, name + ".csv");
var appendHeader = overwrite || !File.Exists(fileName) || new FileInfo(fileName).Length == 0;
var mode = overwrite ? FileMode.Create : FileMode.Append;
using (var writer = new CsvFileWriter(new TransactionFileStream(fileName, mode)))
{
if (appendHeader)
writer.WriteRow(new[] { "SecurityCode", "BoardCode", "AdapterCode", "AdapterBoard" });
foreach (var mapping in mappings)
{
writer.WriteRow(new[]
{
mapping.StockSharpId.SecurityCode,
mapping.StockSharpId.BoardCode,
mapping.AdapterId.SecurityCode,
mapping.AdapterId.BoardCode
});
}
}
});
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Wim
{
using System;
using System.IO;
using DiscUtils.Compression;
/// <summary>
/// Class to read data compressed using LZX algorithm.
/// </summary>
/// <remarks>This is not a general purpose LZX decompressor - it makes
/// simplifying assumptions, such as being able to load the entire stream
/// contents into memory..</remarks>
internal class LzxStream : Stream
{
private static uint[] s_positionSlots;
private static uint[] s_extraBits;
private LzxBitStream _bitStream;
private int _windowBits;
private int _fileSize;
private int _numPositionSlots;
private byte[] _buffer;
private int _bufferCount;
private long _position;
// Block state
private HuffmanTree _mainTree = null;
private HuffmanTree _lengthTree = null;
private HuffmanTree _alignedOffsetTree = null;
private uint[] _repeatedOffsets = new uint[] { 1, 1, 1 };
static LzxStream()
{
s_positionSlots = new uint[50];
s_extraBits = new uint[50];
uint numBits = 0;
s_positionSlots[1] = 1;
for (int i = 2; i < 50; i += 2)
{
s_extraBits[i] = numBits;
s_extraBits[i + 1] = numBits;
s_positionSlots[i] = s_positionSlots[i - 1] + (uint)(1 << (int)s_extraBits[i - 1]);
s_positionSlots[i + 1] = s_positionSlots[i] + (uint)(1 << (int)numBits);
if (numBits < 17)
{
numBits++;
}
}
}
public LzxStream(Stream stream, int windowBits, int fileSize)
{
_bitStream = new LzxBitStream(new BufferedStream(stream, 8192));
_windowBits = windowBits;
_fileSize = fileSize;
_numPositionSlots = _windowBits * 2;
_buffer = new byte[1 << windowBits];
ReadBlocks();
}
private enum BlockType
{
None = 0,
Verbatim = 1,
AlignedOffset = 2,
Uncompressed = 3
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { return _bufferCount; }
}
public override long Position
{
get
{
return _position;
}
set
{
_position = value;
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_position > Length)
{
return 0;
}
int numToRead = (int)Math.Min(count, _bufferCount - _position);
Array.Copy(_buffer, _position, buffer, offset, numToRead);
_position += numToRead;
return numToRead;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
private void ReadBlocks()
{
BlockType blockType = (BlockType)_bitStream.Read(3);
_buffer = new byte[32768];
_bufferCount = 0;
while (blockType != BlockType.None)
{
int blockSize = (_bitStream.Read(1) == 1) ? (1 << 15) : (int)_bitStream.Read(16);
if (blockType == BlockType.Uncompressed)
{
DecodeUncompressedBlock(blockSize);
}
else
{
DecodeCompressedBlock(blockType, blockSize);
_bufferCount += (int)blockSize;
}
// Read start of next block (if any)
blockType = (BlockType)_bitStream.Read(3);
}
FixupBlockBuffer();
}
/// <summary>
/// Fix up CALL instruction optimization.
/// </summary>
/// <remarks>A slightly odd feature of LZX for optimizing executable compression is that
/// relative CALL instructions (opcode E8) are converted to absolute values before compression.
/// This feature seems to always be turned-on in WIM files, so we have to apply the reverse
/// conversion.</remarks>
private void FixupBlockBuffer()
{
byte[] temp = new byte[4];
int i = 0;
while (i < _bufferCount - 10)
{
if (_buffer[i] == 0xE8)
{
Array.Copy(_buffer, i + 1, temp, 0, 4);
int absoluteValue = Utilities.ToInt32LittleEndian(_buffer, i + 1);
if (absoluteValue >= -i && absoluteValue < _fileSize)
{
int offsetValue;
if (absoluteValue >= 0)
{
offsetValue = absoluteValue - i;
}
else
{
offsetValue = absoluteValue + _fileSize;
}
Utilities.WriteBytesLittleEndian(offsetValue, _buffer, i + 1);
}
i += 4;
}
++i;
}
}
private void DecodeUncompressedBlock(int blockSize)
{
_bitStream.Align(16);
_repeatedOffsets[0] = Utilities.ToUInt32LittleEndian(_bitStream.ReadBytes(4), 0);
_repeatedOffsets[1] = Utilities.ToUInt32LittleEndian(_bitStream.ReadBytes(4), 0);
_repeatedOffsets[2] = Utilities.ToUInt32LittleEndian(_bitStream.ReadBytes(4), 0);
int numRead = _bitStream.ReadBytes(_buffer, _bufferCount, blockSize);
_bufferCount += numRead;
if ((numRead & 1) != 0)
{
_bitStream.ReadBytes(1);
}
}
private void DecodeCompressedBlock(BlockType blockType, int blockSize)
{
if (blockType == BlockType.AlignedOffset)
{
_alignedOffsetTree = ReadFixedHuffmanTree(8, 3);
}
ReadMainTree();
ReadLengthTree();
uint numRead = 0;
while (numRead < (uint)blockSize)
{
uint symbol = _mainTree.NextSymbol(_bitStream);
if (symbol < 256)
{
_buffer[_bufferCount + numRead++] = (byte)symbol;
}
else
{
uint lengthHeader = (symbol - 256) & 7;
uint matchLength = lengthHeader + 2 + ((lengthHeader == 7) ? _lengthTree.NextSymbol(_bitStream) : 0);
uint positionSlot = (symbol - 256) >> 3;
uint matchOffset;
if (positionSlot == 0)
{
matchOffset = _repeatedOffsets[0];
}
else if (positionSlot == 1)
{
matchOffset = _repeatedOffsets[1];
_repeatedOffsets[1] = _repeatedOffsets[0];
_repeatedOffsets[0] = matchOffset;
}
else if (positionSlot == 2)
{
matchOffset = _repeatedOffsets[2];
_repeatedOffsets[2] = _repeatedOffsets[0];
_repeatedOffsets[0] = matchOffset;
}
else
{
int extra = (int)s_extraBits[positionSlot];
uint formattedOffset;
if (blockType == BlockType.AlignedOffset)
{
uint verbatimBits = 0;
uint alignedBits = 0;
if (extra >= 3)
{
verbatimBits = _bitStream.Read(extra - 3) << 3;
alignedBits = _alignedOffsetTree.NextSymbol(_bitStream);
}
else if (extra > 0)
{
verbatimBits = _bitStream.Read(extra);
}
formattedOffset = s_positionSlots[positionSlot] + verbatimBits + alignedBits;
}
else
{
uint verbatimBits = (extra > 0) ? _bitStream.Read(extra) : 0;
formattedOffset = s_positionSlots[positionSlot] + verbatimBits;
}
matchOffset = formattedOffset - 2;
_repeatedOffsets[2] = _repeatedOffsets[1];
_repeatedOffsets[1] = _repeatedOffsets[0];
_repeatedOffsets[0] = matchOffset;
}
int destOffset = _bufferCount + (int)numRead;
int srcOffset = destOffset - (int)matchOffset;
for (int i = 0; i < matchLength; ++i)
{
_buffer[destOffset + i] = _buffer[srcOffset + i];
}
numRead += matchLength;
}
}
}
private void ReadMainTree()
{
uint[] lengths;
if (_mainTree == null)
{
lengths = new uint[256 + (8 * _numPositionSlots)];
}
else
{
lengths = _mainTree.Lengths;
}
HuffmanTree preTree = ReadFixedHuffmanTree(20, 4);
ReadLengths(preTree, lengths, 0, 256);
preTree = ReadFixedHuffmanTree(20, 4);
ReadLengths(preTree, lengths, 256, 8 * _numPositionSlots);
_mainTree = new HuffmanTree(lengths);
}
private void ReadLengthTree()
{
HuffmanTree preTree = ReadFixedHuffmanTree(20, 4);
_lengthTree = ReadDynamicHuffmanTree(249, preTree, _lengthTree);
}
private HuffmanTree ReadFixedHuffmanTree(int count, int bits)
{
uint[] treeLengths = new uint[count];
for (int i = 0; i < treeLengths.Length; ++i)
{
treeLengths[i] = _bitStream.Read(bits);
}
return new HuffmanTree(treeLengths);
}
private HuffmanTree ReadDynamicHuffmanTree(int count, HuffmanTree preTree, HuffmanTree oldTree)
{
uint[] lengths;
if (oldTree == null)
{
lengths = new uint[256 + (8 * _numPositionSlots)];
}
else
{
lengths = oldTree.Lengths;
}
ReadLengths(preTree, lengths, 0, count);
return new HuffmanTree(lengths);
}
private void ReadLengths(HuffmanTree preTree, uint[] lengths, int offset, int count)
{
int i = 0;
while (i < count)
{
uint value = preTree.NextSymbol(_bitStream);
if (value == 17)
{
uint numZeros = 4 + _bitStream.Read(4);
for (uint j = 0; j < numZeros; ++j)
{
lengths[offset + i] = 0;
++i;
}
}
else if (value == 18)
{
uint numZeros = 20 + _bitStream.Read(5);
for (uint j = 0; j < numZeros; ++j)
{
lengths[offset + i] = 0;
++i;
}
}
else if (value == 19)
{
uint same = _bitStream.Read(1);
value = preTree.NextSymbol(_bitStream);
if (value > 16)
{
throw new InvalidDataException("Invalid table encoding");
}
uint symbol = (17 + lengths[offset + i] - value) % 17;
for (uint j = 0; j < 4 + same; ++j)
{
lengths[offset + i] = symbol;
++i;
}
}
else
{
lengths[offset + i] = (17 + lengths[offset + i] - value) % 17;
++i;
}
}
}
}
}
| |
using System;
using System.Security.Cryptography;
using Core.Interfaces;
using Core.Model;
using Crypto.Generators;
using Crypto.Mappers;
using Crypto.Providers;
using Crypto.Wrappers;
using Moq;
using NUnit.Framework;
using Org.BouncyCastle.Math;
namespace Crypto.Test.Providers
{
[TestFixture]
public class AsymmetricKeyProviderTest
{
private AsymmetricKeyProvider keyProvider;
private RsaKeyProvider rsaKeyProvider;
private DsaKeyProvider dsaKeyProvider;
private EcKeyProvider ecKeyProvider;
private ElGamalKeyProvider elGamalKeyProvider;
private OidToCipherTypeMapper cipherTypeMapper;
private KeyEncryptionProvider pkcsEncryptionProvider;
private Mock<KeyInfoWrapper> keyInfoWrapper;
private IAsymmetricKeyPair rsaKeyPair;
private IAsymmetricKeyPair dsaKeyPair;
private IAsymmetricKeyPair ecKeyPair;
private IAsymmetricKeyPair elGamalKeyPair;
[OneTimeSetUp]
public void SetupAsymmetricKeyProviderTest()
{
var configuration = Mock.Of<IConfiguration>(c => c.Get<int>("SaltLengthInBytes") == 100 &&
c.Get<int>("KeyDerivationIterationCount") == 10);
var secureRandom = new SecureRandomGenerator();
var asymmetricKeyPairGenerator = new AsymmetricKeyPairGenerator(secureRandom);
var primeMapper = new Rfc3526PrimeMapper();
var fieldMapper = new FieldToCurveNameMapper();
rsaKeyProvider = new RsaKeyProvider(asymmetricKeyPairGenerator);
dsaKeyProvider = new DsaKeyProvider(asymmetricKeyPairGenerator);
ecKeyProvider = new EcKeyProvider(asymmetricKeyPairGenerator, fieldMapper);
elGamalKeyProvider = new ElGamalKeyProvider(asymmetricKeyPairGenerator, primeMapper);
cipherTypeMapper = new OidToCipherTypeMapper();
keyInfoWrapper = new Mock<KeyInfoWrapper>();
SetupValidKeyInfo();
SetupValidKeyProvider();
pkcsEncryptionProvider = new KeyEncryptionProvider(configuration, secureRandom, keyProvider, new Pkcs12KeyEncryptionGenerator(), new AesKeyEncryptionGenerator());
rsaKeyPair = rsaKeyProvider.CreateKeyPair(2048);
dsaKeyPair = dsaKeyProvider.CreateKeyPair(2048);
ecKeyPair = ecKeyProvider.CreateKeyPair("secp384r1");
elGamalKeyPair = elGamalKeyProvider.CreateKeyPair(2048, true);
}
private void SetupValidKeyProvider()
{
keyProvider = new AsymmetricKeyProvider(cipherTypeMapper, keyInfoWrapper.Object, rsaKeyProvider, dsaKeyProvider, ecKeyProvider, elGamalKeyProvider);
}
private void SetupValidKeyInfo()
{
keyInfoWrapper.Setup(k => k.GetPublicKeyInfo(It.IsAny<byte[]>()))
.Returns<byte[]>(content =>
{
var wrapper = new KeyInfoWrapper();
return wrapper.GetPublicKeyInfo(content);
});
keyInfoWrapper.Setup(k => k.GetPrivateKeyInfo(It.IsAny<byte[]>()))
.Returns<byte[]>(content =>
{
var wrapper = new KeyInfoWrapper();
return wrapper.GetPrivateKeyInfo(content);
});
}
[TestFixture]
public class GetPublicKey : AsymmetricKeyProviderTest
{
[SetUp]
public void Setup()
{
SetupValidKeyProvider();
SetupValidKeyInfo();
}
[TestCase(CipherType.Pkcs5Encrypted)]
[TestCase(CipherType.Pkcs12Encrypted)]
[TestCase(CipherType.Unknown)]
public void ShouldThrowExceptionWhenKeyTypeIsNotSupported(CipherType cipherType)
{
var typeMapperMock = new Mock<OidToCipherTypeMapper>();
typeMapperMock.Setup(ctm => ctm.MapOidToCipherType(It.IsAny<string>()))
.Returns(cipherType);
keyProvider = new AsymmetricKeyProvider(typeMapperMock.Object, keyInfoWrapper.Object, rsaKeyProvider, dsaKeyProvider, ecKeyProvider, elGamalKeyProvider);
Assert.Throws<ArgumentException>(() =>
{
keyProvider.GetPublicKey(rsaKeyPair.PublicKey.Content);
});
}
[Test]
public void ShouldThrowExceptionWhenPublicKeyCannotBeConstrcuted()
{
keyInfoWrapper.Setup(k => k.GetPublicKeyInfo(It.IsAny<byte[]>()))
.Throws<ArgumentException>();
Assert.Throws<CryptographicException>(() =>
{
keyProvider.GetPublicKey(rsaKeyPair.PublicKey.Content);
});
}
[Test]
public void ShouldReturnPublicRsaKey()
{
IAsymmetricKey result = keyProvider.GetPublicKey(rsaKeyPair.PublicKey.Content);
Assert.IsAssignableFrom<RsaKey>(result);
Assert.IsFalse(result.IsPrivateKey);
}
[Test]
public void ShouldReturnPublicDsaKey()
{
IAsymmetricKey result = keyProvider.GetPublicKey(dsaKeyPair.PublicKey.Content);
Assert.IsAssignableFrom<DsaKey>(result);
Assert.IsFalse(result.IsPrivateKey);
}
[Test]
public void ShouldReturnPublicEcKey()
{
IAsymmetricKey result = keyProvider.GetPublicKey(ecKeyPair.PublicKey.Content);
Assert.IsAssignableFrom<EcKey>(result);
Assert.IsFalse(result.IsPrivateKey);
}
[Test]
public void ShouldReturnPublicElGamalKey()
{
IAsymmetricKey result = keyProvider.GetPublicKey(elGamalKeyPair.PublicKey.Content);
Assert.IsAssignableFrom<ElGamalKey>(result);
Assert.IsFalse(result.IsPrivateKey);
}
[Test]
public void ShouldReturnValidKey()
{
var algorithmMapper = new SignatureAlgorithmIdentifierMapper();
var secureRandom = new SecureRandomGenerator();
var signatureProvider = new SignatureProvider(algorithmMapper, secureRandom, new SignerUtilitiesWrapper());
byte[] data = secureRandom.NextBytes(100);
Signature signature = signatureProvider.CreateSignature(rsaKeyPair.PrivateKey, data);
IAsymmetricKey result = keyProvider.GetPublicKey(rsaKeyPair.PublicKey.Content);
Assert.IsTrue(signatureProvider.VerifySignature(result, signature));
}
}
[TestFixture]
public class GetPrivateKey : AsymmetricKeyProviderTest
{
[SetUp]
public void Setup()
{
SetupValidKeyProvider();
SetupValidKeyInfo();
}
[TestCase(CipherType.Pkcs5Encrypted)]
[TestCase(CipherType.Pkcs12Encrypted)]
[TestCase(CipherType.Unknown)]
public void ShouldThrowExceptionWhenKeyTypeIsNotSupported(CipherType cipherType)
{
var typeMapperMock = new Mock<OidToCipherTypeMapper>();
typeMapperMock.Setup(ctm => ctm.MapOidToCipherType(It.IsAny<string>()))
.Returns(cipherType);
keyProvider = new AsymmetricKeyProvider(typeMapperMock.Object, keyInfoWrapper.Object, rsaKeyProvider, dsaKeyProvider, ecKeyProvider, elGamalKeyProvider);
Assert.Throws<ArgumentException>(() =>
{
keyProvider.GetPrivateKey(rsaKeyPair.PrivateKey.Content);
});
}
[Test]
public void ShouldThrowExceptionWhenKeyInfoTrowsArgumentException()
{
keyInfoWrapper.Setup(k => k.GetPrivateKeyInfo(It.IsAny<byte[]>()))
.Throws<ArgumentException>();
Assert.Throws<CryptographicException>(() =>
{
keyProvider.GetPrivateKey(rsaKeyPair.PrivateKey.Content);
});
}
[Test]
public void ShouldThrowExceptionWhenKeyInfoThrowsInvalidCastException()
{
keyInfoWrapper.Setup(k => k.GetPrivateKeyInfo(It.IsAny<byte[]>()))
.Throws<InvalidCastException>();
Assert.Throws<CryptographicException>(() =>
{
keyProvider.GetPrivateKey(rsaKeyPair.PrivateKey.Content);
});
}
[Test]
public void ShouldReturnPrivateRsaKey()
{
IAsymmetricKey result = keyProvider.GetPrivateKey(rsaKeyPair.PrivateKey.Content);
Assert.IsAssignableFrom<RsaKey>(result);
Assert.IsTrue(result.IsPrivateKey);
}
[Test]
public void ShouldReturnPrivateDsaKey()
{
IAsymmetricKey result = keyProvider.GetPrivateKey(dsaKeyPair.PrivateKey.Content);
Assert.IsAssignableFrom<DsaKey>(result);
Assert.IsTrue(result.IsPrivateKey);
}
[Test]
public void ShouldReturnPrivateEcKey()
{
IAsymmetricKey result = keyProvider.GetPrivateKey(ecKeyPair.PrivateKey.Content);
Assert.IsAssignableFrom<EcKey>(result);
Assert.IsTrue(result.IsPrivateKey);
}
[Test]
public void ShouldReturnPrivateElGamalKey()
{
IAsymmetricKey result = keyProvider.GetPrivateKey(elGamalKeyPair.PrivateKey.Content);
Assert.IsAssignableFrom<ElGamalKey>(result);
Assert.IsTrue(result.IsPrivateKey);
}
[Test]
public void ShouldReturnValidKey()
{
var algorithmMapper = new SignatureAlgorithmIdentifierMapper();
var secureRandom = new SecureRandomGenerator();
var signatureProvider = new SignatureProvider(algorithmMapper, secureRandom, new SignerUtilitiesWrapper());
byte[] data = secureRandom.NextBytes(100);
IAsymmetricKey result = keyProvider.GetPrivateKey(rsaKeyPair.PrivateKey.Content);
Signature signature = signatureProvider.CreateSignature(result, data);
Assert.IsTrue(signatureProvider.VerifySignature(rsaKeyPair.PublicKey, signature));
}
}
[TestFixture]
public class GetEncryptedPrivateKey : AsymmetricKeyProviderTest
{
private IAsymmetricKey encryptedPrivateKey;
[SetUp]
public void SetupGetEncryptedPrivateKey()
{
keyProvider = new AsymmetricKeyProvider(new OidToCipherTypeMapper(), new KeyInfoWrapper(), rsaKeyProvider, dsaKeyProvider, ecKeyProvider, elGamalKeyProvider);
}
[TestFixture]
public class PkcsEncrypted : GetEncryptedPrivateKey
{
[SetUp]
public void Setup()
{
var key = pkcsEncryptionProvider.EncryptPrivateKey(rsaKeyPair.PrivateKey, "foobar", EncryptionType.Pkcs);
encryptedPrivateKey = keyProvider.GetEncryptedPrivateKey(key.Content);
}
[Test]
public void ShouldSetCipherType()
{
Assert.AreEqual(CipherType.Pkcs12Encrypted, encryptedPrivateKey.CipherType);
}
[Test]
public void ShouldReturnEncryptedPrivateKey()
{
Assert.IsAssignableFrom<EncryptedKey>(encryptedPrivateKey);
CollectionAssert.AreNotEqual(encryptedPrivateKey.Content, rsaKeyPair.PrivateKey.Content);
}
}
[TestFixture]
public class AesEncrypted : GetEncryptedPrivateKey
{
[SetUp]
public void Setup()
{
var key = pkcsEncryptionProvider.EncryptPrivateKey(rsaKeyPair.PrivateKey, "foobar", EncryptionType.Aes);
encryptedPrivateKey = keyProvider.GetEncryptedPrivateKey(key.Content);
}
[Test]
public void ShouldSetCipherType()
{
Assert.AreEqual(CipherType.AesEncrypted, encryptedPrivateKey.CipherType);
}
[Test]
public void ShouldReturnEncryptedPrivateKey()
{
Assert.IsAssignableFrom<EncryptedKey>(encryptedPrivateKey);
CollectionAssert.AreNotEqual(encryptedPrivateKey.Content, rsaKeyPair.PrivateKey.Content);
}
}
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
using System;
using System.CodeDom;
using System.Collections;
using System.Globalization;
using System.Threading;
using System.Windows.Automation;
using System.Windows;
using Drawing = System.Drawing;
namespace InternalHelper.Tests.Patterns
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
public class TogglePatternWrapper : PatternObject
{
#region Variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
TogglePattern _pattern = null;
#endregion
#region Constructor
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
protected TogglePatternWrapper(AutomationElement element, string testSuite, TestPriorities priority, TypeOfControl typeOfControl, TypeOfPattern typeOfPattern, string dirResults, bool testEvents, IApplicationCommands commands)
:
base(element, testSuite, priority, typeOfControl, typeOfPattern, dirResults, testEvents, commands)
{
_pattern = (TogglePattern)element.GetCurrentPattern(TogglePattern.Pattern);
if (_pattern == null)
throw new Exception("TogglePattern: " + Helpers.PatternNotSupported);
}
#endregion
#region Properties
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal ToggleState pToggleState
{
get
{
ToggleState ts = _pattern.Current.ToggleState;
Comment("Current ToggleState == " + ts);
return ts;
}
}
#endregion Properties
#region Methods
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
internal void patternToggle(Type expectedException, CheckType checkType)
{
string call = "Toggle()";
try
{
_pattern.Toggle();
}
catch (Exception actualException)
{
if (Library.IsCriticalException(actualException))
throw;
TestException(expectedException, actualException, call, checkType);
return;
}
TestNoException(expectedException, call, checkType);
}
#endregion Methods
}
}
namespace Microsoft.Test.UIAutomation.Tests.Patterns
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Tests.Patterns;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
public sealed class ToggleTests : TogglePatternWrapper
{
#region InternalHelper Generic code common to all patterns/controls
#region Member variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
const string THIS = "ToggleTests";
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public const string TestSuite = NAMESPACE + "." + THIS;
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public static readonly string TestWhichPattern = Automation.PatternName(TogglePattern.Pattern);
#endregion Member variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public ToggleTests(AutomationElement element, TestPriorities priority, string dirResults, bool testEvents, TypeOfControl typeOfControl, IApplicationCommands commands)
:
base(element, TestSuite, priority, typeOfControl, TypeOfPattern.Toggle, dirResults, testEvents, commands)
{
}
#endregion InternalHelper Generic code common to all patterns/controls
#region Toggle Method
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Toggle.1.1",
TestSummary = "Toggle to the next state when ToggleStateProperty == ToggleStateProperty.On",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(TogglePattern.ToggleStateProperty)",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
Description = new string[] {
"Precondition: ToggleStateProperty == On",
"Precondition: SetFocus to the element",
"Step: Setup a StateProperty PropertyChange event",
"Step: Successful call TogglePattern.Toggle()",
"Step: Wait for 1 event to occur",
"Verify: The StateProperty PropertyChange event is fired",
"Verify: The StateProperty has changed",
"Cleanup: Call Toggle() until ToggleStateProperty == original state(On)"
})]
public void Toggle11(TestCaseAttribute testCase)
{
try
{
HeaderComment(testCase);
TestToggle1(ToggleState.On, EventFired.True, false);
}
catch (Exception e)
{
throw e; /* amd64fre does not include this function (1st called in assembly?) in the trace unless we do this */
}
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Toggle.1.2",
TestSummary = "Toggle to the next state when ToggleStateProperty == Off",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(TogglePattern.ToggleStateProperty)",
Priority = TestPriorities.Pri1,
Status = TestStatus.Problem,
ProblemDescription = "Radio buttons have an issue if the value is On",
Author = "Microsoft Corp.",
Description = new string[] {
"Precondition: ToggleStateProperty == Off",
"Precondition: SetFocus to the element",
"Step: Setup a StateProperty PropertyChange event",
"Step: Successful call TogglePattern.Toggle()",
"Step: Wait for 1 event to occur",
"Verify: The StateProperty PropertyChange event is fired",
"Verify: The StateProperty has changed",
"Cleanup: Call Toggle() until ToggleStateProperty == original state(Off)"
})]
public void Toggle12(TestCaseAttribute testCase)
{
try
{
HeaderComment(testCase);
TestToggle1(ToggleState.Off, EventFired.True, false);
}
catch (Exception e)
{
throw e; /* amd64fre does not include this function (1st called in assembly?) in the trace unless we do this */
}
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Toggle.1.3",
TestSummary = "Toggle to the next state when ToggleState = ToggleState.Indeterminate",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(TogglePattern.ToggleStateProperty)",
Priority = TestPriorities.Pri1,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
Description = new string[] {
"Precondition: ToggleStateProperty == Indeterminate",
"Precondition: SetFocus to the element",
"Step: Setup a StateProperty PropertyChange event",
"Verify: Successful call TogglePattern.Toggle()",
"Step: Wait for 1 event to occur",
"Verify: The StateProperty PropertyChange event is fired",
"Verify: The StateProperty has changed",
"Cleanup: Call Toggle() until ToggleStateProperty == original state(Off)"
})]
public void Toggle13(TestCaseAttribute testCase)
{
try
{
HeaderComment(testCase);
TestToggle1(ToggleState.Indeterminate, EventFired.True, false);
}
catch (Exception e)
{
throw e; /* amd64fre does not include this function (1st called in assembly?) in the trace unless we do this */
}
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Toggle.1.4",
TestSummary = "Toggle to the next state when ToggleState = ToggleState.Off using spacebar",
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(TogglePattern.ToggleStateProperty)",
Priority = TestPriorities.Pri1,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
Description = new string[] {
"Procendition: ToggleStateProperty == off",
"Precondition: SetFocus to the element",
"Step: Setup a StateProperty PropertyChange event",
"Step: Press the spacebar to toggle the item",
"Step: Wait for 1 event to occur",
"Verify: The StateProperty PropertyChange event is fired",
"Verify: The StateProperty has changed",
"Cleanup: Call Toggle() until ToggleStateProperty == original state(Off)"
})]
public void Toggle14(TestCaseAttribute testCase)
{
try
{
HeaderComment(testCase);
TestToggle1(ToggleState.Off, EventFired.True, true);
}
catch (Exception e)
{
throw e; /* amd64fre does not include this function (1st called in assembly?) in the trace unless we do this */
}
}
#endregion Toggle Method
#region ToggleState Property
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("ToggleState.2.1",
TestSummary = "Verify the control is at the ToggleState is as defined by 'argument'",
TestCaseType = TestCaseType.Arguments | TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(TogglePattern.ToggleStateProperty)",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
Description = new string[] {
"Verify: The element is at the On state",
})]
public void Toggle21(TestCaseAttribute testCase, object[] argument)
{
try
{
HeaderComment(testCase);
if (argument == null)
throw new ArgumentException();
if (argument[0] == null)
throw new ArgumentException();
if (argument.Length != 1)
throw new ArgumentException();
// Get the value passed into the test case
ToggleState expectedValue = (ToggleState)(argument[0]);
TS_VerifyToggleState(expectedValue, true, CheckType.Verification);
}
catch (Exception e)
{
throw e; /* amd64fre does not include this function (1st called in assembly?) in the trace unless we do this */
}
}
#endregion ToggleState Property
#region Tests
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TestToggle1(ToggleState expectedState, EventFired eventShouldFire, bool usingKeyboard)
{
ToggleState orgState = pToggleState;
// "Precondition: ToggleStateProperty == expectedState",
TS_VerifyToggleState(orgState, true, CheckType.IncorrectElementConfiguration);
// "SetFocus to the element",
TS_SetFocus(m_le, null, CheckType.IncorrectElementConfiguration);
// "Step: Setup a StateProperty PropertyChange event",
TSC_AddPropertyChangedListener(m_le, TreeScope.Element, new AutomationProperty[] { TogglePattern.ToggleStateProperty }, CheckType.Verification);
// "Verify: Successful call TogglePattern.Toggle()",
if (!usingKeyboard)
TS_Toggle(null, CheckType.Verification);
else
TS_PressKeys(true, System.Windows.Input.Key.Space);
// "Step: Wait for 1 event to occur
TSC_WaitForEvents(1);
// "Verify: The StateProperty PropertyChange event is fired",
TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { eventShouldFire }, new AutomationProperty[] { TogglePattern.ToggleStateProperty }, CheckType.Verification);
// "Verify: The StateProperty has changed",
TS_VerifyToggleState(orgState, false, CheckType.Verification);
// "Cleanup: Call Toggle() until ToggleStateProperty == original state(Off)"
//TS_ToggleTo(orgState, null, CheckType.Verification);
m_TestStep++;
}
#endregion Tests
#region TS_
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_ToggleTo(ToggleState toggleState, Type exceptionExpected, CheckType checkType)
{
// I don't know, lets try 5 times max<g>
const int MAX = 5;
for (int count = 0; count < MAX; count++)
{
patternToggle(exceptionExpected, checkType);
if (toggleState == pToggleState)
{
m_TestStep++;
return;
}
}
ThrowMe(checkType, "Could not set ToggeState == " + toggleState + " in " + MAX + " tries");
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_Toggle(Type expectedExpection, CheckType checkType)
{
patternToggle(expectedExpection, checkType);
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_VerifyToggleState(ToggleState state, bool shouldBe, CheckType checkType)
{
ToggleState ts = pToggleState;
if ((ts == state) != shouldBe)
ThrowMe(checkType, "TogglePattern.ToggleState == " + ts);
m_TestStep++;
}
#endregion TS_
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.Reinforcement.CS
{
/// <summary>
/// The interface for the family instance reinforcement creation.
/// The main method is Run(), which used to create the reinforcement
/// </summary>
public interface IFrameReinMaker
{
/// <summary>
/// Main function of Maker interface
/// </summary>
/// <returns>indicate the result of run</returns>
bool Run();
}
/// <summary>
/// The base class for family instance reinforcement creation.
/// It only implement the Run() method. which give the flow process for creation.
/// </summary>
public class FramReinMaker : IFrameReinMaker
{
/// <summary>
/// the API create handle
/// </summary>
protected Autodesk.Revit.DB.Document m_revitDoc;
/// <summary>
/// the family instance to places rebar on
/// </summary>
protected FamilyInstance m_hostObject;
/// <summary>
/// a set to store all the rebar types
/// </summary>
protected List<RebarBarType> m_rebarTypes = new List<RebarBarType>();
/// <summary>
/// a list to store all the hook types
/// </summary>
protected List<RebarHookType> m_hookTypes = new List<RebarHookType>();
/// <summary>
/// Show all the rebar types in revit
/// </summary>
public IList<RebarBarType> RebarTypes
{
get
{
return m_rebarTypes;
}
}
/// <summary>
/// Show all the rebar hook types in revit
/// </summary>
public IList<RebarHookType> HookTypes
{
get
{
return m_hookTypes;
}
}
/// <summary>
/// Implement the Run() method of IFrameReinMaker interface.
/// Give the flew process of the reinforcement creation.
/// </summary>
/// <returns></returns>
bool IFrameReinMaker.Run()
{
// First, check the data whether is right and enough.
if (!AssertData())
{
return false;
}
// Second, show a form to the user to collect creation information
if (!DisplayForm())
{
return false;
}
// At last, begin to create the reinforcement rebars
if (!FillWithBars())
{
return false;
}
return true;
}
/// <summary>
/// This is a virtual method which used to check the data whether is right and enough.
/// </summary>
/// <returns>true if the the data is right and enough, otherwise false.</returns>
protected virtual bool AssertData()
{
return true; // only return true
}
/// <summary>
/// This is a virtual method which used to collect creation information
/// </summary>
/// <returns>true if the informatin collection is successful, otherwise false</returns>
protected virtual bool DisplayForm()
{
return true; // only return true
}
/// <summary>
/// This is a virtual method which used to create reinforcement.
/// </summary>
/// <returns>true if the creation is successful, otherwise false</returns>
protected virtual bool FillWithBars()
{
return true; // only return true
}
/// <summary>
/// The constructor of FramReinMaker
/// </summary>
/// <param name="commandData">the ExternalCommandData reference</param>
/// <param name="hostObject">the host family instance</param>
protected FramReinMaker(ExternalCommandData commandData, FamilyInstance hostObject)
{
// Get and store reinforcement create handle and host family instance
m_revitDoc = commandData.Application.ActiveUIDocument.Document;
m_hostObject = hostObject;
// Get all the rebar types in revit
if (!GetRebarTypes(commandData))
{
throw new Exception("Can't get any rebar type from revit.");
}
// Get all the rebar hook types in revit
if (!GetHookTypes(commandData))
{
throw new Exception("Can't get any rebar hook type from revit.");
}
}
/// <summary>
/// The helper function to changed rebar number and spacing properties
/// </summary>
/// <param name="bar">The rebar instance which need to modify</param>
/// <param name="number">The rebar number want to set</param>
/// <param name="spacing">The spacing want to set</param>
protected static void SetRebarSpaceAndNumber(Rebar bar, int number, double spacing)
{
// Asset the parameter is valid
if (null == bar || 2 > number || 0 > spacing)
{
return;
}
// Change the rebar number and spacing properties
bar.SetLayoutAsNumberWithSpacing(number, spacing, true, true, true);
}
/// <summary>
/// A wrap fuction which used to create the reinforcement.
/// </summary>
/// <param name="rebarType">The element of RebarBarType</param>
/// <param name="startHook">The element of start RebarHookType</param>
/// <param name="endHook">The element of end RebarHookType</param>
/// <param name="geomInfo">The goemetry information of the rebar</param>
/// <param name="startOrient">An Integer defines the orientation of the start hook</param>
/// <param name="endOrient">An Integer defines the orientation of the end hook</param>
/// <returns></returns>
protected Rebar PlaceRebars(RebarBarType rebarType, RebarHookType startHook,
RebarHookType endHook, RebarGeometry geomInfo,
RebarHookOrientation startOrient, RebarHookOrientation endOrient)
{
Autodesk.Revit.DB.XYZ normal = geomInfo.Normal; // the direction of rebar distribution
IList<Curve> curves = geomInfo.Curves; // the shape of the rebar curves
// Invoke the NewRebar() method to create rebar
Rebar createdRebar = Rebar.CreateFromCurves(m_revitDoc, Autodesk.Revit.DB.Structure.RebarStyle.Standard, rebarType, startHook, endHook,
m_hostObject, normal, curves,
startOrient, endOrient, false, true);
if (null == createdRebar) // Assert the creation is successful
{
return null;
}
// Change the rebar number and spacing properties to the user wanted
SetRebarSpaceAndNumber(createdRebar, geomInfo.RebarNumber, geomInfo.RebarSpacing);
return createdRebar;
}
/// <summary>
/// get all the hook types in current project, and store in m_hookTypes data
/// </summary>
/// <param name="commandData">the ExternalCommandData reference</param>
/// <returns>true if some hook types can be gotton, otherwise false</returns>
private bool GetHookTypes(ExternalCommandData commandData)
{
// Initialize the m_hookTypes which used to store all hook types.
RebarHookTypeSet hookTypes = commandData.Application.ActiveUIDocument.Document.RebarHookTypes;
foreach (RebarHookType hookType in hookTypes)
{
m_hookTypes.Add(hookType);
}
// If no hook types in revit return false, otherwise true
return (0 == m_hookTypes.Count) ? false : true;
}
/// <summary>
/// get all the rebar types in current project, and store in m_rebarTypes data
/// </summary>
/// <param name="commandData">the ExternalCommandData reference</param>
/// <returns>true if some rebar types can be gotton, otherwise false</returns>
private bool GetRebarTypes(ExternalCommandData commandData)
{
// Initialize the m_rebarTypes which used to store all rebar types.
// Get all rebar types in revit and add them in m_rebarTypes
RebarBarTypeSet rebarTypes = commandData.Application.ActiveUIDocument.Document.RebarBarTypes;
foreach (RebarBarType barType in rebarTypes)
{
m_rebarTypes.Add(barType);
}
// If no rebar types in revit return false, otherwise true
return (0 == m_rebarTypes.Count) ? false : true;
}
}
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
{
/// <summary>
/// Manage asset transactions for a single agent.
/// </summary>
public class AgentAssetTransactions
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Fields
private bool m_dumpAssetsToFile;
public AssetTransactionModule Manager;
public UUID UserID;
public Dictionary<UUID, AssetXferUploader> XferUploaders = new Dictionary<UUID, AssetXferUploader>();
// Methods
public AgentAssetTransactions(UUID agentID, AssetTransactionModule manager, bool dumpAssetsToFile)
{
UserID = agentID;
Manager = manager;
m_dumpAssetsToFile = dumpAssetsToFile;
}
private void CleanupCallback(object state)
{
lock (XferUploaders)
{
List<UUID> expiredUploaders = new List<UUID>();
foreach (KeyValuePair<UUID,AssetXferUploader> kvp in XferUploaders)
{
AssetXferUploader uploader = kvp.Value;
if ((DateTime.Now - uploader.LastAccess).TotalMinutes > 10)
{
UUID transactionID = kvp.Key;
expiredUploaders.Add(transactionID);
m_log.WarnFormat("[ASSET TRANSACTIONS]: Timeout on asset upload for transaction {0}", transactionID);
}
}
foreach (UUID transactionID in expiredUploaders)
{
XferUploaders.Remove(transactionID);
}
}
}
static Timer cleanupTimer = null;
public AssetXferUploader RequestXferUploader(UUID transactionID)
{
lock (XferUploaders)
{
if (!XferUploaders.ContainsKey(transactionID))
{
AssetXferUploader uploader = new AssetXferUploader(this, m_dumpAssetsToFile);
if (uploader != null)
{
XferUploaders.Add(transactionID, uploader);
if (cleanupTimer == null)
cleanupTimer = new Timer(CleanupCallback, null, 0, 60000); // once per minute
}
return uploader;
}
return null;
}
}
public void HandleXfer(ulong xferID, uint packetID, byte[] data)
{
lock (XferUploaders)
{
foreach (AssetXferUploader uploader in XferUploaders.Values)
{
if (uploader.XferID == xferID)
{
if (uploader.HandleXferPacket(xferID, packetID, data))
{
// returns true when the xfer is complete
// signal the item update to check for completion
Monitor.PulseAll(XferUploaders);
}
break;
}
}
}
}
public void RequestCreateInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID,
uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask)
{
AssetXferUploader uploader = null;
lock (XferUploaders)
{
XferUploaders.TryGetValue(transactionID, out uploader);
}
if (uploader != null)
{
uploader.RequestCreateInventoryItem(remoteClient, transactionID, folderID,
callbackID, description, name, invType, type,
wearableType, nextOwnerMask);
}
}
private AssetXferUploader GetTransactionUploader(UUID transactionID)
{
lock (XferUploaders)
{
AssetXferUploader value = null;
if (XferUploaders.TryGetValue(transactionID, out value))
return value;
}
return null;
}
public bool RequestUpdateTaskInventoryItem(
IClientAPI remoteClient, SceneObjectPart part, UUID transactionID, TaskInventoryItem item)
{
AssetXferUploader uploader = GetTransactionUploader(transactionID);
if (uploader == null)
{
m_log.WarnFormat("[ASSET TRANSACTIONS]: Transaction {0} NOT FOUND (duplicate removed?) for inventory item update {1}", transactionID, item.Name);
return false;
}
// This may complete now if upload complete, or later when the upload completes.
uploader.TriggerWhenUploadComplete(delegate(AssetBase asset)
{
// This upload transaction is complete.
XferUploaders.Remove(transactionID);
if (asset == null)
return; // UpdateItem() not called
m_log.DebugFormat(
"[ASSET TRANSACTIONS]: Updating task item {0} in {1} with asset in transaction {2}",
item.Name, part.Name, transactionID);
asset.Name = item.Name;
asset.Description = item.Description;
asset.Type = (sbyte)item.Type;
try
{
Manager.MyScene.CommsManager.AssetCache.AddAsset(asset, AssetRequestInfo.GenericNetRequest());
if (part.Inventory.UpdateTaskInventoryItemAsset(part.UUID, item.ItemID, asset.FullID))
{
part.GetProperties(remoteClient);
}
}
catch (AssetServerException e)
{
remoteClient.SendAgentAlertMessage("Unable to upload asset. Please try again later.", false);
m_log.ErrorFormat("[ASSET TRANSACTIONS] Unable to update task item due to asset server error {0}", e);
}
});
// We at least found an uploader with that transaction ID.
return true;
}
public bool RequestUpdateInventoryItem(IClientAPI remoteClient, UUID transactionID, InventoryItemBase item)
{
AssetXferUploader uploader = GetTransactionUploader(transactionID);
if (uploader == null)
{
m_log.WarnFormat("[ASSET TRANSACTIONS]: Transaction {0} NOT FOUND (duplicate removed?) for inventory item update {1}", transactionID, item.Name);
return false;
}
CachedUserInfo userInfo = Manager.MyScene.CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId);
if (userInfo == null)
{
m_log.WarnFormat("[ASSET TRANSACTIONS]: Could not find user {0} for transaction {1} for inventory update {2}",
remoteClient.AgentId, transactionID, item.Name);
return false;
}
// This may complete now if upload complete, or later when the upload completes.
uploader.TriggerWhenUploadComplete(delegate(AssetBase asset)
{
// This upload transaction is complete.
XferUploaders.Remove(transactionID);
UUID assetID = UUID.Combine(transactionID, remoteClient.SecureSessionId);
if (asset == null || asset.FullID != assetID)
{
m_log.ErrorFormat("[ASSETS]: RequestUpdateInventoryItem wrong asset ID or not found {0}", asset == null ? "null" : asset.FullID.ToString());
return;
}
// Assets never get updated, new ones get created
UUID oldID = asset.FullID;
asset.FullID = UUID.Random();
asset.Name = item.Name;
asset.Description = item.Description;
asset.Type = (sbyte)item.AssetType;
try
{
m_log.DebugFormat("[ASSETS]: RequestUpdateInventoryItem for transaction {0}, new asset {1} -> {2}", transactionID, oldID, asset.FullID);
Manager.MyScene.CommsManager.AssetCache.AddAsset(asset, AssetRequestInfo.GenericNetRequest());
}
catch (AssetServerException e)
{
remoteClient.SendAgentAlertMessage("Unable to upload asset. Please try again later.", false);
m_log.ErrorFormat("[ASSET TRANSACTIONS] Creation of asset failed {0}", e);
return;
}
item.AssetID = asset.FullID;
//wait for completion of the write to avoid reversion
ManualResetEventSlim waitEvent = new ManualResetEventSlim();
remoteClient.HandleWithInventoryWriteThread(() =>
{
// Update the asset ID
userInfo.UpdateItem(item);
waitEvent.Set();
});
waitEvent.Wait();
waitEvent.Dispose();
});
return true; // userInfo item was updated
}
}
}
| |
using Kazyx.RemoteApi;
using Kazyx.RemoteApi.Camera;
using Kazyx.WPPMM.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
namespace Kazyx.WPPMM.CameraManager
{
public class CameraStatus : INotifyPropertyChanged
{
/// <summary>
/// returnes true if it's possible to connect.
/// (device info has got correctly)
/// </summary>
public bool isAvailableConnecting
{
get;
set;
}
private DeviceType _DeviceType = DeviceType.UNDEFINED;
public DeviceType DeviceType
{
set { _DeviceType = value; }
get { return _DeviceType; }
}
private ServerVersion version = ServerVersion.CreateDefault();
public ServerVersion Version
{
set
{
version = value;
OnPropertyChanged("IsRestrictedApiVisible");
OnPropertyChanged("AvailableApis");
}
get
{
if (version == null)
{
version = ServerVersion.CreateDefault();
}
return version;
}
}
public Visibility IsRestrictedApiVisible
{
get { return Version.IsLiberated ? Visibility.Visible : Visibility.Collapsed; }
}
public enum AutoFocusType
{
None,
HalfPress,
Touch,
}
private Dictionary<string, List<string>> _SupportedApis = null;
public Dictionary<string, List<string>> SupportedApis
{
get { return (_SupportedApis == null) ? new Dictionary<string, List<string>>() : _SupportedApis; }
set
{
if (DeviceType == DeviceType.DSC_QX10) // QX10 firmware v3.00 has bug in the response of getMethodTypes.
{
value.Remove("setFocusMode");
}
_SupportedApis = value;
OnPropertyChanged("MethodTypes");
}
}
public bool IsSupported(string apiName)
{
return SupportedApis.ContainsKey(apiName);
}
public bool IsSupported(string apiName, string version)
{
return SupportedApis.ContainsKey(apiName) && SupportedApis[apiName].Contains(version);
}
public void Init()
{
_init();
}
public CameraStatus()
{
_init();
InitEventParams();
}
private void _init()
{
isAvailableConnecting = false;
StorageAccessSupported = false;
SupportedApis = new Dictionary<string, List<string>>();
}
public void InitEventParams()
{
ProgramShiftActivated = false;
EvInfo = null;
ISOSpeedRate = null;
ShutterSpeed = null;
ExposureMode = null;
ShootMode = null;
SelfTimer = null;
PostviewSizeInfo = null;
FocusStatus = null;
IsLiveviewAvailable = false;
IsLiveviewFrameInfoAvailable = false;
ZoomInfo = null;
Status = EventParam.NotReady;
AvailableApis = null;
AfType = AutoFocusType.None;
}
static readonly IEnumerable<string> RestrictedApiSet =
new string[]{
"actHalfPressShutter",
"setExposureCompensation",
"setTouchAFPosition",
"setExposureMode",
"setFNumber",
"setShutterSpeed",
"setIsoSpeedRate",
"setWhiteBalance",
"setStillSize",
"setBeepMode",
"setMovieQuality",
"setViewAngle",
"setSteadyMode",
"setCurrentTime",
};
public bool IsRestrictedApi(string apiName)
{
foreach (var api in RestrictedApiSet)
{
if (apiName == api)
{
return true;
}
}
return false;
}
private string[] _AvailableApis;
public string[] AvailableApis
{
set
{
_AvailableApis = value;
if (value != null)
AvailableApiList = new List<string>(value);
else
AvailableApiList = new List<string>();
OnPropertyChanged("AvailableApis");
if (IsAvailable("setLiveviewFrameInfo"))
{
this.IsLiveviewFrameInfoAvailable = true;
}
else
{
this.IsLiveviewFrameInfoAvailable = false;
}
}
get { return _AvailableApis; }
}
private List<string> AvailableApiList = new List<string>();
public bool IsAvailable(string apiName)
{
if (!Version.IsLiberated && IsRestrictedApi(apiName))
{
return false;
}
return AvailableApiList.Contains(apiName);
}
private string _Status = EventParam.NotReady;
public string Status
{
set
{
if (value != _Status)
{
_Status = value;
OnPropertyChanged("Status");
}
}
get { return _Status; }
}
private ZoomInfo _ZoomInfo = null;
public ZoomInfo ZoomInfo
{
set
{
_ZoomInfo = value;
OnPropertyChanged("ZoomInfo");
}
get { return _ZoomInfo; }
}
private bool _IsLiveviewAvailable = false;
public bool IsLiveviewAvailable
{
set
{
DebugUtil.Log("isLiveViewAvailableSet: " + value);
if (_IsLiveviewAvailable != value)
{
OnPropertyChanged("IsLiveviewAvailable");
_IsLiveviewAvailable = value;
if (LiveviewAvailabilityNotifier != null)
{
LiveviewAvailabilityNotifier.Invoke(value);
}
}
}
get
{
return _IsLiveviewAvailable;
}
}
public Action<bool> LiveviewAvailabilityNotifier;
private bool _IsFocusFrameInfoAvailable = false;
public bool IsLiveviewFrameInfoAvailable
{
set
{
DebugUtil.Log("IsFocusFrameInfoAvailable set: " + value);
if (_IsFocusFrameInfoAvailable != value)
{
_IsFocusFrameInfoAvailable = value;
OnPropertyChanged("IsFocusFrameInfoAvailable");
if (LiveviewFrameAvailablityNotifier != null)
{
LiveviewFrameAvailablityNotifier.Invoke(value);
}
}
}
get
{
return _IsFocusFrameInfoAvailable;
}
}
public Action<bool> LiveviewFrameAvailablityNotifier;
private Capability<string> _PostviewSizeInfo;
public Capability<string> PostviewSizeInfo
{
set
{
_PostviewSizeInfo = value;
OnPropertyChanged("PostviewSize");
}
get { return _PostviewSizeInfo; }
}
private Capability<int> _SelfTimer;
public Capability<int> SelfTimer
{
set
{
_SelfTimer = value;
OnPropertyChanged("SelfTimer");
}
get { return _SelfTimer; }
}
private ExtendedInfo<string> _ShootMode;
public ExtendedInfo<string> ShootMode
{
set
{
string previous = null;
if (_ShootMode != null)
{
previous = _ShootMode.Current;
}
_ShootMode = value;
if (_ShootMode != null)
{
_ShootMode.previous = previous;
}
OnPropertyChanged("ShootMode");
OnPropertyChanged("LiveviewScreenVisibility");
OnPropertyChanged("AudioScreenVisibility");
if (value != null && value.Current != null & CurrentShootModeNotifier != null)
{
CurrentShootModeNotifier.Invoke(value.Current);
}
}
get { return _ShootMode; }
}
private Capability<string> _ExposureMode;
public Capability<string> ExposureMode
{
set
{
_ExposureMode = value;
OnPropertyChanged("ExposureMode");
}
get { return _ExposureMode; }
}
private Capability<string> _ShutterSpeed;
public Capability<string> ShutterSpeed
{
set
{
_ShutterSpeed = value;
OnPropertyChanged("ShutterSpeed");
}
get { return _ShutterSpeed; }
}
private Capability<string> _ISOSpeedRate;
public Capability<string> ISOSpeedRate
{
set
{
_ISOSpeedRate = value;
OnPropertyChanged("ISOSpeedRate");
}
get { return _ISOSpeedRate; }
}
private Capability<string> _FNumber;
public Capability<string> FNumber
{
set
{
_FNumber = value;
OnPropertyChanged("FNumber");
}
get { return _FNumber; }
}
private Capability<string> _BeepMode;
public Capability<string> BeepMode
{
set
{
_BeepMode = value;
OnPropertyChanged("BeepMode");
}
get { return _BeepMode; }
}
private Capability<string> _SteadyMode;
public Capability<string> SteadyMode
{
set
{
_SteadyMode = value;
OnPropertyChanged("SteadyMode");
}
get { return _SteadyMode; }
}
private Capability<int> _ViewAngle;
public Capability<int> ViewAngle
{
set
{
_ViewAngle = value;
OnPropertyChanged("ViewAngle");
}
get { return _ViewAngle; }
}
private Capability<string> _MovieQuality;
public Capability<string> MovieQuality
{
set
{
_MovieQuality = value;
OnPropertyChanged("MovieQuality");
}
get { return _MovieQuality; }
}
private Capability<StillImageSize> _StillSize;
public Capability<StillImageSize> StillImageSize
{
set
{
_StillSize = value;
OnPropertyChanged("StillImageSize");
}
get { return _StillSize; }
}
private Capability<string> _FlashMode;
public Capability<string> FlashMode
{
set
{
_FlashMode = value;
OnPropertyChanged("FlashMode");
}
get
{
return _FlashMode;
}
}
private Capability<string> _FocusMode;
public Capability<string> FocusMode
{
set
{
_FocusMode = value;
OnPropertyChanged("FocusMode");
}
get
{
return _FocusMode;
}
}
private TouchFocusStatus _TouchFocusStatus;
public TouchFocusStatus TouchFocusStatus
{
set
{
_TouchFocusStatus = value;
OnPropertyChanged("TouchFocusStatus");
}
get
{
return _TouchFocusStatus;
}
}
private Capability<string> _WhiteBalance;
public Capability<string> WhiteBalance
{
set
{
_WhiteBalance = value;
OnPropertyChanged("WhiteBalance");
OnPropertyChanged("ColorTemperture");
}
get { return _WhiteBalance; }
}
private int _ColorTemperture = -1;
public int ColorTemperture
{
set
{
_ColorTemperture = value;
OnPropertyChanged("ColorTemperture");
}
get { return _ColorTemperture; }
}
private Dictionary<string, int[]> _ColorTempertureCandidates;
public Dictionary<string, int[]> ColorTempertureCandidates
{
set
{
_ColorTempertureCandidates = value;
OnPropertyChanged("ColorTemperture");
}
get { return _ColorTempertureCandidates; }
}
private EvCapability _EvInfo;
public EvCapability EvInfo
{
set
{
_EvInfo = value;
OnPropertyChanged("EvInfo");
}
get { return _EvInfo; }
}
private List<StorageInfo> _Storages;
public List<StorageInfo> Storages
{
set
{
_Storages = value;
OnPropertyChanged("Storages");
}
get { return _Storages; }
}
private string _LiveviewOrientation;
public string LiveviewOrientation
{
set
{
_LiveviewOrientation = value;
OnPropertyChanged("LiveviewOrientation");
}
get { return _LiveviewOrientation == null ? Orientation.Straight : _LiveviewOrientation; }
}
private string[] _PictureUrls;
public string[] PictureUrls
{
set
{
_PictureUrls = value;
OnPropertyChanged("PictureUrls");
}
get { return _PictureUrls; }
}
private bool _ProgramShiftActivated = false;
public bool ProgramShiftActivated
{
set
{
_ProgramShiftActivated = value;
OnPropertyChanged("ProgramShiftActivated");
}
get { return _ProgramShiftActivated; }
}
private ProgramShiftRange _ProgramShiftRange;
public ProgramShiftRange ProgramShiftRange
{
set
{
_ProgramShiftRange = value;
OnPropertyChanged("ProgramShiftRange");
}
get
{
return _ProgramShiftRange;
}
}
public void ClearFocusStatus()
{
FocusStatus = FocusState.Released;
}
private string _FocusStatus;
public string FocusStatus
{
set
{
_FocusStatus = value;
OnPropertyChanged("FocusStatus");
}
get { return _FocusStatus; }
}
public AutoFocusType AfType { get; set; }
private Capability<string> _ZoomSetting;
public Capability<string> ZoomSetting
{
set
{
_ZoomSetting = value;
OnPropertyChanged("ZoomSetting");
}
get { return _ZoomSetting; }
}
private Capability<string> _StillQuality;
public Capability<string> StillQuality
{
set
{
_StillQuality = value;
OnPropertyChanged("StillQuality");
}
get { return _StillQuality; }
}
private Capability<string> _ContShootingMode;
public Capability<string> ContShootingMode
{
set
{
_ContShootingMode = value;
OnPropertyChanged("ContShootingMode");
}
get { return _ContShootingMode; }
}
private Capability<string> _ContShootingSpeed;
public Capability<string> ContShootingSpeed
{
set
{
_ContShootingSpeed = value;
OnPropertyChanged("ContShootingSpeed");
}
get { return _ContShootingSpeed; }
}
private List<ContShootingResult> _ContShootingResult;
public List<ContShootingResult> ContShootingResult
{
set
{
_ContShootingResult = value;
OnPropertyChanged("ContShootingResult");
}
get { return _ContShootingResult; }
}
private Capability<string> _FlipMode;
public Capability<string> FlipMode
{
set
{
_FlipMode = value;
OnPropertyChanged("FlipMode");
}
get { return _FlipMode; }
}
private Capability<string> _SceneSelection;
public Capability<string> SceneSelection
{
set
{
_SceneSelection = value;
OnPropertyChanged("SceneSelection");
}
get { return _SceneSelection; }
}
private Capability<string> _IntervalTime;
public Capability<string> IntervalTime
{
set
{
_IntervalTime = value;
OnPropertyChanged("IntervalTime");
}
get { return _IntervalTime; }
}
private Capability<string> _ColorSetting;
public Capability<string> ColorSetting
{
set
{
_ColorSetting = value;
OnPropertyChanged("ColorSetting");
}
get { return _ColorSetting; }
}
private Capability<string> _MovieFileFormat;
public Capability<string> MovieFileFormat
{
set
{
_MovieFileFormat = value;
OnPropertyChanged("MovieFileFormat");
}
get { return _MovieFileFormat; }
}
private Capability<string> _InfraredRemoteControl;
public Capability<string> InfraredRemoteControl
{
set
{
_InfraredRemoteControl = value;
OnPropertyChanged("InfraredRemoteControl");
}
get { return _InfraredRemoteControl; }
}
private Capability<string> _TvColorSystem;
public Capability<string> TvColorSystem
{
set
{
_TvColorSystem = value;
OnPropertyChanged("TvColorSystem");
}
get { return _TvColorSystem; }
}
private string _TrackingFocusStatus;
public string TrackingFocusStatus
{
set
{
_TrackingFocusStatus = value;
OnPropertyChanged("TrackingFocusStatus");
}
get { return _TrackingFocusStatus; }
}
private Capability<string> _TrackingFocus;
public Capability<string> TrackingFocus
{
set
{
_TrackingFocus = value;
OnPropertyChanged("TrackingFocus");
}
get { return _TrackingFocus; }
}
private List<BatteryInfo> _BatteryInfo;
public List<BatteryInfo> BatteryInfo
{
set
{
_BatteryInfo = value;
OnPropertyChanged("BatteryInfo");
}
get { return _BatteryInfo; }
}
private int _RecordingTimeSec;
public int RecordingTimeSec
{
set
{
_RecordingTimeSec = value;
OnPropertyChanged("RecordingTimeSec");
}
get { return _RecordingTimeSec; }
}
private int _NumberOfShots;
public int NumberOfShots
{
set
{
_NumberOfShots = value;
OnPropertyChanged("NumberOfShots");
}
get { return _NumberOfShots; }
}
private Capability<int> _AutoPowerOff;
public Capability<int> AutoPowerOff
{
set
{
_AutoPowerOff = value;
OnPropertyChanged("AutoPowerOff");
}
get { return _AutoPowerOff; }
}
private bool _StorageAccessSupported = false;
public bool StorageAccessSupported
{
set
{
_StorageAccessSupported = value;
OnPropertyChanged("StorageAccessSupported");
OnPropertyChanged("StorageAccessVisibility");
}
get { return _StorageAccessSupported; }
}
public Visibility LiveviewScreenVisibility
{
get
{
if (_ShootMode == null)
{
return Visibility.Collapsed;
}
if (_ShootMode.Current == ShootModeParam.Audio)
{
return Visibility.Collapsed;
}
else
{
return Visibility.Visible;
}
}
}
public Visibility AudioScreenVisibility
{
get
{
if (_ShootMode == null)
{
return Visibility.Collapsed;
}
if (_ShootMode.Current == ShootModeParam.Audio)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
}
public Action<string> CurrentShootModeNotifier;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
// DebugUtil.Log("OnPropertyChanged: " + name);
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
});
}
catch (COMException)
{
}
}
}
public class ExtendedInfo<T> : Capability<T>
{
public T previous { set; get; }
public ExtendedInfo(Capability<T> basic)
{
this.Candidates = basic.Candidates;
this.Current = basic.Current;
}
public ExtendedInfo(Capability<T> basic, T previous)
{
this.Candidates = basic.Candidates;
this.Current = basic.Current;
this.previous = previous;
}
}
}
| |
using J2N;
using J2N.Text;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using BitSet = Lucene.Net.Util.OpenBitSet;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Util.Fst
{
/*
* 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.
*/
/// <summary>
/// Static helper methods.
/// <para/>
/// @lucene.experimental
/// </summary>
public static class Util // LUCENENET specific - made static // LUCENENET TODO: Fix naming conflict with containing namespace
{
/// <summary>
/// Looks up the output for this input, or <c>null</c> if the
/// input is not accepted.
/// </summary>
public static T Get<T>(FST<T> fst, Int32sRef input)
{
// TODO: would be nice not to alloc this on every lookup
var arc = fst.GetFirstArc(new FST.Arc<T>());
var fstReader = fst.GetBytesReader();
// Accumulate output as we go
T output = fst.Outputs.NoOutput;
for (int i = 0; i < input.Length; i++)
{
if (fst.FindTargetArc(input.Int32s[input.Offset + i], arc, arc, fstReader) == null)
{
return default;
}
output = fst.Outputs.Add(output, arc.Output);
}
if (arc.IsFinal)
{
return fst.Outputs.Add(output, arc.NextFinalOutput);
}
else
{
return default;
}
}
// TODO: maybe a CharsRef version for BYTE2
/// <summary>
/// Looks up the output for this input, or <c>null</c> if the
/// input is not accepted
/// </summary>
public static T Get<T>(FST<T> fst, BytesRef input)
{
if (Debugging.AssertsEnabled) Debugging.Assert(fst.InputType == FST.INPUT_TYPE.BYTE1);
var fstReader = fst.GetBytesReader();
// TODO: would be nice not to alloc this on every lookup
var arc = fst.GetFirstArc(new FST.Arc<T>());
// Accumulate output as we go
T output = fst.Outputs.NoOutput;
for (int i = 0; i < input.Length; i++)
{
if (fst.FindTargetArc(input.Bytes[i + input.Offset] & 0xFF, arc, arc, fstReader) == null)
{
return default;
}
output = fst.Outputs.Add(output, arc.Output);
}
if (arc.IsFinal)
{
return fst.Outputs.Add(output, arc.NextFinalOutput);
}
else
{
return default;
}
}
/// <summary>
/// Reverse lookup (lookup by output instead of by input),
/// in the special case when your FSTs outputs are
/// strictly ascending. This locates the input/output
/// pair where the output is equal to the target, and will
/// return <c>null</c> if that output does not exist.
///
/// <para/>NOTE: this only works with <see cref="T:FST{long?}"/>, only
/// works when the outputs are ascending in order with
/// the inputs.
/// For example, simple ordinals (0, 1,
/// 2, ...), or file offets (when appending to a file)
/// fit this.
/// </summary>
public static Int32sRef GetByOutput(FST<long?> fst, long targetOutput)
{
var @in = fst.GetBytesReader();
// TODO: would be nice not to alloc this on every lookup
FST.Arc<long?> arc = fst.GetFirstArc(new FST.Arc<long?>());
FST.Arc<long?> scratchArc = new FST.Arc<long?>();
Int32sRef result = new Int32sRef();
return GetByOutput(fst, targetOutput, @in, arc, scratchArc, result);
}
/// <summary>
/// Expert: like <see cref="Util.GetByOutput(FST{long?}, long)"/> except reusing
/// <see cref="FST.BytesReader"/>, initial and scratch Arc, and result.
/// </summary>
public static Int32sRef GetByOutput(FST<long?> fst, long targetOutput, FST.BytesReader @in, FST.Arc<long?> arc, FST.Arc<long?> scratchArc, Int32sRef result)
{
long output = arc.Output.Value;
int upto = 0;
//System.out.println("reverseLookup output=" + targetOutput);
while (true)
{
//System.out.println("loop: output=" + output + " upto=" + upto + " arc=" + arc);
if (arc.IsFinal)
{
long finalOutput = output + arc.NextFinalOutput.Value;
//System.out.println(" isFinal finalOutput=" + finalOutput);
if (finalOutput == targetOutput)
{
result.Length = upto;
//System.out.println(" found!");
return result;
}
else if (finalOutput > targetOutput)
{
//System.out.println(" not found!");
return null;
}
}
if (FST<long?>.TargetHasArcs(arc))
{
//System.out.println(" targetHasArcs");
if (result.Int32s.Length == upto)
{
result.Grow(1 + upto);
}
fst.ReadFirstRealTargetArc(arc.Target, arc, @in);
if (arc.BytesPerArc != 0)
{
int low = 0;
int high = arc.NumArcs - 1;
int mid = 0;
//System.out.println("bsearch: numArcs=" + arc.numArcs + " target=" + targetOutput + " output=" + output);
bool exact = false;
while (low <= high)
{
mid = (int)((uint)(low + high) >> 1);
@in.Position = arc.PosArcsStart;
@in.SkipBytes(arc.BytesPerArc * mid);
var flags = (sbyte)@in.ReadByte();
fst.ReadLabel(@in);
long minArcOutput;
if ((flags & FST.BIT_ARC_HAS_OUTPUT) != 0)
{
long arcOutput = fst.Outputs.Read(@in).Value;
minArcOutput = output + arcOutput;
}
else
{
minArcOutput = output;
}
if (minArcOutput == targetOutput)
{
exact = true;
break;
}
else if (minArcOutput < targetOutput)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
if (high == -1)
{
return null;
}
else if (exact)
{
arc.ArcIdx = mid - 1;
}
else
{
arc.ArcIdx = low - 2;
}
fst.ReadNextRealArc(arc, @in);
result.Int32s[upto++] = arc.Label;
output += arc.Output.Value;
}
else
{
FST.Arc<long?> prevArc = null;
while (true)
{
//System.out.println(" cycle label=" + arc.label + " output=" + arc.output);
// this is the min output we'd hit if we follow
// this arc:
long minArcOutput = output + arc.Output.Value;
if (minArcOutput == targetOutput)
{
// Recurse on this arc:
//System.out.println(" match! break");
output = minArcOutput;
result.Int32s[upto++] = arc.Label;
break;
}
else if (minArcOutput > targetOutput)
{
if (prevArc == null)
{
// Output doesn't exist
return null;
}
else
{
// Recurse on previous arc:
arc.CopyFrom(prevArc);
result.Int32s[upto++] = arc.Label;
output += arc.Output.Value;
//System.out.println(" recurse prev label=" + (char) arc.label + " output=" + output);
break;
}
}
else if (arc.IsLast)
{
// Recurse on this arc:
output = minArcOutput;
//System.out.println(" recurse last label=" + (char) arc.label + " output=" + output);
result.Int32s[upto++] = arc.Label;
break;
}
else
{
// Read next arc in this node:
prevArc = scratchArc;
prevArc.CopyFrom(arc);
//System.out.println(" after copy label=" + (char) prevArc.label + " vs " + (char) arc.label);
fst.ReadNextRealArc(arc, @in);
}
}
}
}
else
{
//System.out.println(" no target arcs; not found!");
return null;
}
}
}
/// <summary>
/// Represents a path in TopNSearcher.
/// <para/>
/// @lucene.experimental
/// </summary>
public class FSTPath<T>
{
public FST.Arc<T> Arc { get; set; }
public T Cost { get; set; }
public Int32sRef Input { get; private set; }
/// <summary>
/// Sole constructor </summary>
public FSTPath(T cost, FST.Arc<T> arc, Int32sRef input)
{
this.Arc = (new FST.Arc<T>()).CopyFrom(arc);
this.Cost = cost;
this.Input = input;
}
public override string ToString()
{
return "input=" + Input + " cost=" + Cost;
}
}
/// <summary>
/// Compares first by the provided comparer, and then
/// tie breaks by <see cref="FSTPath{T}.Input"/>.
/// </summary>
private class TieBreakByInputComparer<T> : IComparer<FSTPath<T>>
{
internal readonly IComparer<T> comparer;
public TieBreakByInputComparer(IComparer<T> comparer)
{
this.comparer = comparer;
}
public virtual int Compare(FSTPath<T> a, FSTPath<T> b)
{
int cmp = comparer.Compare(a.Cost, b.Cost);
if (cmp == 0)
{
return a.Input.CompareTo(b.Input);
}
else
{
return cmp;
}
}
}
/// <summary>
/// Utility class to find top N shortest paths from start
/// point(s).
/// </summary>
public class TopNSearcher<T>
{
private readonly FST<T> fst;
private readonly FST.BytesReader bytesReader;
private readonly int topN;
private readonly int maxQueueDepth;
private readonly FST.Arc<T> scratchArc = new FST.Arc<T>();
internal readonly IComparer<T> comparer;
internal JCG.SortedSet<FSTPath<T>> queue = null;
private readonly object syncLock = new object();
/// <summary>
/// Creates an unbounded TopNSearcher </summary>
/// <param name="fst"> the <see cref="Lucene.Net.Util.Fst.FST{T}"/> to search on </param>
/// <param name="topN"> the number of top scoring entries to retrieve </param>
/// <param name="maxQueueDepth"> the maximum size of the queue of possible top entries </param>
/// <param name="comparer"> the comparer to select the top N </param>
public TopNSearcher(FST<T> fst, int topN, int maxQueueDepth, IComparer<T> comparer)
{
this.fst = fst;
this.bytesReader = fst.GetBytesReader();
this.topN = topN;
this.maxQueueDepth = maxQueueDepth;
this.comparer = comparer;
queue = new JCG.SortedSet<FSTPath<T>>(new TieBreakByInputComparer<T>(comparer));
}
/// <summary>
/// If back plus this arc is competitive then add to queue:
/// </summary>
protected virtual void AddIfCompetitive(FSTPath<T> path)
{
if (Debugging.AssertsEnabled) Debugging.Assert(queue != null);
T cost = fst.Outputs.Add(path.Cost, path.Arc.Output);
//System.out.println(" addIfCompetitive queue.size()=" + queue.size() + " path=" + path + " + label=" + path.arc.label);
if (queue.Count == maxQueueDepth)
{
FSTPath<T> bottom = queue.Max;
int comp = comparer.Compare(cost, bottom.Cost);
if (comp > 0)
{
// Doesn't compete
return;
}
else if (comp == 0)
{
// Tie break by alpha sort on the input:
path.Input.Grow(path.Input.Length + 1);
path.Input.Int32s[path.Input.Length++] = path.Arc.Label;
int cmp = bottom.Input.CompareTo(path.Input);
path.Input.Length--;
// We should never see dups:
if (Debugging.AssertsEnabled) Debugging.Assert(cmp != 0);
if (cmp < 0)
{
// Doesn't compete
return;
}
}
// Competes
}
else
{
// Queue isn't full yet, so any path we hit competes:
}
// copy over the current input to the new input
// and add the arc.label to the end
Int32sRef newInput = new Int32sRef(path.Input.Length + 1);
Array.Copy(path.Input.Int32s, 0, newInput.Int32s, 0, path.Input.Length);
newInput.Int32s[path.Input.Length] = path.Arc.Label;
newInput.Length = path.Input.Length + 1;
FSTPath<T> newPath = new FSTPath<T>(cost, path.Arc, newInput);
queue.Add(newPath);
if (queue.Count == maxQueueDepth + 1)
{
// LUCENENET NOTE: SortedSet doesn't have atomic operations,
// so we need to add some thread safety just in case.
// Perhaps it might make sense to wrap SortedSet into a type
// that provides thread safety.
lock (syncLock)
{
queue.Remove(queue.Max);
}
}
}
/// <summary>
/// Adds all leaving arcs, including 'finished' arc, if
/// the node is final, from this node into the queue.
/// </summary>
public virtual void AddStartPaths(FST.Arc<T> node, T startOutput, bool allowEmptyString, Int32sRef input)
{
// De-dup NO_OUTPUT since it must be a singleton:
if (startOutput.Equals(fst.Outputs.NoOutput))
{
startOutput = fst.Outputs.NoOutput;
}
FSTPath<T> path = new FSTPath<T>(startOutput, node, input);
fst.ReadFirstTargetArc(node, path.Arc, bytesReader);
//System.out.println("add start paths");
// Bootstrap: find the min starting arc
while (true)
{
if (allowEmptyString || path.Arc.Label != FST.END_LABEL)
{
AddIfCompetitive(path);
}
if (path.Arc.IsLast)
{
break;
}
fst.ReadNextArc(path.Arc, bytesReader);
}
}
public virtual TopResults<T> Search()
{
IList<Result<T>> results = new JCG.List<Result<T>>();
//System.out.println("search topN=" + topN);
var fstReader = fst.GetBytesReader();
T NO_OUTPUT = fst.Outputs.NoOutput;
// TODO: we could enable FST to sorting arcs by weight
// as it freezes... can easily do this on first pass
// (w/o requiring rewrite)
// TODO: maybe we should make an FST.INPUT_TYPE.BYTE0.5!?
// (nibbles)
int rejectCount = 0;
// For each top N path:
while (results.Count < topN)
{
//System.out.println("\nfind next path: queue.size=" + queue.size());
FSTPath<T> path;
if (queue == null)
{
// Ran out of paths
//System.out.println(" break queue=null");
break;
}
// Remove top path since we are now going to
// pursue it:
// LUCENENET NOTE: SortedSet doesn't have atomic operations,
// so we need to add some thread safety just in case.
// Perhaps it might make sense to wrap SortedSet into a type
// that provides thread safety.
lock (syncLock)
{
path = queue.Min;
if (path != null)
{
queue.Remove(path);
}
}
if (path == null)
{
// There were less than topN paths available:
//System.out.println(" break no more paths");
break;
}
if (path.Arc.Label == FST.END_LABEL)
{
//System.out.println(" empty string! cost=" + path.cost);
// Empty string!
path.Input.Length--;
results.Add(new Result<T>(path.Input, path.Cost));
continue;
}
if (results.Count == topN - 1 && maxQueueDepth == topN)
{
// Last path -- don't bother w/ queue anymore:
queue = null;
}
//System.out.println(" path: " + path);
// We take path and find its "0 output completion",
// ie, just keep traversing the first arc with
// NO_OUTPUT that we can find, since this must lead
// to the minimum path that completes from
// path.arc.
// For each input letter:
while (true)
{
//System.out.println("\n cycle path: " + path);
fst.ReadFirstTargetArc(path.Arc, path.Arc, fstReader);
// For each arc leaving this node:
bool foundZero = false;
while (true)
{
//System.out.println(" arc=" + (char) path.arc.label + " cost=" + path.arc.output);
// tricky: instead of comparing output == 0, we must
// express it via the comparer compare(output, 0) == 0
if (comparer.Compare(NO_OUTPUT, path.Arc.Output) == 0)
{
if (queue == null)
{
foundZero = true;
break;
}
else if (!foundZero)
{
scratchArc.CopyFrom(path.Arc);
foundZero = true;
}
else
{
AddIfCompetitive(path);
}
}
else if (queue != null)
{
AddIfCompetitive(path);
}
if (path.Arc.IsLast)
{
break;
}
fst.ReadNextArc(path.Arc, fstReader);
}
if (Debugging.AssertsEnabled) Debugging.Assert(foundZero);
if (queue != null)
{
// TODO: maybe we can save this copyFrom if we
// are more clever above... eg on finding the
// first NO_OUTPUT arc we'd switch to using
// scratchArc
path.Arc.CopyFrom(scratchArc);
}
if (path.Arc.Label == FST.END_LABEL)
{
// Add final output:
//Debug.WriteLine(" done!: " + path);
T finalOutput = fst.Outputs.Add(path.Cost, path.Arc.Output);
if (AcceptResult(path.Input, finalOutput))
{
//Debug.WriteLine(" add result: " + path);
results.Add(new Result<T>(path.Input, finalOutput));
}
else
{
rejectCount++;
}
break;
}
else
{
path.Input.Grow(1 + path.Input.Length);
path.Input.Int32s[path.Input.Length] = path.Arc.Label;
path.Input.Length++;
path.Cost = fst.Outputs.Add(path.Cost, path.Arc.Output);
}
}
}
return new TopResults<T>(rejectCount + topN <= maxQueueDepth, results);
}
protected virtual bool AcceptResult(Int32sRef input, T output)
{
return true;
}
}
/// <summary>
/// Holds a single input (<see cref="Int32sRef"/>) + output, returned by
/// <see cref="ShortestPaths"/>.
/// </summary>
public sealed class Result<T>
{
public Int32sRef Input { get; private set; }
public T Output { get; private set; }
public Result(Int32sRef input, T output)
{
this.Input = input;
this.Output = output;
}
}
/// <summary>
/// Holds the results for a top N search using <see cref="TopNSearcher{T}"/>
/// </summary>
public sealed class TopResults<T> : IEnumerable<Result<T>>
{
/// <summary>
/// <c>true</c> iff this is a complete result ie. if
/// the specified queue size was large enough to find the complete list of results. this might
/// be <c>false</c> if the <see cref="TopNSearcher{T}"/> rejected too many results.
/// </summary>
public bool IsComplete { get; private set; }
/// <summary>
/// The top results
/// </summary>
public IList<Result<T>> TopN { get; private set; }
internal TopResults(bool isComplete, IList<Result<T>> topN)
{
this.TopN = topN;
this.IsComplete = isComplete;
}
public IEnumerator<Result<T>> GetEnumerator()
{
return TopN.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
/// <summary>
/// Starting from node, find the top N min cost
/// completions to a final node.
/// </summary>
public static TopResults<T> ShortestPaths<T>(FST<T> fst, FST.Arc<T> fromNode, T startOutput, IComparer<T> comparer, int topN, bool allowEmptyString)
{
// All paths are kept, so we can pass topN for
// maxQueueDepth and the pruning is admissible:
TopNSearcher<T> searcher = new TopNSearcher<T>(fst, topN, topN, comparer);
// since this search is initialized with a single start node
// it is okay to start with an empty input path here
searcher.AddStartPaths(fromNode, startOutput, allowEmptyString, new Int32sRef());
return searcher.Search();
}
/// <summary>
/// Dumps an <see cref="FST{T}"/> to a GraphViz's <c>dot</c> language description
/// for visualization. Example of use:
///
/// <code>
/// using (TextWriter sw = new StreamWriter("out.dot"))
/// {
/// Util.ToDot(fst, sw, true, true);
/// }
/// </code>
///
/// and then, from command line:
///
/// <code>
/// dot -Tpng -o out.png out.dot
/// </code>
///
/// <para/>
/// Note: larger FSTs (a few thousand nodes) won't even
/// render, don't bother. If the FST is > 2.1 GB in size
/// then this method will throw strange exceptions.
/// <para/>
/// See also <a href="http://www.graphviz.org/">http://www.graphviz.org/</a>.
/// </summary>
/// <param name="sameRank">
/// If <c>true</c>, the resulting <c>dot</c> file will try
/// to order states in layers of breadth-first traversal. This may
/// mess up arcs, but makes the output FST's structure a bit clearer.
/// </param>
/// <param name="labelStates">
/// If <c>true</c> states will have labels equal to their offsets in their
/// binary format. Expands the graph considerably.
/// </param>
public static void ToDot<T>(FST<T> fst, TextWriter @out, bool sameRank, bool labelStates)
{
const string expandedNodeColor = "blue";
// this is the start arc in the automaton (from the epsilon state to the first state
// with outgoing transitions.
FST.Arc<T> startArc = fst.GetFirstArc(new FST.Arc<T>());
// A queue of transitions to consider for the next level.
IList<FST.Arc<T>> thisLevelQueue = new JCG.List<FST.Arc<T>>();
// A queue of transitions to consider when processing the next level.
IList<FST.Arc<T>> nextLevelQueue = new JCG.List<FST.Arc<T>>
{
startArc
};
//System.out.println("toDot: startArc: " + startArc);
// A list of states on the same level (for ranking).
IList<int?> sameLevelStates = new JCG.List<int?>();
// A bitset of already seen states (target offset).
BitSet seen = new BitSet();
seen.Set((int)startArc.Target);
// Shape for states.
const string stateShape = "circle";
const string finalStateShape = "doublecircle";
// Emit DOT prologue.
@out.Write("digraph FST {\n");
@out.Write(" rankdir = LR; splines=true; concentrate=true; ordering=out; ranksep=2.5; \n");
if (!labelStates)
{
@out.Write(" node [shape=circle, width=.2, height=.2, style=filled]\n");
}
EmitDotState(@out, "initial", "point", "white", "");
T NO_OUTPUT = fst.Outputs.NoOutput;
var r = fst.GetBytesReader();
// final FST.Arc<T> scratchArc = new FST.Arc<>();
{
string stateColor;
if (fst.IsExpandedTarget(startArc, r))
{
stateColor = expandedNodeColor;
}
else
{
stateColor = null;
}
bool isFinal;
T finalOutput;
if (startArc.IsFinal)
{
isFinal = true;
finalOutput = startArc.NextFinalOutput.Equals(NO_OUTPUT) ? default : startArc.NextFinalOutput;
}
else
{
isFinal = false;
finalOutput = default;
}
EmitDotState(@out, Convert.ToString(startArc.Target), isFinal ? finalStateShape : stateShape, stateColor, finalOutput == null ? "" : fst.Outputs.OutputToString(finalOutput));
}
@out.Write(" initial -> " + startArc.Target + "\n");
int level = 0;
while (nextLevelQueue.Count > 0)
{
// we could double buffer here, but it doesn't matter probably.
//System.out.println("next level=" + level);
thisLevelQueue.AddRange(nextLevelQueue);
nextLevelQueue.Clear();
level++;
@out.Write("\n // Transitions and states at level: " + level + "\n");
while (thisLevelQueue.Count > 0)
{
FST.Arc<T> arc = thisLevelQueue[thisLevelQueue.Count - 1];
thisLevelQueue.RemoveAt(thisLevelQueue.Count - 1);
//System.out.println(" pop: " + arc);
if (FST<T>.TargetHasArcs(arc))
{
// scan all target arcs
//System.out.println(" readFirstTarget...");
long node = arc.Target;
fst.ReadFirstRealTargetArc(arc.Target, arc, r);
//System.out.println(" firstTarget: " + arc);
while (true)
{
//System.out.println(" cycle arc=" + arc);
// Emit the unseen state and add it to the queue for the next level.
if (arc.Target >= 0 && !seen.Get((int)arc.Target))
{
/*
boolean isFinal = false;
T finalOutput = null;
fst.readFirstTargetArc(arc, scratchArc);
if (scratchArc.isFinal() && fst.targetHasArcs(scratchArc)) {
// target is final
isFinal = true;
finalOutput = scratchArc.output == NO_OUTPUT ? null : scratchArc.output;
System.out.println("dot hit final label=" + (char) scratchArc.label);
}
*/
string stateColor;
if (fst.IsExpandedTarget(arc, r))
{
stateColor = expandedNodeColor;
}
else
{
stateColor = null;
}
string finalOutput;
if (arc.NextFinalOutput != null && !arc.NextFinalOutput.Equals(NO_OUTPUT))
{
finalOutput = fst.Outputs.OutputToString(arc.NextFinalOutput);
}
else
{
finalOutput = "";
}
EmitDotState(@out, Convert.ToString(arc.Target), stateShape, stateColor, finalOutput);
// To see the node address, use this instead:
//emitDotState(out, Integer.toString(arc.target), stateShape, stateColor, String.valueOf(arc.target));
seen.Set((int)arc.Target);
nextLevelQueue.Add((new FST.Arc<T>()).CopyFrom(arc));
sameLevelStates.Add((int)arc.Target);
}
string outs;
if (!arc.Output.Equals(NO_OUTPUT))
{
outs = "/" + fst.Outputs.OutputToString(arc.Output);
}
else
{
outs = "";
}
if (!FST<T>.TargetHasArcs(arc) && arc.IsFinal && !arc.NextFinalOutput.Equals(NO_OUTPUT))
{
// Tricky special case: sometimes, due to
// pruning, the builder can [sillily] produce
// an FST with an arc into the final end state
// (-1) but also with a next final output; in
// this case we pull that output up onto this
// arc
outs = outs + "/[" + fst.Outputs.OutputToString(arc.NextFinalOutput) + "]";
}
string arcColor;
if (arc.Flag(FST.BIT_TARGET_NEXT))
{
arcColor = "red";
}
else
{
arcColor = "black";
}
if (Debugging.AssertsEnabled) Debugging.Assert(arc.Label != FST.END_LABEL);
@out.Write(" " + node + " -> " + arc.Target + " [label=\"" + PrintableLabel(arc.Label) + outs + "\"" + (arc.IsFinal ? " style=\"bold\"" : "") + " color=\"" + arcColor + "\"]\n");
// Break the loop if we're on the last arc of this state.
if (arc.IsLast)
{
//System.out.println(" break");
break;
}
fst.ReadNextRealArc(arc, r);
}
}
}
// Emit state ranking information.
if (sameRank && sameLevelStates.Count > 1)
{
@out.Write(" {rank=same; ");
foreach (int state in sameLevelStates)
{
@out.Write(state + "; ");
}
@out.Write(" }\n");
}
sameLevelStates.Clear();
}
// Emit terminating state (always there anyway).
@out.Write(" -1 [style=filled, color=black, shape=doublecircle, label=\"\"]\n\n");
@out.Write(" {rank=sink; -1 }\n");
@out.Write("}\n");
@out.Flush();
}
/// <summary>
/// Emit a single state in the <c>dot</c> language.
/// </summary>
private static void EmitDotState(TextWriter @out, string name, string shape, string color, string label)
{
@out.Write(" " + name
+ " ["
+ (shape != null ? "shape=" + shape : "") + " "
+ (color != null ? "color=" + color : "") + " "
+ (label != null ? "label=\"" + label + "\"" : "label=\"\"") + " "
+ "]\n");
}
/// <summary>
/// Ensures an arc's label is indeed printable (dot uses US-ASCII).
/// </summary>
private static string PrintableLabel(int label)
{
// Any ordinary ascii character, except for " or \, are
// printed as the character; else, as a hex string:
if (label >= 0x20 && label <= 0x7d && label != 0x22 && label != 0x5c) // " OR \
{
return char.ToString((char)label);
}
return "0x" + label.ToString("x", CultureInfo.InvariantCulture);
}
/// <summary>
/// Just maps each UTF16 unit (char) to the <see cref="int"/>s in an
/// <see cref="Int32sRef"/>.
/// </summary>
public static Int32sRef ToUTF16(string s, Int32sRef scratch)
{
int charLimit = s.Length;
scratch.Offset = 0;
scratch.Length = charLimit;
scratch.Grow(charLimit);
for (int idx = 0; idx < charLimit; idx++)
{
scratch.Int32s[idx] = (int)s[idx];
}
return scratch;
}
/// <summary>
/// Decodes the Unicode codepoints from the provided
/// <see cref="ICharSequence"/> and places them in the provided scratch
/// <see cref="Int32sRef"/>, which must not be <c>null</c>, returning it.
/// </summary>
public static Int32sRef ToUTF32(string s, Int32sRef scratch)
{
int charIdx = 0;
int intIdx = 0;
int charLimit = s.Length;
while (charIdx < charLimit)
{
scratch.Grow(intIdx + 1);
int utf32 = Character.CodePointAt(s, charIdx);
scratch.Int32s[intIdx] = utf32;
charIdx += Character.CharCount(utf32);
intIdx++;
}
scratch.Length = intIdx;
return scratch;
}
/// <summary>
/// Decodes the Unicode codepoints from the provided
/// <see cref="T:char[]"/> and places them in the provided scratch
/// <see cref="Int32sRef"/>, which must not be <c>null</c>, returning it.
/// </summary>
public static Int32sRef ToUTF32(char[] s, int offset, int length, Int32sRef scratch)
{
int charIdx = offset;
int intIdx = 0;
int charLimit = offset + length;
while (charIdx < charLimit)
{
scratch.Grow(intIdx + 1);
int utf32 = Character.CodePointAt(s, charIdx, charLimit);
scratch.Int32s[intIdx] = utf32;
charIdx += Character.CharCount(utf32);
intIdx++;
}
scratch.Length = intIdx;
return scratch;
}
/// <summary>
/// Just takes unsigned byte values from the <see cref="BytesRef"/> and
/// converts into an <see cref="Int32sRef"/>.
/// <para/>
/// NOTE: This was toIntsRef() in Lucene
/// </summary>
public static Int32sRef ToInt32sRef(BytesRef input, Int32sRef scratch)
{
scratch.Grow(input.Length);
for (int i = 0; i < input.Length; i++)
{
scratch.Int32s[i] = input.Bytes[i + input.Offset] & 0xFF;
}
scratch.Length = input.Length;
return scratch;
}
/// <summary>
/// Just converts <see cref="Int32sRef"/> to <see cref="BytesRef"/>; you must ensure the
/// <see cref="int"/> values fit into a <see cref="byte"/>.
/// </summary>
public static BytesRef ToBytesRef(Int32sRef input, BytesRef scratch)
{
scratch.Grow(input.Length);
for (int i = 0; i < input.Length; i++)
{
int value = input.Int32s[i + input.Offset];
// NOTE: we allow -128 to 255
if (Debugging.AssertsEnabled) Debugging.Assert(value >= sbyte.MinValue && value <= 255, () => "value " + value + " doesn't fit into byte");
scratch.Bytes[i] = (byte)value;
}
scratch.Length = input.Length;
return scratch;
}
// Uncomment for debugging:
/*
public static <T> void dotToFile(FST<T> fst, String filePath) throws IOException {
Writer w = new OutputStreamWriter(new FileOutputStream(filePath));
toDot(fst, w, true, true);
w.Dispose();
}
*/
/// <summary>
/// Reads the first arc greater or equal that the given label into the provided
/// arc in place and returns it iff found, otherwise return <c>null</c>.
/// </summary>
/// <param name="label"> the label to ceil on </param>
/// <param name="fst"> the fst to operate on </param>
/// <param name="follow"> the arc to follow reading the label from </param>
/// <param name="arc"> the arc to read into in place </param>
/// <param name="in"> the fst's <see cref="FST.BytesReader"/> </param>
public static FST.Arc<T> ReadCeilArc<T>(int label, FST<T> fst, FST.Arc<T> follow, FST.Arc<T> arc, FST.BytesReader @in)
{
// TODO maybe this is a useful in the FST class - we could simplify some other code like FSTEnum?
if (label == FST.END_LABEL)
{
if (follow.IsFinal)
{
if (follow.Target <= 0)
{
arc.Flags = (sbyte)FST.BIT_LAST_ARC;
}
else
{
arc.Flags = 0;
// NOTE: nextArc is a node (not an address!) in this case:
arc.NextArc = follow.Target;
arc.Node = follow.Target;
}
arc.Output = follow.NextFinalOutput;
arc.Label = FST.END_LABEL;
return arc;
}
else
{
return null;
}
}
if (!FST<T>.TargetHasArcs(follow))
{
return null;
}
fst.ReadFirstTargetArc(follow, arc, @in);
if (arc.BytesPerArc != 0 && arc.Label != FST.END_LABEL)
{
// Arcs are fixed array -- use binary search to find
// the target.
int low = arc.ArcIdx;
int high = arc.NumArcs - 1;
int mid /*= 0*/; // LUCENENET: Removed unnecessary assignment
// System.out.println("do arc array low=" + low + " high=" + high +
// " targetLabel=" + targetLabel);
while (low <= high)
{
mid = (int)((uint)(low + high) >> 1);
@in.Position = arc.PosArcsStart;
@in.SkipBytes(arc.BytesPerArc * mid + 1);
int midLabel = fst.ReadLabel(@in);
int cmp = midLabel - label;
// System.out.println(" cycle low=" + low + " high=" + high + " mid=" +
// mid + " midLabel=" + midLabel + " cmp=" + cmp);
if (cmp < 0)
{
low = mid + 1;
}
else if (cmp > 0)
{
high = mid - 1;
}
else
{
arc.ArcIdx = mid - 1;
return fst.ReadNextRealArc(arc, @in);
}
}
if (low == arc.NumArcs)
{
// DEAD END!
return null;
}
arc.ArcIdx = (low > high ? high : low);
return fst.ReadNextRealArc(arc, @in);
}
// Linear scan
fst.ReadFirstRealTargetArc(follow.Target, arc, @in);
while (true)
{
// System.out.println(" non-bs cycle");
// TODO: we should fix this code to not have to create
// object for the output of every arc we scan... only
// for the matching arc, if found
if (arc.Label >= label)
{
// System.out.println(" found!");
return arc;
}
else if (arc.IsLast)
{
return null;
}
else
{
fst.ReadNextRealArc(arc, @in);
}
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SouthwindRepository
{
/// <summary>
/// Strongly-typed collection for the Order class.
/// </summary>
[Serializable]
public partial class OrderCollection : RepositoryList<Order, OrderCollection>
{
public OrderCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>OrderCollection</returns>
public OrderCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Order o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the orders table.
/// </summary>
[Serializable]
public partial class Order : RepositoryRecord<Order>, IRecordBase
{
#region .ctors and Default Settings
public Order()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Order(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("orders", TableType.Table, DataService.GetInstance("SouthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 10;
colvarOrderID.AutoIncrement = true;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = true;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
colvarOrderID.DefaultSetting = @"";
colvarOrderID.ForeignKeyTableName = "";
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.AnsiStringFixedLength;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = true;
colvarCustomerID.IsPrimaryKey = false;
colvarCustomerID.IsForeignKey = true;
colvarCustomerID.IsReadOnly = false;
colvarCustomerID.DefaultSetting = @"";
colvarCustomerID.ForeignKeyTableName = "";
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema);
colvarEmployeeID.ColumnName = "EmployeeID";
colvarEmployeeID.DataType = DbType.Int32;
colvarEmployeeID.MaxLength = 10;
colvarEmployeeID.AutoIncrement = false;
colvarEmployeeID.IsNullable = true;
colvarEmployeeID.IsPrimaryKey = false;
colvarEmployeeID.IsForeignKey = true;
colvarEmployeeID.IsReadOnly = false;
colvarEmployeeID.DefaultSetting = @"";
colvarEmployeeID.ForeignKeyTableName = "";
schema.Columns.Add(colvarEmployeeID);
TableSchema.TableColumn colvarOrderDate = new TableSchema.TableColumn(schema);
colvarOrderDate.ColumnName = "OrderDate";
colvarOrderDate.DataType = DbType.DateTime;
colvarOrderDate.MaxLength = 0;
colvarOrderDate.AutoIncrement = false;
colvarOrderDate.IsNullable = true;
colvarOrderDate.IsPrimaryKey = false;
colvarOrderDate.IsForeignKey = true;
colvarOrderDate.IsReadOnly = false;
colvarOrderDate.DefaultSetting = @"";
colvarOrderDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarOrderDate);
TableSchema.TableColumn colvarRequiredDate = new TableSchema.TableColumn(schema);
colvarRequiredDate.ColumnName = "RequiredDate";
colvarRequiredDate.DataType = DbType.DateTime;
colvarRequiredDate.MaxLength = 0;
colvarRequiredDate.AutoIncrement = false;
colvarRequiredDate.IsNullable = true;
colvarRequiredDate.IsPrimaryKey = false;
colvarRequiredDate.IsForeignKey = false;
colvarRequiredDate.IsReadOnly = false;
colvarRequiredDate.DefaultSetting = @"";
colvarRequiredDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarRequiredDate);
TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema);
colvarShippedDate.ColumnName = "ShippedDate";
colvarShippedDate.DataType = DbType.DateTime;
colvarShippedDate.MaxLength = 0;
colvarShippedDate.AutoIncrement = false;
colvarShippedDate.IsNullable = true;
colvarShippedDate.IsPrimaryKey = false;
colvarShippedDate.IsForeignKey = true;
colvarShippedDate.IsReadOnly = false;
colvarShippedDate.DefaultSetting = @"";
colvarShippedDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarShippedDate);
TableSchema.TableColumn colvarShipVia = new TableSchema.TableColumn(schema);
colvarShipVia.ColumnName = "ShipVia";
colvarShipVia.DataType = DbType.Int32;
colvarShipVia.MaxLength = 10;
colvarShipVia.AutoIncrement = false;
colvarShipVia.IsNullable = true;
colvarShipVia.IsPrimaryKey = false;
colvarShipVia.IsForeignKey = true;
colvarShipVia.IsReadOnly = false;
colvarShipVia.DefaultSetting = @"";
colvarShipVia.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipVia);
TableSchema.TableColumn colvarFreight = new TableSchema.TableColumn(schema);
colvarFreight.ColumnName = "Freight";
colvarFreight.DataType = DbType.Decimal;
colvarFreight.MaxLength = 0;
colvarFreight.AutoIncrement = false;
colvarFreight.IsNullable = true;
colvarFreight.IsPrimaryKey = false;
colvarFreight.IsForeignKey = false;
colvarFreight.IsReadOnly = false;
colvarFreight.DefaultSetting = @"";
colvarFreight.ForeignKeyTableName = "";
schema.Columns.Add(colvarFreight);
TableSchema.TableColumn colvarShipName = new TableSchema.TableColumn(schema);
colvarShipName.ColumnName = "ShipName";
colvarShipName.DataType = DbType.String;
colvarShipName.MaxLength = 40;
colvarShipName.AutoIncrement = false;
colvarShipName.IsNullable = true;
colvarShipName.IsPrimaryKey = false;
colvarShipName.IsForeignKey = false;
colvarShipName.IsReadOnly = false;
colvarShipName.DefaultSetting = @"";
colvarShipName.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipName);
TableSchema.TableColumn colvarShipAddress = new TableSchema.TableColumn(schema);
colvarShipAddress.ColumnName = "ShipAddress";
colvarShipAddress.DataType = DbType.String;
colvarShipAddress.MaxLength = 60;
colvarShipAddress.AutoIncrement = false;
colvarShipAddress.IsNullable = true;
colvarShipAddress.IsPrimaryKey = false;
colvarShipAddress.IsForeignKey = false;
colvarShipAddress.IsReadOnly = false;
colvarShipAddress.DefaultSetting = @"";
colvarShipAddress.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipAddress);
TableSchema.TableColumn colvarShipCity = new TableSchema.TableColumn(schema);
colvarShipCity.ColumnName = "ShipCity";
colvarShipCity.DataType = DbType.String;
colvarShipCity.MaxLength = 15;
colvarShipCity.AutoIncrement = false;
colvarShipCity.IsNullable = true;
colvarShipCity.IsPrimaryKey = false;
colvarShipCity.IsForeignKey = false;
colvarShipCity.IsReadOnly = false;
colvarShipCity.DefaultSetting = @"";
colvarShipCity.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipCity);
TableSchema.TableColumn colvarShipRegion = new TableSchema.TableColumn(schema);
colvarShipRegion.ColumnName = "ShipRegion";
colvarShipRegion.DataType = DbType.String;
colvarShipRegion.MaxLength = 15;
colvarShipRegion.AutoIncrement = false;
colvarShipRegion.IsNullable = true;
colvarShipRegion.IsPrimaryKey = false;
colvarShipRegion.IsForeignKey = false;
colvarShipRegion.IsReadOnly = false;
colvarShipRegion.DefaultSetting = @"";
colvarShipRegion.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipRegion);
TableSchema.TableColumn colvarShipPostalCode = new TableSchema.TableColumn(schema);
colvarShipPostalCode.ColumnName = "ShipPostalCode";
colvarShipPostalCode.DataType = DbType.String;
colvarShipPostalCode.MaxLength = 10;
colvarShipPostalCode.AutoIncrement = false;
colvarShipPostalCode.IsNullable = true;
colvarShipPostalCode.IsPrimaryKey = false;
colvarShipPostalCode.IsForeignKey = true;
colvarShipPostalCode.IsReadOnly = false;
colvarShipPostalCode.DefaultSetting = @"";
colvarShipPostalCode.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipPostalCode);
TableSchema.TableColumn colvarShipCountry = new TableSchema.TableColumn(schema);
colvarShipCountry.ColumnName = "ShipCountry";
colvarShipCountry.DataType = DbType.String;
colvarShipCountry.MaxLength = 15;
colvarShipCountry.AutoIncrement = false;
colvarShipCountry.IsNullable = true;
colvarShipCountry.IsPrimaryKey = false;
colvarShipCountry.IsForeignKey = false;
colvarShipCountry.IsReadOnly = false;
colvarShipCountry.DefaultSetting = @"";
colvarShipCountry.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipCountry);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["SouthwindRepository"].AddSchema("orders",schema);
}
}
#endregion
#region Props
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get { return GetColumnValue<int>(Columns.OrderID); }
set { SetColumnValue(Columns.OrderID, value); }
}
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get { return GetColumnValue<string>(Columns.CustomerID); }
set { SetColumnValue(Columns.CustomerID, value); }
}
[XmlAttribute("EmployeeID")]
[Bindable(true)]
public int? EmployeeID
{
get { return GetColumnValue<int?>(Columns.EmployeeID); }
set { SetColumnValue(Columns.EmployeeID, value); }
}
[XmlAttribute("OrderDate")]
[Bindable(true)]
public DateTime? OrderDate
{
get { return GetColumnValue<DateTime?>(Columns.OrderDate); }
set { SetColumnValue(Columns.OrderDate, value); }
}
[XmlAttribute("RequiredDate")]
[Bindable(true)]
public DateTime? RequiredDate
{
get { return GetColumnValue<DateTime?>(Columns.RequiredDate); }
set { SetColumnValue(Columns.RequiredDate, value); }
}
[XmlAttribute("ShippedDate")]
[Bindable(true)]
public DateTime? ShippedDate
{
get { return GetColumnValue<DateTime?>(Columns.ShippedDate); }
set { SetColumnValue(Columns.ShippedDate, value); }
}
[XmlAttribute("ShipVia")]
[Bindable(true)]
public int? ShipVia
{
get { return GetColumnValue<int?>(Columns.ShipVia); }
set { SetColumnValue(Columns.ShipVia, value); }
}
[XmlAttribute("Freight")]
[Bindable(true)]
public decimal? Freight
{
get { return GetColumnValue<decimal?>(Columns.Freight); }
set { SetColumnValue(Columns.Freight, value); }
}
[XmlAttribute("ShipName")]
[Bindable(true)]
public string ShipName
{
get { return GetColumnValue<string>(Columns.ShipName); }
set { SetColumnValue(Columns.ShipName, value); }
}
[XmlAttribute("ShipAddress")]
[Bindable(true)]
public string ShipAddress
{
get { return GetColumnValue<string>(Columns.ShipAddress); }
set { SetColumnValue(Columns.ShipAddress, value); }
}
[XmlAttribute("ShipCity")]
[Bindable(true)]
public string ShipCity
{
get { return GetColumnValue<string>(Columns.ShipCity); }
set { SetColumnValue(Columns.ShipCity, value); }
}
[XmlAttribute("ShipRegion")]
[Bindable(true)]
public string ShipRegion
{
get { return GetColumnValue<string>(Columns.ShipRegion); }
set { SetColumnValue(Columns.ShipRegion, value); }
}
[XmlAttribute("ShipPostalCode")]
[Bindable(true)]
public string ShipPostalCode
{
get { return GetColumnValue<string>(Columns.ShipPostalCode); }
set { SetColumnValue(Columns.ShipPostalCode, value); }
}
[XmlAttribute("ShipCountry")]
[Bindable(true)]
public string ShipCountry
{
get { return GetColumnValue<string>(Columns.ShipCountry); }
set { SetColumnValue(Columns.ShipCountry, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region Typed Columns
public static TableSchema.TableColumn OrderIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CustomerIDColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn EmployeeIDColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn OrderDateColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn RequiredDateColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ShippedDateColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn ShipViaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn FreightColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn ShipNameColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn ShipAddressColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn ShipCityColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn ShipRegionColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn ShipPostalCodeColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn ShipCountryColumn
{
get { return Schema.Columns[13]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string OrderID = @"OrderID";
public static string CustomerID = @"CustomerID";
public static string EmployeeID = @"EmployeeID";
public static string OrderDate = @"OrderDate";
public static string RequiredDate = @"RequiredDate";
public static string ShippedDate = @"ShippedDate";
public static string ShipVia = @"ShipVia";
public static string Freight = @"Freight";
public static string ShipName = @"ShipName";
public static string ShipAddress = @"ShipAddress";
public static string ShipCity = @"ShipCity";
public static string ShipRegion = @"ShipRegion";
public static string ShipPostalCode = @"ShipPostalCode";
public static string ShipCountry = @"ShipCountry";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
namespace REBasic
{
partial class RETranslate
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnMinus = new System.Windows.Forms.Button();
this.btnPlus = new System.Windows.Forms.Button();
this.lpInput = new RE.RELinkPoint();
this.lpOutput = new RE.RELinkPoint();
this.cbIgnoreCase = new System.Windows.Forms.CheckBox();
this.btnDown = new System.Windows.Forms.Button();
this.btnUp = new System.Windows.Forms.Button();
this.panItems = new System.Windows.Forms.Panel();
this.cbGlobal = new System.Windows.Forms.CheckBox();
this.lblSearch = new System.Windows.Forms.Label();
this.panColumn1 = new System.Windows.Forms.Panel();
this.lblReplace = new System.Windows.Forms.Label();
this.panItemClient.SuspendLayout();
this.SuspendLayout();
//
// panItemClient
//
this.panItemClient.Controls.Add(this.lblReplace);
this.panItemClient.Controls.Add(this.panColumn1);
this.panItemClient.Controls.Add(this.lblSearch);
this.panItemClient.Controls.Add(this.panItems);
this.panItemClient.Controls.Add(this.btnDown);
this.panItemClient.Controls.Add(this.btnUp);
this.panItemClient.Controls.Add(this.cbGlobal);
this.panItemClient.Controls.Add(this.cbIgnoreCase);
this.panItemClient.Controls.Add(this.lpOutput);
this.panItemClient.Controls.Add(this.lpInput);
this.panItemClient.Controls.Add(this.btnMinus);
this.panItemClient.Controls.Add(this.btnPlus);
this.panItemClient.Size = new System.Drawing.Size(265, 122);
//
// btnMinus
//
this.btnMinus.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnMinus.Image = global::REBasic.Properties.Resources.Minus;
this.btnMinus.Location = new System.Drawing.Point(26, 3);
this.btnMinus.Name = "btnMinus";
this.btnMinus.Size = new System.Drawing.Size(17, 17);
this.btnMinus.TabIndex = 5;
this.btnMinus.UseVisualStyleBackColor = true;
this.btnMinus.Click += new System.EventHandler(this.btnMinus_Click);
//
// btnPlus
//
this.btnPlus.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnPlus.Image = global::REBasic.Properties.Resources.Plus;
this.btnPlus.Location = new System.Drawing.Point(3, 3);
this.btnPlus.Name = "btnPlus";
this.btnPlus.Size = new System.Drawing.Size(17, 17);
this.btnPlus.TabIndex = 4;
this.btnPlus.UseVisualStyleBackColor = true;
this.btnPlus.Click += new System.EventHandler(this.btnPlus_Click);
//
// lpInput
//
this.lpInput.AllowDrop = true;
this.lpInput.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lpInput.Caption = "input";
this.lpInput.ConnectedTo = null;
this.lpInput.ConnectionColor = System.Drawing.Color.Transparent;
this.lpInput.Direction = RE.RELinkPointDirection.Input;
this.lpInput.Key = "input";
this.lpInput.Location = new System.Drawing.Point(3, 103);
this.lpInput.Name = "lpInput";
this.lpInput.Size = new System.Drawing.Size(48, 16);
this.lpInput.TabIndex = 6;
//
// lpOutput
//
this.lpOutput.AllowDrop = true;
this.lpOutput.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lpOutput.Caption = "output";
this.lpOutput.ConnectedTo = null;
this.lpOutput.ConnectionColor = System.Drawing.Color.Transparent;
this.lpOutput.Direction = RE.RELinkPointDirection.Output;
this.lpOutput.Key = "output";
this.lpOutput.Location = new System.Drawing.Point(58, 103);
this.lpOutput.Name = "lpOutput";
this.lpOutput.Size = new System.Drawing.Size(48, 16);
this.lpOutput.TabIndex = 7;
//
// cbIgnoreCase
//
this.cbIgnoreCase.AutoSize = true;
this.cbIgnoreCase.Checked = true;
this.cbIgnoreCase.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbIgnoreCase.Location = new System.Drawing.Point(100, 3);
this.cbIgnoreCase.Name = "cbIgnoreCase";
this.cbIgnoreCase.Size = new System.Drawing.Size(94, 17);
this.cbIgnoreCase.TabIndex = 9;
this.cbIgnoreCase.Text = "Ignore case";
this.cbIgnoreCase.UseVisualStyleBackColor = true;
//
// btnDown
//
this.btnDown.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnDown.Image = global::REBasic.Properties.Resources.Down;
this.btnDown.Location = new System.Drawing.Point(72, 3);
this.btnDown.Name = "btnDown";
this.btnDown.Size = new System.Drawing.Size(17, 17);
this.btnDown.TabIndex = 12;
this.btnDown.UseVisualStyleBackColor = true;
this.btnDown.Click += new System.EventHandler(this.btnDown_Click);
//
// btnUp
//
this.btnUp.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btnUp.Image = global::REBasic.Properties.Resources.Up;
this.btnUp.Location = new System.Drawing.Point(49, 3);
this.btnUp.Name = "btnUp";
this.btnUp.Size = new System.Drawing.Size(17, 17);
this.btnUp.TabIndex = 11;
this.btnUp.UseVisualStyleBackColor = true;
this.btnUp.Click += new System.EventHandler(this.btnUp_Click);
//
// panItems
//
this.panItems.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panItems.AutoScroll = true;
this.panItems.Location = new System.Drawing.Point(4, 43);
this.panItems.Name = "panItems";
this.panItems.Size = new System.Drawing.Size(258, 54);
this.panItems.TabIndex = 13;
//
// cbGlobal
//
this.cbGlobal.AutoSize = true;
this.cbGlobal.Checked = true;
this.cbGlobal.CheckState = System.Windows.Forms.CheckState.Checked;
this.cbGlobal.Location = new System.Drawing.Point(200, 3);
this.cbGlobal.Name = "cbGlobal";
this.cbGlobal.Size = new System.Drawing.Size(62, 17);
this.cbGlobal.TabIndex = 10;
this.cbGlobal.Text = "Global";
this.cbGlobal.UseVisualStyleBackColor = true;
//
// lblSearch
//
this.lblSearch.AutoSize = true;
this.lblSearch.Location = new System.Drawing.Point(4, 27);
this.lblSearch.Name = "lblSearch";
this.lblSearch.Size = new System.Drawing.Size(47, 13);
this.lblSearch.TabIndex = 14;
this.lblSearch.Text = "Search";
//
// panColumn1
//
this.panColumn1.BackColor = System.Drawing.SystemColors.ControlLight;
this.panColumn1.Cursor = System.Windows.Forms.Cursors.VSplit;
this.panColumn1.Location = new System.Drawing.Point(110, 22);
this.panColumn1.Name = "panColumn1";
this.panColumn1.Size = new System.Drawing.Size(8, 21);
this.panColumn1.TabIndex = 15;
this.panColumn1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.panColumn1_MouseMove);
this.panColumn1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panColumn1_MouseDown);
this.panColumn1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.panColumn1_MouseUp);
//
// lblReplace
//
this.lblReplace.AutoSize = true;
this.lblReplace.Location = new System.Drawing.Point(113, 27);
this.lblReplace.Name = "lblReplace";
this.lblReplace.Size = new System.Drawing.Size(52, 13);
this.lblReplace.TabIndex = 16;
this.lblReplace.Text = "Replace";
//
// RETranslate
//
this.Caption = "Translate";
this.Name = "RETranslate";
this.Size = new System.Drawing.Size(272, 147);
this.panItemClient.ResumeLayout(false);
this.panItemClient.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnMinus;
private System.Windows.Forms.Button btnPlus;
private RE.RELinkPoint lpOutput;
private RE.RELinkPoint lpInput;
private System.Windows.Forms.Button btnDown;
private System.Windows.Forms.Button btnUp;
private System.Windows.Forms.CheckBox cbIgnoreCase;
private System.Windows.Forms.Panel panItems;
private System.Windows.Forms.CheckBox cbGlobal;
private System.Windows.Forms.Panel panColumn1;
private System.Windows.Forms.Label lblSearch;
private System.Windows.Forms.Label lblReplace;
}
}
| |
using EPiServer.Commerce.Catalog.ContentTypes;
using EPiServer.Commerce.Catalog.Linking;
using EPiServer.Commerce.Marketing;
using EPiServer.Commerce.Order;
using EPiServer.Commerce.Order.Internal;
using EPiServer.Core;
using EPiServer.Framework.Cache;
using EPiServer.Reference.Commerce.Site.Features.AddressBook.Services;
using EPiServer.Reference.Commerce.Site.Features.Cart.Services;
using EPiServer.Reference.Commerce.Site.Features.Cart.ViewModels;
using EPiServer.Reference.Commerce.Site.Features.Market.Services;
using EPiServer.Reference.Commerce.Site.Features.Product.Services;
using EPiServer.Reference.Commerce.Site.Features.Shared.Models;
using EPiServer.Reference.Commerce.Site.Features.Shared.Services;
using EPiServer.Reference.Commerce.Site.Infrastructure.Facades;
using EPiServer.Reference.Commerce.Site.Tests.TestSupport.Fakes;
using Mediachase.Commerce;
using Mediachase.Commerce.Catalog;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using Mediachase.Commerce.Pricing;
using Xunit;
namespace EPiServer.Reference.Commerce.Site.Tests.Features.Cart.Services
{
public class CartServiceTests
{
[Fact]
public void AddCouponCode_WhenCouponCodeIsAppliedToPromotion_ShouldReturnTrue()
{
var couponCode = "IBUYALOT";
var rewardDescription = RewardDescription.CreatePercentageReward(FulfillmentStatus.Fulfilled, null, new PromotionForTest(), 10, string.Empty);
rewardDescription.AppliedCoupon = couponCode;
_promotionEngineMock
.Setup(x => x.Run(It.IsAny<IOrderGroup>(), It.IsAny<PromotionEngineSettings>()))
.Returns(new[] { rewardDescription });
var result = _subject.AddCouponCode(_cart, couponCode);
Assert.True(result);
}
[Fact]
public void AddCouponCode_WhenCouponCodeIsNotAppliedToPromotion_ShouldReturnFalse()
{
var couponCode = "IDONTEXIST";
_promotionEngineMock
.Setup(x => x.Run(It.IsAny<IOrderGroup>(), It.IsAny<PromotionEngineSettings>()))
.Returns(new[] {
RewardDescription.CreatePercentageReward(FulfillmentStatus.Fulfilled, null, new PromotionForTest(), 10, string.Empty)
});
var result = _subject.AddCouponCode(_cart, couponCode);
Assert.False(result);
}
[Fact]
public void RemoveCouponCode_ShouldRemoveCodeFromForm()
{
string couponCode = "IBUYALOT";
_cart.GetFirstForm().CouponCodes.Add(couponCode);
_subject.RemoveCouponCode(_cart, couponCode);
Assert.Empty(_cart.GetFirstForm().CouponCodes);
}
[Fact]
public void AddToCart_ShouldRunPromotionEngine()
{
var code = "EAN";
_subject.AddToCart(_cart, code, 1);
_orderValidationServiceMock.Verify(x => x.ValidateOrder(_cart), Times.Once);
}
[Fact]
public void AddToCart_WhenLineItemNotInCart_ShouldAddToCart()
{
_subject.AddToCart(_cart, "code", 1);
Assert.Equal(1, _cart.GetAllLineItems().Single(x => x.Code == "code").Quantity);
}
[Fact]
public void AddToCart_WhenLineItemNotInCart_ShouldAddLineItemDisplayName()
{
_variationContent.DisplayName = "sample-name";
_subject.AddToCart(_cart, "code", 1);
Assert.Equal("sample-name", _cart.GetAllLineItems().Single(x => x.Code == "code").DisplayName);
}
[Fact]
public void AddToCart_WhenLineItemNotInCart_ShouldSetPlacedPrice()
{
var code = "code";
var unitPrice = new Money(9.95m, _cart.Currency);
_pricingServiceMock
.Setup(m => m.GetPrice(code))
.Returns(new PriceValue {UnitPrice = unitPrice});
_subject.AddToCart(_cart, code, 1);
Assert.Equal(unitPrice.Amount, _cart.GetAllLineItems().Single(x => x.Code == code).PlacedPrice);
}
[Fact]
public void AddToCart_WhenLineItemAlreadyInCart_ShouldIncreaseQuantity()
{
_subject.AddToCart(_cart, "code", 1);
_subject.AddToCart(_cart, "code", 1);
Assert.Equal(2, _cart.GetAllLineItems().Single(x => x.Code == "code").Quantity);
}
[Fact]
public void AddToCart_WhenLineItemIsRemoved_ShouldReturnWarningMessage()
{
var validationIssues = new Dictionary<ILineItem, IList<ValidationIssue>>
{
{
new Mock<ILineItem>().Object, new List<ValidationIssue>()
{
ValidationIssue.AdjustedQuantityByAvailableQuantity
}
}
};
_orderValidationServiceMock
.Setup(x => x.ValidateOrder(_cart))
.Returns(validationIssues);
var result = _subject.AddToCart(_cart, "SKU1234", 1);
Assert.Equal<int>(1, result.ValidationMessages.Count);
}
[Fact]
public void AddToCart_WhenItemIsBundle_ShouldAddContainedLineItemsToCart()
{
var bundle = new BundleContent
{
ContentLink = new ContentReference(1),
Code = "bundlecode"
};
var bundleEntry1 = new BundleEntry
{
Parent = new ContentReference(2),
Quantity = 1
};
var variant1 = new VariationContent
{
Code = "variant1code",
ContentLink = bundleEntry1.Parent
};
var bundleEntry2 = new BundleEntry
{
Parent = new ContentReference(3),
Quantity = 2
};
var variant2 = new VariationContent
{
Code = "variant2code",
ContentLink = bundleEntry2.Parent
};
_referenceConverterMock.Setup(x => x.GetContentLink(variant1.Code)).Returns(variant1.ContentLink);
_referenceConverterMock.Setup(x => x.GetContentLink(variant2.Code)).Returns(variant2.ContentLink);
_referenceConverterMock.Setup(x => x.GetContentLink(bundle.Code)).Returns(bundle.ContentLink);
_relationRepositoryMock.Setup(x => x.GetChildren<BundleEntry>(bundle.ContentLink))
.Returns(() => new List<BundleEntry> { bundleEntry1, bundleEntry2 });
_contentLoaderMock.Setup(x => x.Get<EntryContentBase>(bundle.ContentLink)).Returns(bundle);
_contentLoaderMock.Setup(x => x.Get<EntryContentBase>(variant1.ContentLink)).Returns(variant1);
_contentLoaderMock.Setup(x => x.Get<EntryContentBase>(variant2.ContentLink)).Returns(variant2);
_subject.AddToCart(_cart, bundle.Code, 1);
Assert.Equal(bundleEntry1.Quantity + bundleEntry2.Quantity, _cart.GetAllLineItems().Sum(x => x.Quantity));
}
[Fact]
public void AddToCart_WhenItemIsBundleAndContainsPackage_ShouldAddContainedPackageToCart()
{
var bundle = new BundleContent
{
ContentLink = new ContentReference(1),
Code = "bundlecode"
};
var bundleEntry1 = new BundleEntry
{
Parent = new ContentReference(2),
Quantity = 1
};
var variant1 = new VariationContent
{
Code = "variant1code",
ContentLink = bundleEntry1.Parent
};
var bundleEntry2 = new BundleEntry
{
Parent = new ContentReference(3),
Quantity = 2
};
var package = new PackageContent
{
Code = "packagecode",
ContentLink = bundleEntry2.Parent
};
_referenceConverterMock.Setup(x => x.GetContentLink(variant1.Code)).Returns(variant1.ContentLink);
_referenceConverterMock.Setup(x => x.GetContentLink(package.Code)).Returns(package.ContentLink);
_referenceConverterMock.Setup(x => x.GetContentLink(bundle.Code)).Returns(bundle.ContentLink);
_relationRepositoryMock.Setup(x => x.GetChildren<BundleEntry>(bundle.ContentLink))
.Returns(() => new List<BundleEntry> { bundleEntry1, bundleEntry2 });
_contentLoaderMock.Setup(x => x.Get<EntryContentBase>(bundle.ContentLink)).Returns(bundle);
_contentLoaderMock.Setup(x => x.Get<EntryContentBase>(variant1.ContentLink)).Returns(variant1);
_contentLoaderMock.Setup(x => x.Get<EntryContentBase>(package.ContentLink)).Returns(package);
_subject.AddToCart(_cart, bundle.Code, 1);
Assert.Equal(bundleEntry1.Quantity + bundleEntry2.Quantity, _cart.GetAllLineItems().Sum(x => x.Quantity));
}
[Fact]
public void ChangeCartItem_ShouldChangeQuantityAccordingly()
{
var shipmentId = 0;
var quantity = 5m;
var size = "small";
var code = "EAN";
var newSize = "small";
var lineItem = new InMemoryLineItem
{
Quantity = 2,
Code = code
};
_cart.GetFirstShipment().LineItems.Add(lineItem);
_subject.ChangeCartItem(_cart, shipmentId, code, quantity, size, newSize, "");
Assert.Equal<decimal>(quantity, lineItem.Quantity);
}
[Fact]
public void ChangeCartItem_WhenQuantityIsZero_ShouldRemoveLineItem()
{
var shipmentId = 0;
var quantity = 0;
var size = "small";
var code = "EAN";
var newSize = "small";
var lineItem = new InMemoryLineItem
{
Quantity = 2,
Code = code
};
_cart.GetFirstShipment().LineItems.Add(lineItem);
_subject.ChangeCartItem(_cart, shipmentId, code, quantity, size, newSize, "");
Assert.Empty(_cart.GetAllLineItems());
}
[Fact]
public void ChangeCartItemForMultiShipment_WhenQuantityIsZeroInOneShipment_ShouldRemoveTheCorrespondantLineItem()
{
var quantity = 0;
var size = "small";
var code = "EAN";
var newSize = "small";
var lineItem = new InMemoryLineItem
{
Quantity = 2,
Code = code
};
var removedLineItem = new InMemoryLineItem
{
Quantity = 3,
Code = code
};
_cart.GetFirstShipment().LineItems.Add(lineItem);
var shipment = new FakeShipment { ParentOrderGroup = _cart};
shipment.LineItems.Add(removedLineItem);
_cart.AddShipment(shipment, _orderGroupFactoryMock.Object);
_subject.ChangeCartItem(_cart, shipment.ShipmentId, code, quantity, size, newSize, "");
Assert.DoesNotContain(_cart.GetFirstForm().Shipments, s => s.ShipmentId == shipment.ShipmentId && s.LineItems.Any(l => l.Code == code));
}
[Fact]
public void ChangeCartItem_WhenLineItemToChangeToDoesNotExists_ShouldUpdateLineItem()
{
_productServiceMock.Setup(x => x.GetSiblingVariantCodeBySize(It.IsAny<string>(), It.IsAny<string>())).Returns("newcode");
_cart.GetFirstShipment().LineItems.Add(new InMemoryLineItem { Quantity = 1, Code = "code" });
_subject.ChangeCartItem(_cart, 0, "code", 5, "S", "M", "");
Assert.Equal("newcode", _cart.GetFirstShipment().LineItems.Single().Code);
Assert.Equal<decimal>(5, _cart.GetFirstShipment().LineItems.Single().Quantity);
}
[Fact]
public void ChangeCartItem_WhenLineItemToChangeToAlreadyExists_ShouldUpdateLineItem()
{
_productServiceMock.Setup(x => x.GetSiblingVariantCodeBySize(It.IsAny<string>(), It.IsAny<string>())).Returns("newcode");
_cart.GetFirstShipment().LineItems.Add(new InMemoryLineItem { Quantity = 1, Code = "newcode" });
_cart.GetFirstShipment().LineItems.Add(new InMemoryLineItem { Quantity = 1, Code = "code" });
_subject.ChangeCartItem(_cart, 0, "code", 5, "S", "M", "");
Assert.Equal("newcode", _cart.GetFirstShipment().LineItems.Single().Code);
Assert.Equal<decimal>(5 + 1, _cart.GetFirstShipment().LineItems.Single().Quantity);
}
[Fact]
public void LoadCart_WhenNotExist_ShouldReturnNUll()
{
var result = _subject.LoadCart("UNKNOWN");
Assert.Null(result);
}
[Fact]
public void LoadCart_WhenExist_ShouldReturnInstanceOfCart()
{
var result = _subject.LoadCart(_subject.DefaultCartName);
Assert.Equal<ICart>(_cart, result);
Assert.Equal(result.Currency, new Currency("USD"));
}
[Fact]
public void LoadCart_WithCurrentCurrency_WhenExist_ShouldReturnInstanceOfCart()
{
var currentCurrency = new Currency("SEK");
_currencyServiceMock.Setup(x => x.GetCurrentCurrency()).Returns(currentCurrency);
var result = _subject.LoadCart(_subject.DefaultCartName);
Assert.Equal(result.Currency, currentCurrency);
}
[Fact]
public void LoadCart_WhenAllItemsIsValid_ShouldReturnCartWithAllItems()
{
var lineItem = new InMemoryLineItem { Quantity = 2, Code = "code1" };
var lineItem2 = new InMemoryLineItem { Quantity = 2, Code = "code2" };
_cart.GetFirstShipment().LineItems.Add(lineItem);
_cart.GetFirstShipment().LineItems.Add(lineItem2);
var result = _subject.LoadCart(_subject.DefaultCartName);
Assert.Equal(2, result.GetAllLineItems().Count());
}
[Fact]
public void LoadOrCreateCart_WhenExist_ShouldReturnInstanceOfCart()
{
var result = _subject.LoadOrCreateCart(_subject.DefaultCartName);
Assert.Equal<ICart>(_cart, result);
Assert.Equal(result.Currency, new Currency("USD"));
}
[Fact]
public void LoadOrCreateCart_WithCurrentCurrency_WhenExist_ShouldReturnInstanceOfCart()
{
var currentCurrency = new Currency("SEK");
_currencyServiceMock.Setup(x => x.GetCurrentCurrency()).Returns(currentCurrency);
var result = _subject.LoadOrCreateCart(_subject.DefaultCartName);
Assert.Equal(result.Currency, currentCurrency);
}
[Fact]
public void LoadOrCreateCart_WhenNoCartExists_ShouldReturnNewInstanceOfCart()
{
_orderRepositoryMock
.Setup(x => x.Create<ICart>(It.IsAny<Guid>(), It.IsAny<string>()))
.Returns(new FakeCart(_marketMock.Object, new Currency("USD")));
var result = _subject.LoadOrCreateCart("UNKNOWN");
Assert.NotNull(result);
Assert.NotEqual<ICart>(_cart, result);
}
[Fact]
public void MergeShipments()
{
_subject.MergeShipments(_cart);
}
[Fact]
public void RecreateLineItemsBasedOnShipments_WhenHavingLineItemDisplayName_ShouldSaveToCart()
{
var shipment = _cart.GetFirstShipment();
var skuCode = "EAN";
var displayName = "display-name";
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 2
});
_subject.RecreateLineItemsBasedOnShipments(_cart, new[]
{
new CartItemViewModel { Code = skuCode, AddressId = "1", DisplayName = displayName },
new CartItemViewModel { Code = skuCode, AddressId = "2", DisplayName = displayName }
}, new[]
{
new AddressModel { AddressId = "1", Line1 = "First street" },
new AddressModel { AddressId = "2", Line1 = "Second street" }
});
Assert.Equal(displayName, _cart.GetAllLineItems().First().DisplayName);
}
[Fact]
public void RecreateLineItemsBasedOnShipments_WhenHavingTwoShippingAddresses_ShouldCreateTwoShipmentLineItems()
{
var shipment = _cart.GetFirstShipment();
var skuCode = "EAN";
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 3
});
_subject.RecreateLineItemsBasedOnShipments(_cart, new[]
{
new CartItemViewModel { Code = skuCode, AddressId = "1" },
new CartItemViewModel { Code = skuCode, AddressId = "2" },
new CartItemViewModel { Code = skuCode, AddressId = "2" }
}, new[]
{
new AddressModel { AddressId = "1", Line1 = "First street" },
new AddressModel { AddressId = "2", Line1 = "Second street" }
});
Assert.Equal<int>(2, _cart.GetAllLineItems().Count());
}
[Fact]
public void RecreateLineItemsBasedOnShipments_WhenHavingLineItemAsGift_ShouldKeepIsGift()
{
var shipment = _cart.GetFirstShipment();
var skuCode = "EAN";
var giftSkuCode = "AAA";
shipment.LineItems.Add(new InMemoryLineItem
{
Code = giftSkuCode,
Quantity = 1,
IsGift = true
});
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 2,
IsGift = false
});
_subject.RecreateLineItemsBasedOnShipments(_cart, new[]
{
new CartItemViewModel { Code = skuCode, AddressId = "1", IsGift = false},
new CartItemViewModel { Code = skuCode, AddressId = "2", IsGift = false},
new CartItemViewModel { Code = giftSkuCode, AddressId = "2", IsGift = true},
}, new[]
{
new AddressModel { AddressId = "1", Line1 = "First street" },
new AddressModel { AddressId = "2", Line1 = "Second street" }
});
Assert.Single(_cart.GetAllLineItems().Where(x => x.Code == giftSkuCode && x.IsGift));
Assert.Equal<int>(2, _cart.GetAllLineItems().Count(x => x.Code == skuCode && !x.IsGift));
}
[Fact]
public void RecreateLineItemsBasedOnShipments_WhenHavingLineItemWithSameCodeAsGiftAndNotGift_ShouldKeepIsGift()
{
var shipment = _cart.GetFirstShipment();
var skuCode = "EAN";
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 1,
IsGift = true
});
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 2,
IsGift = false
});
_subject.RecreateLineItemsBasedOnShipments(_cart, new[]
{
new CartItemViewModel { Code = skuCode, AddressId = "1", IsGift = false},
new CartItemViewModel { Code = skuCode, AddressId = "2" , IsGift = false},
new CartItemViewModel { Code = skuCode, AddressId = "2" , IsGift = true}
}, new[]
{
new AddressModel { AddressId = "1", Line1 = "First street" },
new AddressModel { AddressId = "2", Line1 = "Second street" }
});
Assert.Equal<int>(2, _cart.GetAllLineItems().Count(x => x.Code == skuCode && !x.IsGift));
Assert.Single(_cart.GetAllLineItems().Where(x => x.Code == skuCode && x.IsGift));
}
[Fact]
public void RequestInventory()
{
_subject.RequestInventory(_cart);
}
[Fact]
public void ValidateCart()
{
var result = _subject.ValidateCart(_cart);
}
[Fact]
public void ValidateCart_WhenIsWishList_ShouldReturnEmptyDictionary()
{
_cart.Name = _subject.DefaultWishListName;
var expectedResult = new Dictionary<ILineItem, IList<ValidationIssue>>();
var result = _subject.ValidateCart(_cart);
Assert.Equal(expectedResult, result);
}
[Fact]
public void AddToCart_WhenExistSameItemIsGiftInCart_ShouldAddToCart()
{
var shipment = _cart.GetFirstShipment();
var skuCode = "EAN";
shipment.LineItems.Add(new InMemoryLineItem
{
Code = skuCode,
Quantity = 1,
IsGift = true
});
_subject.AddToCart(_cart, skuCode, 1);
Assert.Equal(2, _cart.GetAllLineItems().Count());
}
private readonly Mock<IAddressBookService> _addressBookServiceMock;
private readonly Mock<CustomerContextFacade> _customerContextFacaceMock;
private readonly Mock<IOrderGroupFactory> _orderGroupFactoryMock;
private readonly Mock<IInventoryProcessor> _inventoryProcessorMock;
private readonly Mock<IOrderRepository> _orderRepositoryMock;
private readonly Mock<IPricingService> _pricingServiceMock;
private readonly Mock<IProductService> _productServiceMock;
private readonly Mock<IPromotionEngine> _promotionEngineMock;
private readonly Mock<ICurrentMarket> _currentMarketMock;
private readonly Mock<IMarket> _marketMock;
private readonly Mock<ICurrencyService> _currencyServiceMock;
private readonly Mock<ReferenceConverter> _referenceConverterMock;
private readonly Mock<IContentLoader> _contentLoaderMock;
private readonly Mock<IRelationRepository> _relationRepositoryMock;
private readonly CartService _subject;
private readonly ICart _cart;
private readonly VariationContent _variationContent;
private readonly Mock<OrderValidationService> _orderValidationServiceMock;
public CartServiceTests()
{
var synchronizedObjectInstanceCacheMock = new Mock<ISynchronizedObjectInstanceCache>();
_addressBookServiceMock = new Mock<IAddressBookService>();
_customerContextFacaceMock = new Mock<CustomerContextFacade>(null);
_orderGroupFactoryMock = new Mock<IOrderGroupFactory>();
_inventoryProcessorMock = new Mock<IInventoryProcessor>();
_orderRepositoryMock = new Mock<IOrderRepository>();
_pricingServiceMock = new Mock<IPricingService>();
_productServiceMock = new Mock<IProductService>();
_productServiceMock = new Mock<IProductService>();
_promotionEngineMock = new Mock<IPromotionEngine>();
_marketMock = new Mock<IMarket>();
_currentMarketMock = new Mock<ICurrentMarket>();
_currencyServiceMock = new Mock<ICurrencyService>();
_contentLoaderMock = new Mock<IContentLoader>();
_variationContent = new VariationContent();
_relationRepositoryMock = new Mock<IRelationRepository>();
_orderValidationServiceMock =
new Mock<OrderValidationService>(null, null, null, null);
_referenceConverterMock = new Mock<ReferenceConverter>(
new EntryIdentityResolver(synchronizedObjectInstanceCacheMock.Object, new CatalogOptions()),
new NodeIdentityResolver(synchronizedObjectInstanceCacheMock.Object, new CatalogOptions()));
_orderValidationServiceMock.Setup(x => x.ValidateOrder(It.IsAny<IOrderGroup>()))
.Returns(new Dictionary<ILineItem, IList<ValidationIssue>>());
_subject = new CartService(_productServiceMock.Object, _pricingServiceMock.Object, _orderGroupFactoryMock.Object,
_customerContextFacaceMock.Object, _inventoryProcessorMock.Object, _orderRepositoryMock.Object, _promotionEngineMock.Object,
_addressBookServiceMock.Object, _currentMarketMock.Object, _currencyServiceMock.Object,
_referenceConverterMock.Object, _contentLoaderMock.Object, _relationRepositoryMock.Object,
_orderValidationServiceMock.Object);
_cart = new FakeCart(new Mock<IMarket>().Object, new Currency("USD"))
{
Name = _subject.DefaultCartName,
OrderLink = new OrderReference(1, "Default", Guid.NewGuid(), typeof(FakeCart))
};
_orderGroupFactoryMock.Setup(x => x.CreateLineItem(It.IsAny<string>(), It.IsAny<IOrderGroup>())).Returns((string code, IOrderGroup orderGroup) => new FakeLineItem { Code = code, ParentOrderGroup = orderGroup });
_orderGroupFactoryMock.Setup(x => x.CreateShipment(It.IsAny<IOrderGroup>())).Returns((IOrderGroup orderGroup) => new FakeShipment { ParentOrderGroup = orderGroup });
_orderRepositoryMock.Setup(x => x.Load<ICart>(It.IsAny<Guid>(), _subject.DefaultCartName)).Returns(new[] { _cart });
_orderRepositoryMock.Setup(x => x.Create<ICart>(It.IsAny<Guid>(), _subject.DefaultCartName)).Returns(_cart);
_currentMarketMock.Setup(x => x.GetCurrentMarket()).Returns(_marketMock.Object);
_contentLoaderMock.Setup(x => x.Get<EntryContentBase>(It.IsAny<ContentReference>())).Returns(_variationContent);
}
class PromotionForTest : EntryPromotion
{
}
}
}
| |
// 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.
/******************************************************************
/*Test case for testing GC with cyclic double linked list leaks
/*In every loop. SetLink() to create a doubLink object array whose size
/*is iRep, each DoubLink Object is a iObj node cyclic double
/*linked list. MakeLeak() deletes all the object reference in the array
/*to make all the cyclic double linked lists become memory leaks.
/*objects' life time is longer than DoubLinkGen.
/******************************************************************/
namespace DoubLink {
using System;
using System.Runtime.CompilerServices;
public class DoubLinkStay
{
internal DoubLink[] Mv_Doub;
public static int Main(System.String [] Args)
{
int iRep = 100;
int iObj = 10;
Console.WriteLine("Test should return with ExitCode 100 ...");
switch( Args.Length )
{
case 1:
if (!Int32.TryParse( Args[0], out iRep ))
{
iRep = 100;
}
break;
case 2:
if (!Int32.TryParse( Args[0], out iRep ))
{
iRep = 100;
}
if (!Int32.TryParse( Args[1], out iObj ))
{
iObj = 10;
}
break;
default:
iRep = 100;
iObj = 10;
break;
}
DoubLinkStay Mv_Leak = new DoubLinkStay();
if(Mv_Leak.runTest(iRep, iObj ))
{
Console.WriteLine("Test Passed");
return 100;
}
Console.WriteLine("Test Failed");
return 1;
}
public bool runTest(int iRep, int iObj)
{
CreateDLinkListsWithLeak(iRep, iObj, 20);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.Write(DLinkNode.FinalCount);
Console.WriteLine(" DLinkNodes finalized");
return (DLinkNode.FinalCount==iRep*iObj*20);
}
[MethodImpl(MethodImplOptions.NoInlining)]
// Do not inline the method that creates GC objects, because it could
// extend their live intervals until the end of the parent method.
public void CreateDLinkListsWithLeak(int iRep, int iObj, int iters)
{
Mv_Doub = new DoubLink[iRep];
for(int i = 0; i < iters; i++)
{
SetLink(iRep, iObj);
MakeLeak(iRep);
}
}
public void SetLink(int iRep, int iObj)
{
for(int i=0; i<iRep; i++)
{
Mv_Doub[i] = new DoubLink(iObj);
}
}
public void MakeLeak(int iRep)
{
for(int i=0; i<iRep; i++)
{
Mv_Doub[i] = null;
}
}
}
public class DoubLink
{
internal DLinkNode[] Mv_DLink;
public DoubLink(int Num)
: this(Num, false)
{
}
public DoubLink(int Num, bool large)
{
Mv_DLink = new DLinkNode[Num];
if (Num == 0)
{
return;
}
if (Num == 1)
{
// only one element
Mv_DLink[0] = new DLinkNode((large ? 250 : 1), Mv_DLink[0], Mv_DLink[0]);
return;
}
// first element
Mv_DLink[0] = new DLinkNode((large ? 250 : 1), Mv_DLink[Num - 1], Mv_DLink[1]);
// all elements in between
for (int i = 1; i < Num - 1; i++)
{
Mv_DLink[i] = new DLinkNode((large ? 250 : i + 1), Mv_DLink[i - 1], Mv_DLink[i + 1]);
}
// last element
Mv_DLink[Num - 1] = new DLinkNode((large ? 250 : Num), Mv_DLink[Num - 2], Mv_DLink[0]);
}
public int NodeNum
{
get
{
return Mv_DLink.Length;
}
}
public DLinkNode this[int index]
{
get
{
return Mv_DLink[index];
}
set
{
Mv_DLink[index] = value;
}
}
}
public class DLinkNode
{
// disabling unused variable warning
#pragma warning disable 0414
internal DLinkNode Last;
internal DLinkNode Next;
internal int[] Size;
#pragma warning restore 0414
public static int FinalCount = 0;
public DLinkNode(int SizeNum, DLinkNode LastObject, DLinkNode NextObject)
{
Last = LastObject;
Next = NextObject;
Size = new int[SizeNum * 1024];
}
~DLinkNode()
{
FinalCount++;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.IO;
namespace System.Net.NetworkInformation
{
internal static partial class StringParsingHelpers
{
private static readonly string[] s_newLineSeparator = new string[] { Environment.NewLine }; // Used for string splitting
internal static int ParseNumSocketConnections(string filePath, string protocolName)
{
if (!File.Exists(filePath))
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
// Parse the number of active connections out of /proc/net/sockstat
string sockstatFile = File.ReadAllText(filePath);
int indexOfTcp = sockstatFile.IndexOf(protocolName, StringComparison.Ordinal);
int endOfTcpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfTcp + 1, StringComparison.Ordinal);
string tcpLineData = sockstatFile.Substring(indexOfTcp, endOfTcpLine - indexOfTcp);
StringParser sockstatParser = new StringParser(tcpLineData, ' ');
sockstatParser.MoveNextOrFail(); // Skip "<name>:"
sockstatParser.MoveNextOrFail(); // Skip: "inuse"
return sockstatParser.ParseNextInt32();
}
internal static TcpConnectionInformation[] ParseActiveTcpConnectionsFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
{
if (!File.Exists(tcp4ConnectionsFile) || !File.Exists(tcp6ConnectionsFile))
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile);
string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string tcp6FileContents = File.ReadAllText(tcp6ConnectionsFile);
string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file.
TcpConnectionInformation[] connections = new TcpConnectionInformation[v4connections.Length + v6connections.Length - 2];
int index = 0;
// TCP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
connections[index++] = ParseTcpConnectionInformationFromLine(line);
}
// TCP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
connections[index++] = ParseTcpConnectionInformationFromLine(line);
}
return connections;
}
internal static IPEndPoint[] ParseActiveTcpListenersFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile)
{
if (!File.Exists(tcp4ConnectionsFile) || !File.Exists(tcp6ConnectionsFile))
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile);
string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string tcp6FileContents = File.ReadAllText(tcp6ConnectionsFile);
string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
/// First line is header in each file.
IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2];
int index = 0;
// TCP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
// TCP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
return endPoints;
}
public static IPEndPoint[] ParseActiveUdpListenersFromFiles(string udp4File, string udp6File)
{
if (!File.Exists(udp4File) || !File.Exists(udp6File))
{
throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform);
}
string udp4FileContents = File.ReadAllText(udp4File);
string[] v4connections = udp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
string udp6FileContents = File.ReadAllText(udp6File);
string[] v6connections = udp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries);
// First line is header in each file.
IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2];
int index = 0;
// UDP Connections
for (int i = 1; i < v4connections.Length; i++) // Skip first line header.
{
string line = v4connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
// UDP6 Connections
for (int i = 1; i < v6connections.Length; i++) // Skip first line header.
{
string line = v6connections[i];
IPEndPoint endPoint = ParseLocalConnectionInformation(line);
endPoints[index++] = endPoint;
}
return endPoints;
}
// Parsing logic for local and remote addresses and ports, as well as socket state.
internal static TcpConnectionInformation ParseTcpConnectionInformationFromLine(string line)
{
StringParser parser = new StringParser(line, ' ', skipEmpty: true);
parser.MoveNextOrFail(); // skip Index
string localAddressAndPort = parser.MoveAndExtractNext(); // local_address
IPEndPoint localEndPoint = ParseAddressAndPort(localAddressAndPort);
string remoteAddressAndPort = parser.MoveAndExtractNext(); // rem_address
IPEndPoint remoteEndPoint = ParseAddressAndPort(remoteAddressAndPort);
string socketStateHex = parser.MoveAndExtractNext();
int nativeTcpState;
if (!int.TryParse(socketStateHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out nativeTcpState))
{
throw ExceptionHelper.CreateForParseFailure();
}
TcpState tcpState = MapTcpState(nativeTcpState);
return new SimpleTcpConnectionInformation(localEndPoint, remoteEndPoint, tcpState);
}
// Common parsing logic for the local connection information.
private static IPEndPoint ParseLocalConnectionInformation(string line)
{
StringParser parser = new StringParser(line, ' ', skipEmpty: true);
parser.MoveNextOrFail(); // skip Index
string localAddressAndPort = parser.MoveAndExtractNext();
int indexOfColon = localAddressAndPort.IndexOf(':');
if (indexOfColon == -1)
{
throw ExceptionHelper.CreateForParseFailure();
}
string remoteAddressString = localAddressAndPort.Substring(0, indexOfColon);
IPAddress localIPAddress = ParseHexIPAddress(remoteAddressString);
string portString = localAddressAndPort.Substring(indexOfColon + 1, localAddressAndPort.Length - (indexOfColon + 1));
int localPort;
if (!int.TryParse(portString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out localPort))
{
throw ExceptionHelper.CreateForParseFailure();
}
return new IPEndPoint(localIPAddress, localPort);
}
private static IPEndPoint ParseAddressAndPort(string colonSeparatedAddress)
{
int indexOfColon = colonSeparatedAddress.IndexOf(':');
if (indexOfColon == -1)
{
throw ExceptionHelper.CreateForParseFailure();
}
string remoteAddressString = colonSeparatedAddress.Substring(0, indexOfColon);
IPAddress ipAddress = ParseHexIPAddress(remoteAddressString);
string portString = colonSeparatedAddress.Substring(indexOfColon + 1, colonSeparatedAddress.Length - (indexOfColon + 1));
int port;
if (!int.TryParse(portString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out port))
{
throw ExceptionHelper.CreateForParseFailure();
}
return new IPEndPoint(ipAddress, port);
}
// Maps from Linux TCP states to .NET TcpStates.
private static TcpState MapTcpState(int state)
{
return Interop.Sys.MapTcpState((int)state);
}
internal static IPAddress ParseHexIPAddress(string remoteAddressString)
{
if (remoteAddressString.Length <= 8) // IPv4 Address
{
return ParseIPv4HexString(remoteAddressString);
}
else if (remoteAddressString.Length == 32) // IPv6 Address
{
return ParseIPv6HexString(remoteAddressString);
}
else
{
throw ExceptionHelper.CreateForParseFailure();
}
}
// Simply converts the hex string into a long and uses the IPAddress(long) constructor.
// Strings passed to this method must be 8 or less characters in length (32-bit address).
private static IPAddress ParseIPv4HexString(string hexAddress)
{
IPAddress ipAddress;
long addressValue;
if (!long.TryParse(hexAddress, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out addressValue))
{
throw ExceptionHelper.CreateForParseFailure();
}
ipAddress = new IPAddress(addressValue);
return ipAddress;
}
// Parses a 128-bit IPv6 Address stored as a 32-character hex number.
// Strings passed to this must be 32 characters in length.
private static IPAddress ParseIPv6HexString(string hexAddress)
{
Debug.Assert(hexAddress.Length == 32);
byte[] addressBytes = new byte[16];
for (int i = 0; i < 16; i++)
{
addressBytes[i] = (byte)(HexToByte(hexAddress[(i * 2)])
+ HexToByte(hexAddress[(i * 2) + 1]));
}
IPAddress ipAddress = new IPAddress(addressBytes);
return ipAddress;
}
private static byte HexToByte(char val)
{
if (val <= '9' && val >= '0')
{
return (byte)(val - '0');
}
else if (val >= 'a' && val <= 'f')
{
return (byte)((val - 'a') + 10);
}
else if (val >= 'A' && val <= 'F')
{
return (byte)((val - 'A') + 10);
}
else
{
throw ExceptionHelper.CreateForParseFailure();
}
}
}
}
| |
/*
* 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.Impl.Cache.Store
{
using System.Collections;
using System.Diagnostics;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Resource;
using Apache.Ignite.Core.Impl.Unmanaged;
/// <summary>
/// Interop cache store.
/// </summary>
internal class CacheStore
{
/** */
private const byte OpLoadCache = 0;
/** */
private const byte OpLoad = 1;
/** */
private const byte OpLoadAll = 2;
/** */
private const byte OpPut = 3;
/** */
private const byte OpPutAll = 4;
/** */
private const byte OpRmv = 5;
/** */
private const byte OpRmvAll = 6;
/** */
private const byte OpSesEnd = 7;
/** */
private readonly bool _convertBinary;
/** Store. */
private readonly ICacheStore _store;
/** Session. */
private readonly CacheStoreSessionProxy _sesProxy;
/** */
private readonly long _handle;
/// <summary>
/// Initializes a new instance of the <see cref="CacheStore" /> class.
/// </summary>
/// <param name="store">Store.</param>
/// <param name="convertBinary">Whether to convert binary objects.</param>
/// <param name="registry">The handle registry.</param>
private CacheStore(ICacheStore store, bool convertBinary, HandleRegistry registry)
{
Debug.Assert(store != null);
_store = store;
_convertBinary = convertBinary;
_sesProxy = new CacheStoreSessionProxy();
ResourceProcessor.InjectStoreSession(store, _sesProxy);
_handle = registry.AllocateCritical(this);
}
/// <summary>
/// Creates interop cache store from a stream.
/// </summary>
/// <param name="memPtr">Memory pointer.</param>
/// <param name="registry">The handle registry.</param>
/// <returns>
/// Interop cache store.
/// </returns>
internal static CacheStore CreateInstance(long memPtr, HandleRegistry registry)
{
using (var stream = IgniteManager.Memory.Get(memPtr).GetStream())
{
var reader = BinaryUtils.Marshaller.StartUnmarshal(stream, BinaryMode.KeepBinary);
var className = reader.ReadString();
var convertBinary = reader.ReadBoolean();
var propertyMap = reader.ReadDictionaryAsGeneric<string, object>();
var store = IgniteUtils.CreateInstance<ICacheStore>(className);
IgniteUtils.SetProperties(store, propertyMap);
return new CacheStore(store, convertBinary, registry);
}
}
/// <summary>
/// Gets the handle.
/// </summary>
public long Handle
{
get { return _handle; }
}
/// <summary>
/// Initializes this instance with a grid.
/// </summary>
/// <param name="grid">Grid.</param>
public void Init(Ignite grid)
{
ResourceProcessor.Inject(_store, grid);
}
/// <summary>
/// Invokes a store operation.
/// </summary>
/// <param name="input">Input stream.</param>
/// <param name="cb">Callback.</param>
/// <param name="grid">Grid.</param>
/// <returns>Invocation result.</returns>
/// <exception cref="IgniteException">Invalid operation type: + opType</exception>
public int Invoke(IBinaryStream input, IUnmanagedTarget cb, Ignite grid)
{
IBinaryReader reader = grid.Marshaller.StartUnmarshal(input,
_convertBinary ? BinaryMode.Deserialize : BinaryMode.ForceBinary);
IBinaryRawReader rawReader = reader.GetRawReader();
int opType = rawReader.ReadByte();
// Setup cache sessoin for this invocation.
long sesId = rawReader.ReadLong();
CacheStoreSession ses = grid.HandleRegistry.Get<CacheStoreSession>(sesId, true);
ses.CacheName = rawReader.ReadString();
_sesProxy.SetSession(ses);
try
{
// Perform operation.
switch (opType)
{
case OpLoadCache:
_store.LoadCache((k, v) => WriteObjects(cb, grid, k, v), rawReader.ReadArray<object>());
break;
case OpLoad:
object val = _store.Load(rawReader.ReadObject<object>());
if (val != null)
WriteObjects(cb, grid, val);
break;
case OpLoadAll:
var keys = rawReader.ReadCollection();
var result = _store.LoadAll(keys);
foreach (DictionaryEntry entry in result)
WriteObjects(cb, grid, entry.Key, entry.Value);
break;
case OpPut:
_store.Write(rawReader.ReadObject<object>(), rawReader.ReadObject<object>());
break;
case OpPutAll:
_store.WriteAll(rawReader.ReadDictionary());
break;
case OpRmv:
_store.Delete(rawReader.ReadObject<object>());
break;
case OpRmvAll:
_store.DeleteAll(rawReader.ReadCollection());
break;
case OpSesEnd:
grid.HandleRegistry.Release(sesId);
_store.SessionEnd(rawReader.ReadBoolean());
break;
default:
throw new IgniteException("Invalid operation type: " + opType);
}
return 0;
}
finally
{
_sesProxy.ClearSession();
}
}
/// <summary>
/// Writes objects to the marshaller.
/// </summary>
/// <param name="cb">Optional callback.</param>
/// <param name="grid">Grid.</param>
/// <param name="objects">Objects.</param>
private static void WriteObjects(IUnmanagedTarget cb, Ignite grid, params object[] objects)
{
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
BinaryWriter writer = grid.Marshaller.StartMarshal(stream);
try
{
foreach (var obj in objects)
{
var obj0 = obj;
writer.WithDetach(w => w.WriteObject(obj0));
}
}
finally
{
grid.Marshaller.FinishMarshal(writer);
}
if (cb != null)
{
stream.SynchronizeOutput();
UnmanagedUtils.CacheStoreCallbackInvoke(cb, stream.MemoryPointer);
}
}
}
}
}
| |
using System;
namespace ClosedXML.Excel
{
internal class XLComment : XLFormattedText<IXLComment>, IXLComment
{
private XLCell _cell;
public XLComment(XLCell cell, IXLFontBase defaultFont = null, int? shapeId = null)
: base(defaultFont ?? XLFont.DefaultCommentFont)
{
Initialize(cell, shapeId: shapeId);
}
public XLComment(XLCell cell, XLFormattedText<IXLComment> defaultComment, IXLFontBase defaultFont, IXLDrawingStyle style)
: base(defaultComment, defaultFont)
{
Initialize(cell, style);
}
public XLComment(XLCell cell, String text, IXLFontBase defaultFont)
: base(text, defaultFont)
{
Initialize(cell);
}
#region IXLComment Members
public String Author { get; set; }
public IXLComment SetAuthor(String value)
{
Author = value;
return this;
}
public IXLRichString AddSignature()
{
AddText(Author + ":").SetBold();
return AddText(Environment.NewLine);
}
public void Delete()
{
_cell.DeleteComment();
}
#endregion IXLComment Members
#region IXLDrawing
public String Name { get; set; }
public String Description { get; set; }
public XLDrawingAnchor Anchor { get; set; }
public Boolean HorizontalFlip { get; set; }
public Boolean VerticalFlip { get; set; }
public Int32 Rotation { get; set; }
public Int32 ExtentLength { get; set; }
public Int32 ExtentWidth { get; set; }
public Int32 ShapeId { get; internal set; }
public Boolean Visible { get; set; }
public IXLComment SetVisible()
{
Visible = true;
return Container;
}
public IXLComment SetVisible(Boolean hidden)
{
Visible = hidden;
return Container;
}
public IXLDrawingPosition Position { get; private set; }
public Int32 ZOrder { get; set; }
public IXLComment SetZOrder(Int32 zOrder)
{
ZOrder = zOrder;
return Container;
}
public IXLDrawingStyle Style { get; private set; }
public IXLComment SetName(String name)
{
Name = name;
return Container;
}
public IXLComment SetDescription(String description)
{
Description = description;
return Container;
}
public IXLComment SetHorizontalFlip()
{
HorizontalFlip = true;
return Container;
}
public IXLComment SetHorizontalFlip(Boolean horizontalFlip)
{
HorizontalFlip = horizontalFlip;
return Container;
}
public IXLComment SetVerticalFlip()
{
VerticalFlip = true;
return Container;
}
public IXLComment SetVerticalFlip(Boolean verticalFlip)
{
VerticalFlip = verticalFlip;
return Container;
}
public IXLComment SetRotation(Int32 rotation)
{
Rotation = rotation;
return Container;
}
public IXLComment SetExtentLength(Int32 extentLength)
{
ExtentLength = extentLength;
return Container;
}
public IXLComment SetExtentWidth(Int32 extentWidth)
{
ExtentWidth = extentWidth;
return Container;
}
#endregion IXLDrawing
private void Initialize(XLCell cell, IXLDrawingStyle style = null, int? shapeId = null)
{
style = style ?? XLDrawingStyle.DefaultCommentStyle;
shapeId = shapeId ?? cell.Worksheet.Workbook.ShapeIdManager.GetNext();
Author = cell.Worksheet.Author;
Container = this;
Anchor = XLDrawingAnchor.MoveAndSizeWithCells;
Style = new XLDrawingStyle();
Int32 previousRowNumber = cell.Address.RowNumber;
Double previousRowOffset = 0;
if (previousRowNumber > 1)
{
previousRowNumber--;
if (cell.Worksheet.Internals.RowsCollection.TryGetValue(previousRowNumber, out XLRow previousRow))
previousRowOffset = Math.Max(0, previousRow.Height - 7);
else
previousRowOffset = Math.Max(0, cell.Worksheet.RowHeight - 7);
}
Position = new XLDrawingPosition
{
Column = cell.Address.ColumnNumber + 1,
ColumnOffset = 2,
Row = previousRowNumber,
RowOffset = previousRowOffset
};
ZOrder = cell.Worksheet.ZOrder++;
Style
.Margins.SetLeft(style.Margins.Left)
.Margins.SetRight(style.Margins.Right)
.Margins.SetTop(style.Margins.Top)
.Margins.SetBottom(style.Margins.Bottom)
.Margins.SetAutomatic(style.Margins.Automatic)
.Size.SetHeight(style.Size.Height)
.Size.SetWidth(style.Size.Width)
.ColorsAndLines.SetLineColor(style.ColorsAndLines.LineColor)
.ColorsAndLines.SetFillColor(style.ColorsAndLines.FillColor)
.ColorsAndLines.SetLineDash(style.ColorsAndLines.LineDash)
.ColorsAndLines.SetLineStyle(style.ColorsAndLines.LineStyle)
.ColorsAndLines.SetLineWeight(style.ColorsAndLines.LineWeight)
.ColorsAndLines.SetFillTransparency(style.ColorsAndLines.FillTransparency)
.ColorsAndLines.SetLineTransparency(style.ColorsAndLines.LineTransparency)
.Alignment.SetHorizontal(style.Alignment.Horizontal)
.Alignment.SetVertical(style.Alignment.Vertical)
.Alignment.SetDirection(style.Alignment.Direction)
.Alignment.SetOrientation(style.Alignment.Orientation)
.Alignment.SetAutomaticSize(style.Alignment.AutomaticSize)
.Properties.SetPositioning(style.Properties.Positioning)
.Protection.SetLocked(style.Protection.Locked)
.Protection.SetLockText(style.Protection.LockText);
_cell = cell;
ShapeId = shapeId.Value;
}
}
}
| |
using SFML.Graphics;
using SFML.System;
using SFML.Window;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Iris
{
public class Deathmatch : Gamestate
{
public ClientMailman Mailman { get; set; }
public ClientPlayer player;
public List<Actor> Players { get; set; }
public List<Projectile> Projectiles { get; set; }
public List<Sprite> BackgroundImages { get; set; }
public List<Sprite> BackgroundImagesFar { get; set; }
public List<Sprite> BackgroundTracks { get; set; }
public List<GameObject> GameObjects = new List<GameObject>();
public List<GameObject> BackgroundGameObjects = new List<GameObject>();
private Sprite mapSprite;
private byte[] mapBytes;
private int mapWidth;
private int mapHeight;
public static float MAPYOFFSET = 297f;
public static float MAPXOFFSET = 1300f;
private static RenderStates shader;
public static float shakeFactor = .8f;
public bool tunnel = false;
public int tunnelsTimer = 0;
public float interiorAlpha = 0;
public float gravity = 0.5f;
public float PlayerAimSphereRadius = 50;
public int shittyTimerDontUse = 0;
public bool devMode = false;
public float roundTimeLeft = 9001;
public float preRoundTimeLeft = 10;
public bool roundStarted = false;
public Actor firstPlacePlayer;
public bool resetMatch = false;
public SoundInstance trainSound, trainSoundExterior, trainSoundInterior;
public Deathmatch() : base()
{
Projectiles = new List<Projectile>();
BackgroundImages = new List<Sprite>();
BackgroundImagesFar = new List<Sprite>();
BackgroundTracks = new List<Sprite>();
BackgroundGameObjects = new List<GameObject>();
Players = new List<Actor>();
Mailman = new ClientMailman(this);
shader = new RenderStates(new Shader(null, "Content/bgPrlx.frag"));
Image mapImg = new Image("Content/mapCol.png");
mapBytes = mapImg.Pixels;
mapSprite = new Sprite(new Texture(mapImg));
mapWidth = (int)mapImg.Size.X;
mapHeight = (int)mapImg.Size.Y;
player = new ClientPlayer(this);
player.Pos = new Vector2f(46, 62);
Players.Add(player);
trainSoundExterior = new SoundInstance(Content.GetSound("trainSpeed2.wav"), 1f, 0, 15, true);
trainSoundInterior = new SoundInstance(Content.GetSound("trainSpeed0.wav"), 1, 0, 15, true);
trainSound = trainSoundExterior;
MainGame.Camera.Center = player.Pos - new Vector2f(0, 90);
}
public override void Update()
{
base.Update();
shittyTimerDontUse++;
roundStarted = true;
//Console.WriteLine(roundTimeLeft);
if (roundTimeLeft % 60 == 0 && !tunnel)
{
tunnel = true;
tunnelsTimer = 3;
}
if (roundTimeLeft < 15 && !resetMatch)
{
resetMatch = true;
player.gold = 100;
player.weapons = new List<Weapon>()
{
new Revolver(player),
null,
null,
null,
};
player.weapon = player.weapons[0];
MainGame.dm.Mailman.sendWeaponSwitch(0);
for (int i = 0; i < GameObjects.Count; i++)
{
if (GameObjects[i] is Coin)
GameObjects.RemoveAt(i);
}
}
if (roundTimeLeft > 15)
{
firstPlacePlayer = MainGame.dm.Players.OrderByDescending(x => x.gold).ThenBy(x => (int)x.UID).ToList()[0];
resetMatch = false;
}
if (Input.isKeyDown(Keyboard.Key.F1))
{
player.gold = 10000;
player.MaxJumps = 10000000;
player.Health = 1000000;
}
if (Input.isKeyOverride(Keyboard.Key.F12))
{
devMode = true;
player.MaxJumps = 10000;
player.JumpsLeft = 10000;
}
if (tunnelsTimer > 0)
if (shittyTimerDontUse % (60 * 2) == 0)
{
if (!tunnel)
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("TrainWhistle.wav"), 1, 0, 8));
//if (Input.isKeyTap(Keyboard.Key.C))
//{
tunnelsTimer--;
CliffFace c = new CliffFace();
BackgroundGameObjects.Add(c);
}
//if (Input.isKeyTap(Keyboard.Key.C))
//{
// tunnelsTimer = 5;
//}
if (Input.isKeyTap(Keyboard.Key.T))
{
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("fart.wav"), 0, 1));
}
tunnel = false;
Mailman.HandleMessages();
Players.ForEach(p => { p.Update(); });
Projectiles.ForEach(p => { p.Update(); });
GameObjects.ForEach(p => { p.Update(); });
BackgroundGameObjects.ForEach(p => { p.Update(); });
CheckProjectileCollisions();
ApplyShake();
if (MainGame.rand.Next(4) == 0)
for (int i = 0; i < 5; i++)
{
GameObjects.Add(new TrainDust(new Vector2f(60 + (i * 440) + MainGame.rand.Next(70), 215), (float)MainGame.rand.NextDouble() * 90));
GameObjects.Add(new TrainDust(new Vector2f(304 + (i * 440) + MainGame.rand.Next(70), 215), (float)MainGame.rand.NextDouble() * 90));
}
TrainDust td = new TrainDust(new Vector2f(2190 + MainGame.rand.Next(10), 75), (float)MainGame.rand.NextDouble() * 90, 2);
GameObjects.Add(td);
GameObjects.Add(new TrainDust(new Vector2f(1978 + MainGame.rand.Next(10), 75), (float)MainGame.rand.NextDouble() * 90, 1));
if (Input.isKeyTap(Keyboard.Key.LShift) && !player.Alive)
{
if (player.respawnTimer <= 0)
{
//Players.Remove(player);
//player = new ClientPlayer(this);
//Players.Add(player);
player.deathTimer = 0;
player.respawnTimer = player.respawnLength * 60;
player.Pos = new Vector2f(42 + MainGame.rand.Next(1000), 142);
player.Health = 100;
player.Alive = true;
}
//player.Pos = new Vector2f(MainGame.rand.Next(42,1800), 142);
//Mailman.SendRespawn(player.UID);
}
if (Input.isKeyDown(Keyboard.Key.P))
Console.WriteLine(player.Pos);
if (Input.isKeyDown(Keyboard.Key.R))
{
MainGame.Camera.Center += new Vector2f(MainGame.rand.Next(-4, 5) * shakeFactor / 5, MainGame.rand.Next(-4, 5) * shakeFactor / 5);
}
trainSound.Update();
Gui.Update();
}
public override void Draw()
{
base.Draw();
//MainGame.Camera.Center = player.Pos - new Vector2f(0,90);
Vector2f focus = player.Core +
new Vector2f(Input.screenMousePos.X - MainGame.WindowSize.X / 2,
Input.screenMousePos.Y - MainGame.WindowSize.Y / 2) * player.CrosshairCameraRatio;
if (Helper.Distance(player.Core, focus) > PlayerAimSphereRadius)
focus = player.Core + Helper.PolarToVector2(PlayerAimSphereRadius, player.AimAngle, 1, 1);//player.Core + Helper.normalize(focus) * 100;
Helper.MoveCameraTo(MainGame.Camera, focus, .04f);
if (MainGame.Camera.Center.Y > 180 - 90)
{
focus.Y = player.Pos.Y - 90;
MainGame.Camera.Center = new Vector2f(MainGame.Camera.Center.X, 180 - 90);
}
//Camera2D.returnCamera(player.ActorCenter +
// new Vector2(Main.screenMousePos.X - Main.graphics.PreferredBackBufferWidth / 2,
// Main.screenMousePos.Y - Main.graphics.PreferredBackBufferHeight / 2) *
// Main.graphics.GraphicsDevice.Viewport.AspectRatio / player.currentWeapon.viewDistance);
MainGame.window.SetView(MainGame.window.DefaultView);
shader.Shader.SetParameter("offsetY", MainGame.Camera.Center.Y);
RectangleShape rs = new RectangleShape
{
Size = new Vector2f(800, 600)
};
MainGame.window.Draw(rs, shader);
MainGame.window.SetView(MainGame.Camera);
//foreach (Sprite s in BackgroundImagesFar)
//{
// s.Position = new Vector2f(s.Position.X, 280 - MAPYOFFSET + (player.Pos.Y / 15));
//}
BackgroundImagesFar.ForEach(p => { p.Draw(MainGame.window, RenderStates.Default); });
BackgroundImages.ForEach(p => { p.Draw(MainGame.window, RenderStates.Default); });
BackgroundGameObjects.ForEach(p => { p.Draw(); });
BackgroundTracks.ForEach(p => { p.Draw(MainGame.window, RenderStates.Default); });
HandleBackground();
MainGame.window.Draw(new Sprite(Content.GetTexture("mapDecor.png")));
int insideY = 65;
if (player.Pos.Y > insideY)
{
//trainSoundExterior.volume = 1;
trainSound = trainSoundExterior;
// trainSoundInterior.volume = 0;
interiorAlpha += (255f - interiorAlpha) * .1f;
}
else
{
//trainSoundInterior.volume = 0;
interiorAlpha *= .95f;
//trainSound = trainSoundInterior;
//trainSoundExterior.volume = 0;
}
Render.Draw(Content.GetTexture("mapInterior.png"), new Vector2f(0, 0), new Color(255, 255, 255, (byte)interiorAlpha), new Vector2f(0, 0), 1, 0f);
// MainGame.window.Draw(new Sprite(Content.GetTexture("mapInterior.png")));
Players.ForEach(p => { p.Draw(); });
Projectiles.ForEach(p => { p.Draw(); });
GameObjects.ForEach(p => { p.Draw(); });
if (player.Pos.Y < insideY)
Render.Draw(Content.GetTexture("mapDecor.png"), new Vector2f(0, 0), new Color(255, 255, 255, (byte)(255 - interiorAlpha)), new Vector2f(0, 0), 1, 0f);
//MainGame.window.Draw(mapSprite);
Gui.Draw();
}
public bool MapCollide(int x, int y, CollideTypes types)
{
//check if OOB
if (x < 0 || x >= mapWidth || y < 0 || y >= mapHeight)
{
return false;
}
int index = (y * mapWidth + x) * 4;
byte r = mapBytes[index];
byte g = mapBytes[index + 1];
byte b = mapBytes[index + 2];
byte a = mapBytes[index + 3];
//only collide if black or green
if (types.HasFlag(CollideTypes.Hard) && a == 255 && r == 0 && g == 0 && b == 0) return true;
if (types.HasFlag(CollideTypes.Soft) && a == 255 && r == 0 && g == 255 && b == 0) return true;
return false;
}
public Actor GetPlayerWithUID(long id)
{
return Players.FirstOrDefault(p => p.UID == id);
}
public void CheckProjectileCollisions()
{
for (int i = 0; i < Projectiles.Count; i++)
{
if (Helper.Distance(Projectiles[i].Pos, player.Core) < 20)
{
//player.OnProjectileHit(Projectiles[i]);
//Projectiles[i].onPlayerHit(player);
}
for (int a = 0; a < Players.Count; a++)
{
if (Helper.Distance(Projectiles[i].Pos, Players[a].Core) < 20)
{
if (Projectiles[i].OwnerUID != Players[a].UID)
{
//Projectiles[i].onPlayerHit(Players[a]);
//Players[a].OnProjectileHit(Projectiles[i]);
}
}
}
}
}
public void Close()
{
Mailman.Disconnect();
}
private void ApplyShake()
{
if (player.Health == 0)
{
if (player.deathTimer > 0 && player.deathTimer < 20)
MainGame.Camera.Center += new Vector2f(MainGame.rand.Next(-20, 20), MainGame.rand.Next(-20, 20));
}
MainGame.Camera.Center += new Vector2f(((float)MainGame.rand.NextDouble() * 2f - 1f) * shakeFactor, ((float)MainGame.rand.NextDouble() * 2.5f - 1.25f) * shakeFactor);
}
public void HandleBackground()
{
for (int i = 0; i < 16; i++)
{
if (BackgroundImages.Count < i)
{
Sprite s = new Sprite(Content.GetTexture("background1.png"));
s.Position = new Vector2f((float)(s.Texture.Size.X * (i - 1)) - MAPXOFFSET, 225 - MAPYOFFSET);
BackgroundImages.Add(s);
}
}
for (int i = 0; i < 16; i++)
{
if (BackgroundImagesFar.Count < i)
{
Sprite s = new Sprite(Content.GetTexture("background1Far.png"));
s.Position = new Vector2f((float)(s.Texture.Size.X * (i - 1)) - MAPXOFFSET, 300 - MAPYOFFSET);
BackgroundImagesFar.Add(s);
}
}
for (int i = 0; i < 150; i++)
{
if (BackgroundTracks.Count < i)
{
Sprite s = new Sprite(Content.GetTexture("tracksBlur.png"));
s.Position = new Vector2f((float)((s.Texture.Size.X) * (i - 1)) - MAPXOFFSET, 515 - MAPYOFFSET);
BackgroundTracks.Add(s);
}
}
for (int i = 0; i < BackgroundImages.Count; i++) //Main Background
{
BackgroundImages[i].Position -= new Vector2f(1, 0);
if (BackgroundImages[i].Position.X < -BackgroundImages[i].Texture.Size.X - MAPXOFFSET)
BackgroundImages.RemoveAt(i);
}
for (int i = 0; i < BackgroundImagesFar.Count; i++) //Far Background
{
BackgroundImagesFar[i].Position -= new Vector2f(.2f, 0);
if (BackgroundImagesFar[i].Position.X < -BackgroundImagesFar[i].Texture.Size.X - MAPXOFFSET)
BackgroundImagesFar.RemoveAt(i);
}
for (int i = 0; i < BackgroundTracks.Count; i++) //Tracks
{
BackgroundTracks[i].Position -= new Vector2f(20, 0);
if (BackgroundTracks[i].Position.X < -BackgroundTracks[i].Texture.Size.X - MAPXOFFSET)
BackgroundTracks.RemoveAt(i);
}
}
}
[Flags]
public enum CollideTypes
{
Hard = 1,
Soft = 2,
HardOrSoft = 3
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.IO;
using Sce.Atf;
using Sce.Atf.Adaptation;
using Sce.Atf.Applications;
using Sce.Atf.Dom;
using Sce.Sled.Shared.Controls;
using Sce.Sled.Shared.Services;
using Sce.Sled.Shared.Utilities;
namespace Sce.Sled.Shared.Dom
{
/// <summary>
/// Complex Type for a project
/// </summary>
public class SledProjectFilesType : SledProjectFilesFolderType, IItemView, IResource, ISledProjectFilesTreeViewable
{
#region Persisted Stuff
/// <summary>
/// Get or set the asset directory attribute
/// </summary>
public string AssetDirectory
{
get
{
//
// Want to return an absolute path
//
var assetDir = GetAttribute<string>(SledSchema.SledProjectFilesType.assetdirectoryAttribute);
if (PathUtil.IsRelative(assetDir))
assetDir = SledUtil.GetAbsolutePath(assetDir, ProjectDirectory);
return assetDir;
}
set
{
//
// Try to store as a relative path
// from the project directory
//
var assetDir =
PathUtil.IsRelative(value)
? value
: SledUtil.GetRelativePath(value, ProjectDirectory);
SetAttribute(SledSchema.SledProjectFilesType.assetdirectoryAttribute, assetDir);
}
}
/// <summary>
/// Get or set the project's GUID
/// </summary>
public Guid Guid
{
get
{
var szGuid = GetAttribute<string>(SledSchema.SledProjectFilesType.guidAttribute);
var guid = string.IsNullOrEmpty(szGuid) ? Guid.NewGuid() : new Guid(szGuid);
return guid;
}
set
{
var guid = value;
if (guid == Guid.Empty)
guid = SledUtil.MakeXmlSafeGuid();
SetAttribute(SledSchema.SledProjectFilesType.guidAttribute, guid.ToString());
}
}
/// <summary>
/// Gets the Languages sequence
/// </summary>
public IList<SledProjectFilesLanguageType> Languages
{
get { return GetChildList<SledProjectFilesLanguageType>(SledSchema.SledProjectFilesType.LanguagesChild); }
}
/// <summary>
/// Gets the Watches sequence
/// </summary>
public IList<SledProjectFilesWatchType> Watches
{
get { return GetChildList<SledProjectFilesWatchType>(SledSchema.SledProjectFilesType.WatchesChild); }
}
/// <summary>
/// Gets the Roots sequence
/// </summary>
public IList<SledProjectFilesRootType> Roots
{
get { return GetChildList<SledProjectFilesRootType>(SledSchema.SledProjectFilesType.RootsChild); }
}
/// <summary>
/// Gets the UserSettings sequence
/// </summary>
public IList<SledProjectFilesUserSettingsType> UserSettings
{
get { return GetChildList<SledProjectFilesUserSettingsType>(SledSchema.SledProjectFilesType.UserSettingsChild); }
}
#endregion
#region Non-Persisted Stuff
/// <summary>
/// Get or set dirty
/// </summary>
public bool Dirty { get; set; }
/// <summary>
/// Gets the directory that the project file lives in
/// </summary>
public string ProjectDirectory
{
get { return Path.GetDirectoryName(AbsolutePath); }
}
/// <summary>
/// Gets the absolute path to the project file on disk
/// </summary>
public string AbsolutePath
{
get { return m_uri.LocalPath; }
}
/// <summary>
/// Gets all files in the project (recursively gathers them all)
/// </summary>
public ICollection<SledProjectFilesFileType> AllFiles
{
get
{
var lstFiles = new List<SledProjectFilesFileType>();
GatherFiles(this, ref lstFiles);
return lstFiles;
}
}
private static void GatherFiles(SledProjectFilesFolderType rootFolder, ref List<SledProjectFilesFileType> lstFiles)
{
// Add files from this folder
lstFiles.AddRange(rootFolder.Files);
// Search sub-folders
foreach (var folder in rootFolder.Folders)
GatherFiles(folder, ref lstFiles);
}
IEnumerable<ISledProjectFilesTreeViewable> ISledProjectFilesTreeViewable.Children
{
get
{
var children = new List<ISledProjectFilesTreeViewable>();
children.AddRange(Folders.AsIEnumerable<ISledProjectFilesTreeViewable>());
children.AddRange(Files.AsIEnumerable<ISledProjectFilesTreeViewable>());
return children;
}
}
#endregion
#region IItemView Interface
/// <summary>
/// Fills in or modifies the given display info for the item</summary>
/// <param name="item">Item</param>
/// <param name="info">Display info to update</param>
public new void GetInfo(object item, ItemInfo info)
{
info.Label = Name;
info.IsLeaf = false;
info.AllowLabelEdit = false;
info.Description = "Project: " + Name;
info.ImageIndex = info.GetImageIndex(Atf.Resources.FolderImage);
// Set source control status
{
if (s_sourceControlService == null)
s_sourceControlService = SledServiceInstance.TryGet<ISledSourceControlService>();
if (s_sourceControlService == null)
return;
if (!s_sourceControlService.CanUseSourceControl)
return;
var sourceControlStatus = s_sourceControlService.GetStatus(this);
switch (sourceControlStatus)
{
case SourceControlStatus.CheckedOut:
info.StateImageIndex = info.GetImageIndex(Atf.Resources.DocumentCheckOutImage);
break;
default:
info.StateImageIndex = Atf.Controls.TreeListView.InvalidImageIndex;
break;
}
}
}
#endregion
#region IResource Interface
/// <summary>
/// Gets a string identifying the type of the resource to the end-user</summary>
public string Type
{
get { return ToString(); }
}
/// <summary>
/// Get or set the path to the project file on disk
/// </summary>
public Uri Uri
{
get { return m_uri; }
set
{
var oldUri = m_uri;
m_uri = value;
if (oldUri != m_uri)
UriChanged.Raise(this, new UriChangedEventArgs(oldUri));
}
}
/// <summary>
/// Event that is raised after the resource's URI changes</summary>
public event EventHandler<UriChangedEventArgs> UriChanged;
#endregion
private Uri m_uri;
private static ISledSourceControlService s_sourceControlService;
}
/// <summary>
/// Sled project files type equality comparer class
/// </summary>
public class SledProjectFilesTypeEqualityComparer : IEqualityComparer<SledProjectFilesType>
{
/// <summary>
/// Check if two items are equal
/// </summary>
/// <param name="projFile1">Project file to be compared</param>
/// <param name="projFile2">Project file to be compared</param>
/// <returns>Less than zero: projFile1 is less than projFile2. Zero: projFile1 equals projFile2. Greater than zero: projFile1 is greater than projFile2.</returns>
public bool Equals(SledProjectFilesType projFile1, SledProjectFilesType projFile2)
{
return
((projFile1.Guid == projFile2.Guid) &&
(string.Compare(projFile1.Name, projFile2.Name, StringComparison.OrdinalIgnoreCase) == 0));
}
/// <summary>
/// Get a hash code for an item
/// </summary>
/// <param name="projFile">Base object to get hash code from</param>
/// <returns>Hash code of project file</returns>
public int GetHashCode(SledProjectFilesType projFile)
{
return projFile.GetHashCode();
}
}
/// <summary>
/// Complex Type for an empty project
/// </summary>
public class SledProjectFilesEmptyType : DomNodeAdapter, IItemView
{
#region Implementation of IItemView
/// <summary>
/// Fills in or modifies the given display info for the item</summary>
/// <param name="item">Item</param>
/// <param name="info">Display info to update</param>
public void GetInfo(object item, ItemInfo info)
{
info.AllowLabelEdit = false;
info.IsLeaf = true;
info.Label = Name;
}
#endregion
/// <summary>
/// Get or set the name
/// </summary>
public string Name
{
get { return GetAttribute<string>(SledSchema.SledProjectFilesEmptyType.nameAttribute); }
set { SetAttribute(SledSchema.SledProjectFilesEmptyType.nameAttribute, value); }
}
}
}
| |
namespace MathGame
{
partial class frmMain
{
/// <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(frmMain));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.mnuFile = new System.Windows.Forms.ToolStripMenuItem();
this.mnuNewGame = new System.Windows.Forms.ToolStripMenuItem();
this.mnuOpen = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuSave = new System.Windows.Forms.ToolStripMenuItem();
this.mnuSaveAs = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuQuit = new System.Windows.Forms.ToolStripMenuItem();
this.directionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuObjective = new System.Windows.Forms.ToolStripMenuItem();
this.mnuHowTo = new System.Windows.Forms.ToolStripMenuItem();
this.mnuOrder = new System.Windows.Forms.ToolStripMenuItem();
this.mnuSpecial = new System.Windows.Forms.ToolStripMenuItem();
this.mnuHints = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuSound = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuAboutMathGame = new System.Windows.Forms.ToolStripMenuItem();
this.txtEquation = new System.Windows.Forms.TextBox();
this.btnNum0 = new System.Windows.Forms.Button();
this.btnNum1 = new System.Windows.Forms.Button();
this.btnNum2 = new System.Windows.Forms.Button();
this.btnNum3 = new System.Windows.Forms.Button();
this.btnNum4 = new System.Windows.Forms.Button();
this.btnNum5 = new System.Windows.Forms.Button();
this.btnNum6 = new System.Windows.Forms.Button();
this.btnNum7 = new System.Windows.Forms.Button();
this.btnNum8 = new System.Windows.Forms.Button();
this.btnNum9 = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.btnSubtract = new System.Windows.Forms.Button();
this.btnMultiply = new System.Windows.Forms.Button();
this.btnDivide = new System.Windows.Forms.Button();
this.btnParLeft = new System.Windows.Forms.Button();
this.btnParRight = new System.Windows.Forms.Button();
this.btnEquals = new System.Windows.Forms.Button();
this.btnUndo = new System.Windows.Forms.Button();
this.lblTurn = new System.Windows.Forms.Label();
this.btnNextTurn = new System.Windows.Forms.Button();
this.btnBest = new System.Windows.Forms.Button();
this.btnCanI = new System.Windows.Forms.Button();
this.btnCompare = new System.Windows.Forms.Button();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFile,
this.directionsToolStripMenuItem,
this.optionsToolStripMenuItem,
this.aboutToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(676, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "mnuMain";
//
// mnuFile
//
this.mnuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuNewGame,
this.mnuOpen,
this.toolStripSeparator2,
this.mnuSave,
this.mnuSaveAs,
this.toolStripSeparator1,
this.mnuQuit});
this.mnuFile.Name = "mnuFile";
this.mnuFile.Size = new System.Drawing.Size(35, 20);
this.mnuFile.Text = "&File";
//
// mnuNewGame
//
this.mnuNewGame.Image = ((System.Drawing.Image)(resources.GetObject("mnuNewGame.Image")));
this.mnuNewGame.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuNewGame.Name = "mnuNewGame";
this.mnuNewGame.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.mnuNewGame.Size = new System.Drawing.Size(200, 30);
this.mnuNewGame.Text = "&New Game";
this.mnuNewGame.Click += new System.EventHandler(this.mnuNewGame_Click);
//
// mnuOpen
//
this.mnuOpen.Image = ((System.Drawing.Image)(resources.GetObject("mnuOpen.Image")));
this.mnuOpen.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuOpen.Name = "mnuOpen";
this.mnuOpen.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.mnuOpen.Size = new System.Drawing.Size(200, 30);
this.mnuOpen.Text = "&Open Game";
this.mnuOpen.Click += new System.EventHandler(this.mnuOpen_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(197, 6);
//
// mnuSave
//
this.mnuSave.Image = ((System.Drawing.Image)(resources.GetObject("mnuSave.Image")));
this.mnuSave.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuSave.Name = "mnuSave";
this.mnuSave.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.mnuSave.Size = new System.Drawing.Size(200, 30);
this.mnuSave.Text = "&Save";
this.mnuSave.Click += new System.EventHandler(this.mnuSave_Click);
//
// mnuSaveAs
//
this.mnuSaveAs.Image = ((System.Drawing.Image)(resources.GetObject("mnuSaveAs.Image")));
this.mnuSaveAs.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuSaveAs.Name = "mnuSaveAs";
this.mnuSaveAs.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.S)));
this.mnuSaveAs.Size = new System.Drawing.Size(200, 30);
this.mnuSaveAs.Text = "Save &As";
this.mnuSaveAs.Click += new System.EventHandler(this.mnuSaveAs_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(197, 6);
//
// mnuQuit
//
this.mnuQuit.Image = ((System.Drawing.Image)(resources.GetObject("mnuQuit.Image")));
this.mnuQuit.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuQuit.Name = "mnuQuit";
this.mnuQuit.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4)));
this.mnuQuit.Size = new System.Drawing.Size(200, 30);
this.mnuQuit.Text = "&Quit";
this.mnuQuit.Click += new System.EventHandler(this.mnuQuit_Click);
//
// directionsToolStripMenuItem
//
this.directionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuObjective,
this.mnuHowTo,
this.mnuOrder,
this.mnuSpecial,
this.mnuHints});
this.directionsToolStripMenuItem.Name = "directionsToolStripMenuItem";
this.directionsToolStripMenuItem.Size = new System.Drawing.Size(66, 20);
this.directionsToolStripMenuItem.Text = "&Directions";
//
// mnuObjective
//
this.mnuObjective.Image = global::MathGame.Properties.Resources.directions;
this.mnuObjective.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuObjective.Name = "mnuObjective";
this.mnuObjective.Size = new System.Drawing.Size(192, 30);
this.mnuObjective.Text = "Objective";
this.mnuObjective.Click += new System.EventHandler(this.objectiveToolStripMenuItem_Click);
//
// mnuHowTo
//
this.mnuHowTo.Image = global::MathGame.Properties.Resources.howtomove;
this.mnuHowTo.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuHowTo.Name = "mnuHowTo";
this.mnuHowTo.Size = new System.Drawing.Size(192, 30);
this.mnuHowTo.Text = "How To Move";
this.mnuHowTo.Click += new System.EventHandler(this.howToMoveToolStripMenuItem_Click);
//
// mnuOrder
//
this.mnuOrder.Image = global::MathGame.Properties.Resources.operations;
this.mnuOrder.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuOrder.Name = "mnuOrder";
this.mnuOrder.Size = new System.Drawing.Size(192, 30);
this.mnuOrder.Text = "Order Of Operations";
this.mnuOrder.Click += new System.EventHandler(this.mnuOrder_Click);
//
// mnuSpecial
//
this.mnuSpecial.Image = global::MathGame.Properties.Resources.directions;
this.mnuSpecial.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuSpecial.Name = "mnuSpecial";
this.mnuSpecial.Size = new System.Drawing.Size(192, 30);
this.mnuSpecial.Text = "Special Moves";
this.mnuSpecial.Click += new System.EventHandler(this.mnuSpecial_Click);
//
// mnuHints
//
this.mnuHints.Image = global::MathGame.Properties.Resources.directions;
this.mnuHints.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuHints.Name = "mnuHints";
this.mnuHints.Size = new System.Drawing.Size(192, 30);
this.mnuHints.Text = "Hints";
this.mnuHints.Click += new System.EventHandler(this.mnuHints_Click);
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuSound});
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(56, 20);
this.optionsToolStripMenuItem.Text = "Options";
//
// mnuSound
//
this.mnuSound.Checked = true;
this.mnuSound.CheckOnClick = true;
this.mnuSound.CheckState = System.Windows.Forms.CheckState.Checked;
this.mnuSound.Image = global::MathGame.Properties.Resources.sound;
this.mnuSound.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuSound.Name = "mnuSound";
this.mnuSound.Size = new System.Drawing.Size(123, 30);
this.mnuSound.Text = "Sound";
this.mnuSound.Click += new System.EventHandler(this.mnuSound_Click);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuAboutMathGame});
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.aboutToolStripMenuItem.Text = "&About";
//
// mnuAboutMathGame
//
this.mnuAboutMathGame.Image = ((System.Drawing.Image)(resources.GetObject("mnuAboutMathGame.Image")));
this.mnuAboutMathGame.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.mnuAboutMathGame.Name = "mnuAboutMathGame";
this.mnuAboutMathGame.Size = new System.Drawing.Size(179, 30);
this.mnuAboutMathGame.Text = "About Math Game";
this.mnuAboutMathGame.Click += new System.EventHandler(this.mnuAboutMathGame_Click);
//
// txtEquation
//
this.txtEquation.Enabled = false;
this.txtEquation.Location = new System.Drawing.Point(91, 29);
this.txtEquation.Name = "txtEquation";
this.txtEquation.Size = new System.Drawing.Size(216, 20);
this.txtEquation.TabIndex = 1;
//
// btnNum0
//
this.btnNum0.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum0.Location = new System.Drawing.Point(13, 55);
this.btnNum0.Name = "btnNum0";
this.btnNum0.Size = new System.Drawing.Size(24, 23);
this.btnNum0.TabIndex = 2;
this.btnNum0.Text = "0";
this.btnNum0.UseVisualStyleBackColor = true;
this.btnNum0.Click += new System.EventHandler(this.btnNum0_Click);
//
// btnNum1
//
this.btnNum1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum1.Location = new System.Drawing.Point(43, 55);
this.btnNum1.Name = "btnNum1";
this.btnNum1.Size = new System.Drawing.Size(24, 23);
this.btnNum1.TabIndex = 3;
this.btnNum1.Text = "1";
this.btnNum1.UseVisualStyleBackColor = true;
this.btnNum1.Click += new System.EventHandler(this.btnNum1_Click);
//
// btnNum2
//
this.btnNum2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum2.Location = new System.Drawing.Point(73, 55);
this.btnNum2.Name = "btnNum2";
this.btnNum2.Size = new System.Drawing.Size(24, 23);
this.btnNum2.TabIndex = 4;
this.btnNum2.Text = "2";
this.btnNum2.UseVisualStyleBackColor = true;
this.btnNum2.Click += new System.EventHandler(this.btnNum2_Click);
//
// btnNum3
//
this.btnNum3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum3.Location = new System.Drawing.Point(103, 55);
this.btnNum3.Name = "btnNum3";
this.btnNum3.Size = new System.Drawing.Size(24, 23);
this.btnNum3.TabIndex = 5;
this.btnNum3.Text = "3";
this.btnNum3.UseVisualStyleBackColor = true;
this.btnNum3.Click += new System.EventHandler(this.btnNum3_Click);
//
// btnNum4
//
this.btnNum4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum4.Location = new System.Drawing.Point(133, 55);
this.btnNum4.Name = "btnNum4";
this.btnNum4.Size = new System.Drawing.Size(24, 23);
this.btnNum4.TabIndex = 6;
this.btnNum4.Text = "4";
this.btnNum4.UseVisualStyleBackColor = true;
this.btnNum4.Click += new System.EventHandler(this.btnNum4_Click);
//
// btnNum5
//
this.btnNum5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum5.Location = new System.Drawing.Point(163, 55);
this.btnNum5.Name = "btnNum5";
this.btnNum5.Size = new System.Drawing.Size(24, 23);
this.btnNum5.TabIndex = 7;
this.btnNum5.Text = "5";
this.btnNum5.UseVisualStyleBackColor = true;
this.btnNum5.Click += new System.EventHandler(this.btnNum5_Click);
//
// btnNum6
//
this.btnNum6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum6.Location = new System.Drawing.Point(193, 55);
this.btnNum6.Name = "btnNum6";
this.btnNum6.Size = new System.Drawing.Size(24, 23);
this.btnNum6.TabIndex = 8;
this.btnNum6.Text = "6";
this.btnNum6.UseVisualStyleBackColor = true;
this.btnNum6.Click += new System.EventHandler(this.btnNum6_Click);
//
// btnNum7
//
this.btnNum7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum7.Location = new System.Drawing.Point(223, 55);
this.btnNum7.Name = "btnNum7";
this.btnNum7.Size = new System.Drawing.Size(24, 23);
this.btnNum7.TabIndex = 9;
this.btnNum7.Text = "7";
this.btnNum7.UseVisualStyleBackColor = true;
this.btnNum7.Click += new System.EventHandler(this.btnNum7_Click);
//
// btnNum8
//
this.btnNum8.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum8.Location = new System.Drawing.Point(253, 55);
this.btnNum8.Name = "btnNum8";
this.btnNum8.Size = new System.Drawing.Size(24, 23);
this.btnNum8.TabIndex = 10;
this.btnNum8.Text = "8";
this.btnNum8.UseVisualStyleBackColor = true;
this.btnNum8.Click += new System.EventHandler(this.btnNum8_Click);
//
// btnNum9
//
this.btnNum9.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNum9.Location = new System.Drawing.Point(283, 55);
this.btnNum9.Name = "btnNum9";
this.btnNum9.Size = new System.Drawing.Size(24, 23);
this.btnNum9.TabIndex = 11;
this.btnNum9.Text = "9";
this.btnNum9.UseVisualStyleBackColor = true;
this.btnNum9.Click += new System.EventHandler(this.btnNum9_Click);
//
// btnAdd
//
this.btnAdd.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnAdd.Location = new System.Drawing.Point(313, 55);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(24, 23);
this.btnAdd.TabIndex = 12;
this.btnAdd.Text = "+";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnSubtract
//
this.btnSubtract.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSubtract.Location = new System.Drawing.Point(343, 55);
this.btnSubtract.Name = "btnSubtract";
this.btnSubtract.Size = new System.Drawing.Size(24, 23);
this.btnSubtract.TabIndex = 13;
this.btnSubtract.Text = "-";
this.btnSubtract.UseVisualStyleBackColor = true;
this.btnSubtract.Click += new System.EventHandler(this.btnSubtract_Click);
//
// btnMultiply
//
this.btnMultiply.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnMultiply.Location = new System.Drawing.Point(373, 55);
this.btnMultiply.Name = "btnMultiply";
this.btnMultiply.Size = new System.Drawing.Size(24, 23);
this.btnMultiply.TabIndex = 14;
this.btnMultiply.Text = "x";
this.btnMultiply.UseVisualStyleBackColor = true;
this.btnMultiply.Click += new System.EventHandler(this.btnMultiply_Click);
//
// btnDivide
//
this.btnDivide.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnDivide.Location = new System.Drawing.Point(403, 55);
this.btnDivide.Name = "btnDivide";
this.btnDivide.Size = new System.Drawing.Size(24, 23);
this.btnDivide.TabIndex = 15;
this.btnDivide.Text = "/";
this.btnDivide.UseVisualStyleBackColor = true;
this.btnDivide.Click += new System.EventHandler(this.btnDivide_Click);
//
// btnParLeft
//
this.btnParLeft.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnParLeft.Location = new System.Drawing.Point(433, 55);
this.btnParLeft.Name = "btnParLeft";
this.btnParLeft.Size = new System.Drawing.Size(24, 23);
this.btnParLeft.TabIndex = 16;
this.btnParLeft.Text = "(";
this.btnParLeft.UseVisualStyleBackColor = true;
this.btnParLeft.Click += new System.EventHandler(this.btnParLeft_Click);
//
// btnParRight
//
this.btnParRight.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnParRight.Location = new System.Drawing.Point(463, 55);
this.btnParRight.Name = "btnParRight";
this.btnParRight.Size = new System.Drawing.Size(24, 23);
this.btnParRight.TabIndex = 17;
this.btnParRight.Text = ")";
this.btnParRight.UseVisualStyleBackColor = true;
this.btnParRight.Click += new System.EventHandler(this.btnParRight_Click);
//
// btnEquals
//
this.btnEquals.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnEquals.Location = new System.Drawing.Point(493, 55);
this.btnEquals.Name = "btnEquals";
this.btnEquals.Size = new System.Drawing.Size(24, 23);
this.btnEquals.TabIndex = 18;
this.btnEquals.Text = "=";
this.btnEquals.UseVisualStyleBackColor = true;
this.btnEquals.Click += new System.EventHandler(this.btnEquals_Click);
//
// btnUndo
//
this.btnUndo.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnUndo.Location = new System.Drawing.Point(523, 55);
this.btnUndo.Name = "btnUndo";
this.btnUndo.Size = new System.Drawing.Size(52, 23);
this.btnUndo.TabIndex = 19;
this.btnUndo.Text = "Undo";
this.btnUndo.UseVisualStyleBackColor = true;
this.btnUndo.Click += new System.EventHandler(this.btnUndo_Click);
//
// lblTurn
//
this.lblTurn.AutoSize = true;
this.lblTurn.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTurn.Location = new System.Drawing.Point(12, 32);
this.lblTurn.Name = "lblTurn";
this.lblTurn.Size = new System.Drawing.Size(73, 13);
this.lblTurn.TabIndex = 20;
this.lblTurn.Text = "Player One:";
//
// btnNextTurn
//
this.btnNextTurn.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNextTurn.Location = new System.Drawing.Point(581, 27);
this.btnNextTurn.Name = "btnNextTurn";
this.btnNextTurn.Size = new System.Drawing.Size(84, 51);
this.btnNextTurn.TabIndex = 21;
this.btnNextTurn.Text = "Start Game";
this.btnNextTurn.UseVisualStyleBackColor = true;
this.btnNextTurn.Click += new System.EventHandler(this.btnNextTurn_Click);
//
// btnBest
//
this.btnBest.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnBest.Location = new System.Drawing.Point(403, 27);
this.btnBest.Name = "btnBest";
this.btnBest.Size = new System.Drawing.Size(84, 23);
this.btnBest.TabIndex = 22;
this.btnBest.Text = "Best (2)";
this.btnBest.UseVisualStyleBackColor = true;
this.btnBest.Click += new System.EventHandler(this.btnBest_Click);
//
// btnCanI
//
this.btnCanI.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCanI.Location = new System.Drawing.Point(493, 27);
this.btnCanI.Name = "btnCanI";
this.btnCanI.Size = new System.Drawing.Size(82, 23);
this.btnCanI.TabIndex = 23;
this.btnCanI.Text = "Can I? (2)";
this.btnCanI.UseVisualStyleBackColor = true;
this.btnCanI.Click += new System.EventHandler(this.btnCanI_Click);
//
// btnCompare
//
this.btnCompare.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCompare.Location = new System.Drawing.Point(313, 27);
this.btnCompare.Name = "btnCompare";
this.btnCompare.Size = new System.Drawing.Size(84, 23);
this.btnCompare.TabIndex = 24;
this.btnCompare.Text = "Compare";
this.btnCompare.UseVisualStyleBackColor = true;
this.btnCompare.Click += new System.EventHandler(this.btnCompare_Click);
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(676, 570);
this.Controls.Add(this.btnCompare);
this.Controls.Add(this.btnCanI);
this.Controls.Add(this.btnBest);
this.Controls.Add(this.btnNextTurn);
this.Controls.Add(this.lblTurn);
this.Controls.Add(this.btnUndo);
this.Controls.Add(this.btnEquals);
this.Controls.Add(this.btnParRight);
this.Controls.Add(this.btnParLeft);
this.Controls.Add(this.btnDivide);
this.Controls.Add(this.btnMultiply);
this.Controls.Add(this.btnSubtract);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnNum9);
this.Controls.Add(this.btnNum8);
this.Controls.Add(this.btnNum7);
this.Controls.Add(this.btnNum6);
this.Controls.Add(this.btnNum5);
this.Controls.Add(this.btnNum4);
this.Controls.Add(this.btnNum3);
this.Controls.Add(this.btnNum2);
this.Controls.Add(this.btnNum1);
this.Controls.Add(this.btnNum0);
this.Controls.Add(this.txtEquation);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(684, 604);
this.MinimumSize = new System.Drawing.Size(684, 604);
this.Name = "frmMain";
this.Text = "Math Game";
this.Load += new System.EventHandler(this.frmMain_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem mnuFile;
private System.Windows.Forms.ToolStripMenuItem mnuNewGame;
private System.Windows.Forms.ToolStripMenuItem mnuQuit;
private System.Windows.Forms.TextBox txtEquation;
private System.Windows.Forms.Button btnNum0;
private System.Windows.Forms.Button btnNum1;
private System.Windows.Forms.Button btnNum2;
private System.Windows.Forms.Button btnNum3;
private System.Windows.Forms.Button btnNum4;
private System.Windows.Forms.Button btnNum5;
private System.Windows.Forms.Button btnNum6;
private System.Windows.Forms.Button btnNum7;
private System.Windows.Forms.Button btnNum8;
private System.Windows.Forms.Button btnNum9;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnSubtract;
private System.Windows.Forms.Button btnMultiply;
private System.Windows.Forms.Button btnDivide;
private System.Windows.Forms.Button btnParLeft;
private System.Windows.Forms.Button btnParRight;
private System.Windows.Forms.Button btnEquals;
private System.Windows.Forms.Button btnUndo;
private System.Windows.Forms.Label lblTurn;
private System.Windows.Forms.Button btnNextTurn;
private System.Windows.Forms.Button btnBest;
private System.Windows.Forms.Button btnCanI;
private System.Windows.Forms.Button btnCompare;
private System.Windows.Forms.ToolStripMenuItem directionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mnuObjective;
private System.Windows.Forms.ToolStripMenuItem mnuHowTo;
private System.Windows.Forms.ToolStripMenuItem mnuOrder;
private System.Windows.Forms.ToolStripMenuItem mnuSpecial;
private System.Windows.Forms.ToolStripMenuItem mnuHints;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mnuAboutMathGame;
private System.Windows.Forms.ToolStripMenuItem mnuOpen;
private System.Windows.Forms.ToolStripMenuItem mnuSave;
private System.Windows.Forms.ToolStripMenuItem mnuSaveAs;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mnuSound;
}
}
| |
// 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 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for AccountOperations.
/// </summary>
public static partial class AccountOperationsExtensions
{
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
public static DataLakeStoreAccount Create(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccount parameters)
{
return operations.CreateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> CreateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccount parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
public static DataLakeStoreAccount Update(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters)
{
return operations.UpdateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> UpdateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
public static void Delete(this IAccountOperations operations, string resourceGroupName, string name)
{
operations.DeleteAsync(resourceGroupName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IAccountOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to retrieve.
/// </param>
public static DataLakeStoreAccount Get(this IAccountOperations operations, string resourceGroupName, string name)
{
return operations.GetAsync(resourceGroupName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to retrieve.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> GetAsync(this IAccountOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Attempts to enable a user managed key vault for encryption of the specified
/// Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to attempt to enable the Key Vault
/// for.
/// </param>
public static void EnableKeyVault(this IAccountOperations operations, string resourceGroupName, string accountName)
{
operations.EnableKeyVaultAsync(resourceGroupName, accountName).GetAwaiter().GetResult();
}
/// <summary>
/// Attempts to enable a user managed key vault for encryption of the specified
/// Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to attempt to enable the Key Vault
/// for.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task EnableKeyVaultAsync(this IAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.EnableKeyVaultWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource group. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account(s).
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// A Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
public static IPage<DataLakeStoreAccount> ListByResourceGroup(this IAccountOperations operations, string resourceGroupName, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?))
{
return operations.ListByResourceGroupAsync(resourceGroupName, odataQuery, select, count).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource group. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account(s).
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// A Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccount>> ListByResourceGroupAsync(this IAccountOperations operations, string resourceGroupName, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, odataQuery, select, count, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The response
/// includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
public static IPage<DataLakeStoreAccount> List(this IAccountOperations operations, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?))
{
return operations.ListAsync(odataQuery, select, count).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The response
/// includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccount>> ListAsync(this IAccountOperations operations, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, select, count, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
public static DataLakeStoreAccount BeginCreate(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccount parameters)
{
return operations.BeginCreateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> BeginCreateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccount parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
public static DataLakeStoreAccount BeginUpdate(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters)
{
return operations.BeginUpdateAsync(resourceGroupName, name, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DataLakeStoreAccount> BeginUpdateAsync(this IAccountOperations operations, string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, name, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
public static void BeginDelete(this IAccountOperations operations, string resourceGroupName, string name)
{
operations.BeginDeleteAsync(resourceGroupName, name).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IAccountOperations operations, string resourceGroupName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, name, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource group. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<DataLakeStoreAccount> ListByResourceGroupNext(this IAccountOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource group. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccount>> ListByResourceGroupNextAsync(this IAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The response
/// includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<DataLakeStoreAccount> ListNext(this IAccountOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The response
/// includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DataLakeStoreAccount>> ListNextAsync(this IAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Factotum
{
public partial class GridProcedureView : Form
{
// ----------------------------------------------------------------------
// Initialization
// ----------------------------------------------------------------------
// Form constructor
public GridProcedureView()
{
InitializeComponent();
// Take care of settings that are not easily managed in the designer.
InitializeControls();
}
// Take care of settings that are not easily managed in the designer.
private void InitializeControls()
{
// Set these combos to their defaults
cboStatusFilter.SelectedIndex = (int)FilterActiveStatus.ShowActive;
cboInOutageFilter.SelectedIndex = Globals.IsMasterDB ?
(int)FilterYesNoAll.ShowAll : (int)FilterYesNoAll.Yes;
}
// Set the status filter to show active tools by default
// and update the tool selector combo box
private void GridProcedureView_Load(object sender, EventArgs e)
{
// Set the status combo first. The selector DataGridView depends on it.
cboStatusFilter.SelectedIndex = (int)FilterActiveStatus.ShowActive;
// Apply the current filters and set the selector row.
// Passing a null selects the first row if there are any rows.
UpdateSelector(null);
// Now that we have some rows and columns, we can do some customization.
CustomizeGrid();
// Need to do this because the customization clears the row selection.
SelectGridRow(null);
// We don't want these to get triggered except by the user
this.cboInOutageFilter.SelectedIndexChanged += new System.EventHandler(this.cboInOutageFilter_SelectedIndexChanged);
// Wire up the handler for the Entity changed event
EGridProcedure.Changed += new EventHandler<EntityChangedEventArgs>(EGridProcedure_Changed);
EGridProcedure.GridProcedureOutageAssignmentsChanged += new EventHandler(EGridProcedure_GridProcedureOutageAssignmentsChanged);
}
private void GridProcedureView_FormClosed(object sender, FormClosedEventArgs e)
{
EGridProcedure.Changed -= new EventHandler<EntityChangedEventArgs>(EGridProcedure_Changed);
EGridProcedure.GridProcedureOutageAssignmentsChanged -= new EventHandler(EGridProcedure_GridProcedureOutageAssignmentsChanged);
}
// ----------------------------------------------------------------------
// Event Handlers
// ----------------------------------------------------------------------
// If any of this type of entity object was saved or deleted, we want to update the selector
// The event args contain the ID of the entity that was added, mofified or deleted.
void EGridProcedure_Changed(object sender, EntityChangedEventArgs e)
{
UpdateSelector(e.ID);
}
void EGridProcedure_GridProcedureOutageAssignmentsChanged(object sender, EventArgs e)
{
UpdateSelector(null);
}
// Handle the user's decision to edit the current tool
private void EditCurrentSelection()
{
// Make sure there's a row selected
if (dgvGridProcedureList.SelectedRows.Count != 1) return;
Guid? currentEditItem = (Guid?)(dgvGridProcedureList.SelectedRows[0].Cells["ID"].Value);
// First check to see if an instance of the form set to the selected ID already exists
if (!Globals.CanActivateForm(this, "GridProcedureEdit", currentEditItem))
{
// Open the edit form with the currently selected ID.
GridProcedureEdit frm = new GridProcedureEdit(currentEditItem);
frm.MdiParent = this.MdiParent;
frm.Show();
}
}
// This handles the datagridview double-click as well as button click
void btnEdit_Click(object sender, System.EventArgs e)
{
EditCurrentSelection();
}
private void dgvGridProcedureList_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
EditCurrentSelection();
}
// Handle the user's decision to add a new tool
private void btnAdd_Click(object sender, EventArgs e)
{
GridProcedureEdit frm = new GridProcedureEdit();
frm.MdiParent = this.MdiParent;
frm.Show();
}
// Handle the user's decision to delete the selected tool
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvGridProcedureList.SelectedRows.Count != 1)
{
MessageBox.Show("Please select a Grid Procedure to delete first.","Factotum");
return;
}
Guid? currentEditItem = (Guid?)(dgvGridProcedureList.SelectedRows[0].Cells["ID"].Value);
if (Globals.IsFormOpen(this, "GridProcedureEdit", currentEditItem))
{
MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum");
return;
}
EGridProcedure GridProcedure = new EGridProcedure(currentEditItem);
GridProcedure.Delete(true);
if (GridProcedure.GridProcedureErrMsg != null)
{
MessageBox.Show(GridProcedure.GridProcedureErrMsg, "Factotum");
GridProcedure.GridProcedureErrMsg = null;
}
}
// The user changed the status filter setting, so update the selector combo.
private void cboStatus_SelectedIndexChanged(object sender, EventArgs e)
{
ApplyFilters();
}
// The user changed the outage filter setting.
private void cboInOutageFilter_SelectedIndexChanged(object sender, EventArgs e)
{
// We need to refresh the data grid in this case
if (dgvGridProcedureList.SelectedRows.Count > 0)
UpdateSelector((Guid?)dgvGridProcedureList.SelectedRows[0].Cells["ID"].Value);
else
UpdateSelector(null);
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
// ----------------------------------------------------------------------
// Private utilities
// ----------------------------------------------------------------------
// Update the tool selector combo box by filling its items based on current data and filters.
// Then set the currently displayed item to that of the supplied ID.
// If the supplied ID isn't on the list because of the current filter state, just show the
// first item if there is one.
private void UpdateSelector(Guid? id)
{
DataView dv;
// Save the sort specs if there are any, so we can re-apply them
SortOrder sortOrder = dgvGridProcedureList.SortOrder;
int sortCol = -1;
if (sortOrder != SortOrder.None)
sortCol = dgvGridProcedureList.SortedColumn.Index;
// Update the grid view selector
if (Globals.CurrentOutageID == null ||
cboInOutageFilter.SelectedIndex == (int)FilterYesNoAll.ShowAll)
dv = EGridProcedure.GetDefaultDataView(null);
else
dv = EGridProcedure.GetDefaultDataView(Globals.CurrentOutageID);
dgvGridProcedureList.DataSource = dv;
ApplyFilters();
// Re-apply the sort specs
if (sortOrder == SortOrder.Ascending)
dgvGridProcedureList.Sort(dgvGridProcedureList.Columns[sortCol], ListSortDirection.Ascending);
else if (sortOrder == SortOrder.Descending)
dgvGridProcedureList.Sort(dgvGridProcedureList.Columns[sortCol], ListSortDirection.Descending);
// Select the current row
SelectGridRow(id);
}
private void CustomizeGrid()
{
// Apply a default sort
dgvGridProcedureList.Sort(dgvGridProcedureList.Columns["GridProcedureName"], ListSortDirection.Ascending);
// Fix up the column headings
dgvGridProcedureList.Columns["GridProcedureName"].HeaderText = "Procedure Name";
dgvGridProcedureList.Columns["GridProcedureDsDiameters"].HeaderText = "D/S Dias";
dgvGridProcedureList.Columns["GridProcedureDescription"].HeaderText = "Procedure Description";
dgvGridProcedureList.Columns["GridProcedureIsActive"].HeaderText = "Active";
// Hide some columns
dgvGridProcedureList.Columns["ID"].Visible = false;
dgvGridProcedureList.Columns["GridProcedureIsActive"].Visible = false;
dgvGridProcedureList.Columns["GridProcedureIsLclChg"].Visible = false;
dgvGridProcedureList.Columns["GridProcedureUsedInOutage"].Visible = false;
dgvGridProcedureList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
}
// Apply the current filters to the DataView. The DataGridView will auto-refresh.
private void ApplyFilters()
{
if (dgvGridProcedureList.DataSource == null) return;
StringBuilder sb = new StringBuilder("GridProcedureIsActive = ", 255);
sb.Append(cboStatusFilter.SelectedIndex == (int)FilterActiveStatus.ShowActive ? "'Yes'" : "'No'");
DataView dv = (DataView)dgvGridProcedureList.DataSource;
dv.RowFilter = sb.ToString();
}
// Select the row with the specified ID if it is currently displayed and scroll to it.
// If the ID is not in the list,
private void SelectGridRow(Guid? id)
{
bool found = false;
int rows = dgvGridProcedureList.Rows.Count;
if (rows == 0) return;
int r = 0;
DataGridViewCell firstCell = dgvGridProcedureList.FirstDisplayedCell;
if (id != null)
{
// Find the row with the specified key id and select it.
for (r = 0; r < rows; r++)
{
if ((Guid?)dgvGridProcedureList.Rows[r].Cells["ID"].Value == id)
{
dgvGridProcedureList.CurrentCell = dgvGridProcedureList[firstCell.ColumnIndex, r];
dgvGridProcedureList.Rows[r].Selected = true;
found = true;
break;
}
}
}
if (found)
{
if (!dgvGridProcedureList.Rows[r].Displayed)
{
// Scroll to the selected row if the ID was in the list.
dgvGridProcedureList.FirstDisplayedScrollingRowIndex = r;
}
}
else
{
// Select the first item
dgvGridProcedureList.CurrentCell = firstCell;
dgvGridProcedureList.Rows[0].Selected = true;
}
}
}
}
| |
// 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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace WebsitePanel.EnterpriseServer
{
public class BackgroundTask
{
#region Fields
public List<BackgroundTaskParameter> Params = new List<BackgroundTaskParameter>();
public List<BackgroundTaskLogRecord> Logs = new List<BackgroundTaskLogRecord>();
#endregion
#region Properties
public int Id { get; set; }
public Guid Guid { get; set; }
public string TaskId { get; set; }
public int ScheduleId { get; set; }
public int PackageId { get; set; }
public int UserId { get; set; }
public int EffectiveUserId { get; set; }
public string TaskName { get; set; }
public int ItemId { get; set; }
public string ItemName { get; set; }
public DateTime StartDate { get; set; }
public DateTime FinishDate { get; set; }
public int IndicatorCurrent { get; set; }
public int IndicatorMaximum { get; set; }
public int MaximumExecutionTime { get; set; }
public string Source { get; set; }
public int Severity { get; set; }
public bool Completed { get; set; }
public bool NotifyOnComplete { get; set; }
public BackgroundTaskStatus Status { get; set; }
#endregion
#region Constructors
public BackgroundTask()
{
StartDate = DateTime.Now;
Severity = 0;
IndicatorCurrent = 0;
IndicatorMaximum = 0;
Status = BackgroundTaskStatus.Run;
Completed = false;
NotifyOnComplete = false;
}
public BackgroundTask(Guid guid, String taskId, int userId, int effectiveUserId, String source, String taskName, String itemName,
int itemId, int scheduleId, int packageId, int maximumExecutionTime, List<BackgroundTaskParameter> parameters)
: this()
{
Guid = guid;
TaskId = taskId;
UserId = userId;
EffectiveUserId = effectiveUserId;
Source = source;
TaskName = taskName;
ItemName = itemName;
ItemId = itemId;
ScheduleId = scheduleId;
PackageId = packageId;
MaximumExecutionTime = maximumExecutionTime;
Params = parameters;
}
#endregion
#region Methods
public List<BackgroundTaskLogRecord> GetLogs()
{
return Logs;
}
public Object GetParamValue(String name)
{
foreach(BackgroundTaskParameter param in Params)
{
if (param.Name == name)
return param.Value;
}
return null;
}
public void UpdateParamValue(String name, object value)
{
foreach (BackgroundTaskParameter param in Params)
{
if (param.Name == name)
{
param.Value = value;
return;
}
}
Params.Add(new BackgroundTaskParameter(name, value));
}
public bool ContainsParam(String name)
{
foreach (BackgroundTaskParameter param in Params)
{
if (param.Name == name)
return true;
}
return false;
}
#endregion
}
public class BackgroundTaskParameter
{
#region Properties
public int ParameterId { get; set; }
public int TaskId { get; set; }
public String Name { get; set; }
public Object Value { get; set; }
public String TypeName { get; set; }
public String SerializerValue { get; set; }
#endregion
#region Constructors
public BackgroundTaskParameter() { }
public BackgroundTaskParameter(String name, Object value)
{
Name = name;
Value = value;
}
#endregion
}
}
| |
#region License
/*
* Copyright 2002-2009 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.
*/
#endregion
using System;
using System.Diagnostics;
using Common.Logging.Factory;
using Microsoft.Practices.EnterpriseLibrary.Logging;
namespace Common.Logging.EntLib
{
/// <summary>
/// Concrete implementation of <see cref="ILog"/> interface specific to Enterprise Logging 4.1.
/// </summary>
/// <remarks>
/// Instances are created by the <see cref="EntLibLoggerFactoryAdapter"/>. <see cref="EntLibLoggerFactoryAdapter.DefaultPriority"/>
/// is used for logging a <see cref="LogEntry"/> to <see cref="Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.Write(LogEntry)"/>.
/// The category name used is the name passed into <see cref="LogManager.GetLogger(string)" />. For configuring logging, see <see cref="EntLibLoggerFactoryAdapter"/>.
/// </remarks>
/// <seealso cref="ILog"/>
/// <seealso cref="EntLibLoggerFactoryAdapter"/>
/// <author>Mark Pollack</author>
/// <author>Erich Eichinger</author>
[Serializable]
public class EntLibLogger : AbstractLogger
{
private class TraceLevelLogEntry : LogEntry
{
public TraceLevelLogEntry(string category, TraceEventType severity)
{
Categories.Add(category);
Severity = severity;
}
}
private readonly LogEntry VerboseLogEntry;
private readonly LogEntry InformationLogEntry;
private readonly LogEntry WarningLogEntry;
private readonly LogEntry ErrorLogEntry;
private readonly LogEntry CriticalLogEntry;
private readonly string category;
private readonly EntLibLoggerSettings settings;
private readonly LogWriter logWriter;
/// <summary>
/// The category of this logger
/// </summary>
public string Category
{
get { return category; }
}
/// <summary>
/// The settings used by this logger
/// </summary>
public EntLibLoggerSettings Settings
{
get { return settings; }
}
/// <summary>
/// The <see cref="LogWriter"/> used by this logger.
/// </summary>
public LogWriter LogWriter
{
get { return logWriter; }
}
/// <summary>
/// Initializes a new instance of the <see cref="EntLibLogger"/> class.
/// </summary>
/// <param name="category">The category.</param>
/// <param name="logWriter">the <see cref="LogWriter"/> to write log events to.</param>
/// <param name="settings">the logger settings</param>
public EntLibLogger(string category, LogWriter logWriter, EntLibLoggerSettings settings)
{
this.category = category;
this.logWriter = logWriter;
this.settings = settings;
VerboseLogEntry = new TraceLevelLogEntry(category, TraceEventType.Verbose);
InformationLogEntry = new TraceLevelLogEntry(category, TraceEventType.Information);
WarningLogEntry = new TraceLevelLogEntry(category, TraceEventType.Warning);
ErrorLogEntry = new TraceLevelLogEntry(category, TraceEventType.Error);
CriticalLogEntry = new TraceLevelLogEntry(category, TraceEventType.Critical);
}
#region IsXXXXEnabled
/// <summary>
/// Gets a value indicating whether this instance is trace enabled.
/// </summary>
public override bool IsTraceEnabled
{
get { return ShouldLog(VerboseLogEntry); }
}
/// <summary>
/// Gets a value indicating whether this instance is debug enabled.
/// </summary>
public override bool IsDebugEnabled
{
get { return ShouldLog(VerboseLogEntry); }
}
/// <summary>
/// Gets a value indicating whether this instance is info enabled.
/// </summary>
public override bool IsInfoEnabled
{
get { return ShouldLog(InformationLogEntry); }
}
/// <summary>
/// Gets a value indicating whether this instance is warn enabled.
/// </summary>
public override bool IsWarnEnabled
{
get { return ShouldLog(WarningLogEntry); }
}
/// <summary>
/// Gets a value indicating whether this instance is error enabled.
/// </summary>
public override bool IsErrorEnabled
{
get { return ShouldLog(ErrorLogEntry); }
}
/// <summary>
/// Gets a value indicating whether this instance is fatal enabled.
/// </summary>
public override bool IsFatalEnabled
{
get { return ShouldLog(CriticalLogEntry); }
}
#endregion
/// <summary>
/// Actually sends the message to the EnterpriseLogging log system.
/// </summary>
/// <param name="logLevel">the level of this log event.</param>
/// <param name="message">the message to log</param>
/// <param name="exception">the exception to log (may be null)</param>
protected override void WriteInternal(LogLevel logLevel, object message, Exception exception)
{
LogEntry log = CreateLogEntry(GetTraceEventType(logLevel));
if (ShouldLog(log))
{
PopulateLogEntry(log, message, exception);
WriteLog(log);
}
}
/// <summary>
/// May be overridden for custom filter logic
/// </summary>
/// <param name="log"></param>
/// <returns></returns>
protected virtual bool ShouldLog(LogEntry log)
{
return logWriter.ShouldLog(log);
}
/// <summary>
/// Write the fully populated event to the log.
/// </summary>
protected virtual void WriteLog(LogEntry log)
{
logWriter.Write(log);
}
/// <summary>
/// Translates a <see cref="LogLevel"/> to a <see cref="TraceEventType"/>.
/// </summary>
protected virtual TraceEventType GetTraceEventType(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.All:
return TraceEventType.Verbose;
case LogLevel.Trace:
return TraceEventType.Verbose;
case LogLevel.Debug:
return TraceEventType.Verbose;
case LogLevel.Info:
return TraceEventType.Information;
case LogLevel.Warn:
return TraceEventType.Warning;
case LogLevel.Error:
return TraceEventType.Error;
case LogLevel.Fatal:
return TraceEventType.Critical;
case LogLevel.Off:
return 0;
default:
throw new ArgumentOutOfRangeException("logLevel", logLevel, "unknown log level");
}
}
/// <summary>
/// Creates a minimal log entry instance that will be passed into <see cref="Logger.ShouldLog"/>
/// to asap decide, whether this event should be logged.
/// </summary>
/// <param name="traceEventType">trace event severity.</param>
/// <returns></returns>
protected virtual LogEntry CreateLogEntry(TraceEventType traceEventType)
{
LogEntry log = new LogEntry();
log.Categories.Add(category);
log.Priority = settings.priority;
log.Severity = traceEventType;
return log;
}
/// <summary>
/// Configures the log entry.
/// </summary>
/// <param name="log">The log.</param>
/// <param name="message">The message.</param>
/// <param name="ex">The ex.</param>
protected virtual void PopulateLogEntry(LogEntry log, object message, Exception ex)
{
log.Message = (message == null ? null : message.ToString());
if (ex != null)
{
AddExceptionInfo(log, ex);
}
}
/// <summary>
/// Adds the exception info.
/// </summary>
/// <param name="log">The log entry.</param>
/// <param name="exception">The exception.</param>
/// <returns></returns>
protected virtual void AddExceptionInfo(LogEntry log, Exception exception)
{
if (exception != null && settings.exceptionFormat != null)
{
string errorMessage = settings.exceptionFormat
.Replace("$(exception.message)", exception.Message)
.Replace("$(exception.source)", exception.Source)
.Replace("$(exception.targetsite)", (exception.TargetSite==null)?string.Empty:exception.TargetSite.ToString())
.Replace("$(exception.stacktrace)", exception.StackTrace)
;
// StringBuilder sb = new StringBuilder(128);
// sb.Append("Exception[ ");
// sb.Append("message = ").Append(exception.Message).Append(separator);
// sb.Append("source = ").Append(exception.Source).Append(separator);
// sb.Append("targetsite = ").Append(exception.TargetSite).Append(separator);
// sb.Append("stacktrace = ").Append(exception.StackTrace).Append("]");
// return sb.ToString();
log.AddErrorMessage(errorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Compute.Tests.DiskRPTests;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.Storage.Models;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Xunit;
namespace Compute.Tests
{
public class GalleryTests : VMTestBase
{
protected const string ResourceGroupPrefix = "galleryPsTestRg";
protected const string GalleryNamePrefix = "galleryPsTestGallery";
protected const string GalleryImageNamePrefix = "galleryPsTestGalleryImage";
protected const string GalleryApplicationNamePrefix = "galleryPsTestGalleryApplication";
private string galleryHomeLocation = "eastus2";
[Fact]
public void Gallery_CRUD_Tests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
string rgName2 = rgName + "New";
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation });
Trace.TraceInformation("Created the resource group: " + rgName);
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery galleryIn = GetTestInputGallery();
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName));
Gallery galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName);
Trace.TraceInformation("Got the gallery.");
Assert.NotNull(galleryOut);
ValidateGallery(galleryIn, galleryOut);
galleryIn.Description = "This is an updated description";
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn);
Trace.TraceInformation("Updated the gallery.");
galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName);
ValidateGallery(galleryIn, galleryOut);
Trace.TraceInformation("Listing galleries.");
string galleryName2 = galleryName + "New";
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = galleryHomeLocation });
Trace.TraceInformation("Created the resource group: " + rgName2);
ComputeManagementTestUtilities.WaitSeconds(10);
m_CrpClient.Galleries.CreateOrUpdate(rgName2, galleryName2, galleryIn);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName2, rgName2));
IPage<Gallery> listGalleriesInRgResult = m_CrpClient.Galleries.ListByResourceGroup(rgName);
Assert.Single(listGalleriesInRgResult);
Assert.Null(listGalleriesInRgResult.NextPageLink);
IPage<Gallery> listGalleriesInSubIdResult = m_CrpClient.Galleries.List();
// Below, >= instead of == is used because this subscription is shared in the group so other developers
// might have created galleries in this subscription.
Assert.True(listGalleriesInSubIdResult.Count() >= 2);
Trace.TraceInformation("Deleting 2 galleries.");
m_CrpClient.Galleries.Delete(rgName, galleryName);
m_CrpClient.Galleries.Delete(rgName2, galleryName2);
listGalleriesInRgResult = m_CrpClient.Galleries.ListByResourceGroup(rgName);
Assert.Empty(listGalleriesInRgResult);
// resource groups cleanup is taken cared by MockContext.Dispose() method.
}
}
[Fact]
public void GalleryImage_CRUD_Tests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation });
Trace.TraceInformation("Created the resource group: " + rgName);
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery gallery = GetTestInputGallery();
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName));
string galleryImageName = ComputeManagementTestUtilities.GenerateName(GalleryImageNamePrefix);
GalleryImage inputGalleryImage = GetTestInputGalleryImage();
m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage);
Trace.TraceInformation(string.Format("Created the gallery image: {0} in gallery: {1}", galleryImageName,
galleryName));
GalleryImage galleryImageFromGet = m_CrpClient.GalleryImages.Get(rgName, galleryName, galleryImageName);
Assert.NotNull(galleryImageFromGet);
ValidateGalleryImage(inputGalleryImage, galleryImageFromGet);
inputGalleryImage.Description = "Updated description.";
m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage);
Trace.TraceInformation(string.Format("Updated the gallery image: {0} in gallery: {1}", galleryImageName,
galleryName));
galleryImageFromGet = m_CrpClient.GalleryImages.Get(rgName, galleryName, galleryImageName);
Assert.NotNull(galleryImageFromGet);
ValidateGalleryImage(inputGalleryImage, galleryImageFromGet);
IPage<GalleryImage> listGalleryImagesResult = m_CrpClient.GalleryImages.ListByGallery(rgName, galleryName);
Assert.Single(listGalleryImagesResult);
Assert.Null(listGalleryImagesResult.NextPageLink);
m_CrpClient.GalleryImages.Delete(rgName, galleryName, galleryImageName);
listGalleryImagesResult = m_CrpClient.GalleryImages.ListByGallery(rgName, galleryName);
Assert.Empty(listGalleryImagesResult);
Trace.TraceInformation(string.Format("Deleted the gallery image: {0} in gallery: {1}", galleryImageName,
galleryName));
m_CrpClient.Galleries.Delete(rgName, galleryName);
}
}
[Fact]
public void GalleryImageVersion_CRUD_Tests()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
using (MockContext context = MockContext.Start(this.GetType()))
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", galleryHomeLocation);
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
VirtualMachine vm = null;
string imageName = ComputeManagementTestUtilities.GenerateName("psTestSourceImage");
try
{
string sourceImageId = "";
vm = CreateCRPImage(rgName, imageName, ref sourceImageId);
Assert.False(string.IsNullOrEmpty(sourceImageId));
Trace.TraceInformation(string.Format("Created the source image id: {0}", sourceImageId));
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery gallery = GetTestInputGallery();
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName,
rgName));
string galleryImageName = ComputeManagementTestUtilities.GenerateName(GalleryImageNamePrefix);
GalleryImage inputGalleryImage = GetTestInputGalleryImage();
m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage);
Trace.TraceInformation(string.Format("Created the gallery image: {0} in gallery: {1}", galleryImageName,
galleryName));
string galleryImageVersionName = "1.0.0";
GalleryImageVersion inputImageVersion = GetTestInputGalleryImageVersion(sourceImageId);
m_CrpClient.GalleryImageVersions.CreateOrUpdate(rgName, galleryName, galleryImageName,
galleryImageVersionName, inputImageVersion);
Trace.TraceInformation(string.Format("Created the gallery image version: {0} in gallery image: {1}",
galleryImageVersionName, galleryImageName));
GalleryImageVersion imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName,
galleryName, galleryImageName, galleryImageVersionName);
Assert.NotNull(imageVersionFromGet);
ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet);
imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName, galleryImageName,
galleryImageVersionName, ReplicationStatusTypes.ReplicationStatus);
Assert.Equal(StorageAccountType.StandardLRS, imageVersionFromGet.PublishingProfile.StorageAccountType);
Assert.Equal(StorageAccountType.StandardLRS,
imageVersionFromGet.PublishingProfile.TargetRegions.First().StorageAccountType);
Assert.NotNull(imageVersionFromGet.ReplicationStatus);
Assert.NotNull(imageVersionFromGet.ReplicationStatus.Summary);
inputImageVersion.PublishingProfile.EndOfLifeDate = DateTime.Now.AddDays(100).Date;
m_CrpClient.GalleryImageVersions.CreateOrUpdate(rgName, galleryName, galleryImageName,
galleryImageVersionName, inputImageVersion);
Trace.TraceInformation(string.Format("Updated the gallery image version: {0} in gallery image: {1}",
galleryImageVersionName, galleryImageName));
imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName,
galleryImageName, galleryImageVersionName);
Assert.NotNull(imageVersionFromGet);
ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet);
Trace.TraceInformation("Listing the gallery image versions");
IPage<GalleryImageVersion> listGalleryImageVersionsResult = m_CrpClient.GalleryImageVersions.
ListByGalleryImage(rgName, galleryName, galleryImageName);
Assert.Single(listGalleryImageVersionsResult);
Assert.Null(listGalleryImageVersionsResult.NextPageLink);
m_CrpClient.GalleryImageVersions.Delete(rgName, galleryName, galleryImageName, galleryImageVersionName);
listGalleryImageVersionsResult = m_CrpClient.GalleryImageVersions.
ListByGalleryImage(rgName, galleryName, galleryImageName);
Assert.Empty(listGalleryImageVersionsResult);
Assert.Null(listGalleryImageVersionsResult.NextPageLink);
Trace.TraceInformation(string.Format("Deleted the gallery image version: {0} in gallery image: {1}",
galleryImageVersionName, galleryImageName));
ComputeManagementTestUtilities.WaitMinutes(5);
m_CrpClient.Images.Delete(rgName, imageName);
Trace.TraceInformation("Deleted the CRP image.");
m_CrpClient.VirtualMachines.Delete(rgName, vm.Name);
Trace.TraceInformation("Deleted the virtual machine.");
m_CrpClient.GalleryImages.Delete(rgName, galleryName, galleryImageName);
Trace.TraceInformation("Deleted the gallery image.");
m_CrpClient.Galleries.Delete(rgName, galleryName);
Trace.TraceInformation("Deleted the gallery.");
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
if (vm != null)
{
m_CrpClient.VirtualMachines.Delete(rgName, vm.Name);
}
m_CrpClient.Images.Delete(rgName, imageName);
}
}
}
[Fact]
public void GalleryApplication_CRUD_Tests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string location = ComputeManagementTestUtilities.DefaultLocation;
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location });
Trace.TraceInformation("Created the resource group: " + rgName);
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
Gallery gallery = GetTestInputGallery();
gallery.Location = location;
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName));
string galleryApplicationName = ComputeManagementTestUtilities.GenerateName(GalleryApplicationNamePrefix);
GalleryApplication inputGalleryApplication = GetTestInputGalleryApplication();
m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication);
Trace.TraceInformation(string.Format("Created the gallery application: {0} in gallery: {1}", galleryApplicationName,
galleryName));
GalleryApplication galleryApplicationFromGet = m_CrpClient.GalleryApplications.Get(rgName, galleryName, galleryApplicationName);
Assert.NotNull(galleryApplicationFromGet);
ValidateGalleryApplication(inputGalleryApplication, galleryApplicationFromGet);
inputGalleryApplication.Description = "Updated description.";
m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication);
Trace.TraceInformation(string.Format("Updated the gallery application: {0} in gallery: {1}", galleryApplicationName,
galleryName));
galleryApplicationFromGet = m_CrpClient.GalleryApplications.Get(rgName, galleryName, galleryApplicationName);
Assert.NotNull(galleryApplicationFromGet);
ValidateGalleryApplication(inputGalleryApplication, galleryApplicationFromGet);
m_CrpClient.GalleryApplications.Delete(rgName, galleryName, galleryApplicationName);
Trace.TraceInformation(string.Format("Deleted the gallery application: {0} in gallery: {1}", galleryApplicationName,
galleryName));
m_CrpClient.Galleries.Delete(rgName, galleryName);
}
}
[Fact]
public void GalleryApplicationVersion_CRUD_Tests()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
using (MockContext context = MockContext.Start(this.GetType()))
{
string location = ComputeManagementTestUtilities.DefaultLocation;
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", location);
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix);
string applicationName = ComputeManagementTestUtilities.GenerateName("psTestSourceApplication");
string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix);
string galleryApplicationName = ComputeManagementTestUtilities.GenerateName(GalleryApplicationNamePrefix);
try
{
string applicationMediaLink = CreateApplicationMediaLink(rgName, "test.txt");
Assert.False(string.IsNullOrEmpty(applicationMediaLink));
Trace.TraceInformation(string.Format("Created the source application media link: {0}", applicationMediaLink));
Gallery gallery = GetTestInputGallery();
gallery.Location = location;
m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery);
Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName,
rgName));
GalleryApplication inputGalleryApplication = GetTestInputGalleryApplication();
m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication);
Trace.TraceInformation(string.Format("Created the gallery application: {0} in gallery: {1}", galleryApplicationName,
galleryName));
string galleryApplicationVersionName = "1.0.0";
GalleryApplicationVersion inputApplicationVersion = GetTestInputGalleryApplicationVersion(applicationMediaLink);
m_CrpClient.GalleryApplicationVersions.CreateOrUpdate(rgName, galleryName, galleryApplicationName,
galleryApplicationVersionName, inputApplicationVersion);
Trace.TraceInformation(string.Format("Created the gallery application version: {0} in gallery application: {1}",
galleryApplicationVersionName, galleryApplicationName));
GalleryApplicationVersion applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName,
galleryName, galleryApplicationName, galleryApplicationVersionName);
Assert.NotNull(applicationVersionFromGet);
ValidateGalleryApplicationVersion(inputApplicationVersion, applicationVersionFromGet);
applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName, galleryName, galleryApplicationName,
galleryApplicationVersionName, ReplicationStatusTypes.ReplicationStatus);
Assert.Equal(StorageAccountType.StandardLRS, applicationVersionFromGet.PublishingProfile.StorageAccountType);
Assert.Equal(StorageAccountType.StandardLRS,
applicationVersionFromGet.PublishingProfile.TargetRegions.First().StorageAccountType);
Assert.NotNull(applicationVersionFromGet.ReplicationStatus);
Assert.NotNull(applicationVersionFromGet.ReplicationStatus.Summary);
inputApplicationVersion.PublishingProfile.EndOfLifeDate = DateTime.Now.AddDays(100).Date;
m_CrpClient.GalleryApplicationVersions.CreateOrUpdate(rgName, galleryName, galleryApplicationName,
galleryApplicationVersionName, inputApplicationVersion);
Trace.TraceInformation(string.Format("Updated the gallery application version: {0} in gallery application: {1}",
galleryApplicationVersionName, galleryApplicationName));
applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName, galleryName,
galleryApplicationName, galleryApplicationVersionName);
Assert.NotNull(applicationVersionFromGet);
ValidateGalleryApplicationVersion(inputApplicationVersion, applicationVersionFromGet);
m_CrpClient.GalleryApplicationVersions.Delete(rgName, galleryName, galleryApplicationName, galleryApplicationVersionName);
Trace.TraceInformation(string.Format("Deleted the gallery application version: {0} in gallery application: {1}",
galleryApplicationVersionName, galleryApplicationName));
m_CrpClient.GalleryApplications.Delete(rgName, galleryName, galleryApplicationName);
Trace.TraceInformation("Deleted the gallery application.");
m_CrpClient.Galleries.Delete(rgName, galleryName);
Trace.TraceInformation("Deleted the gallery.");
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
}
}
}
private void ValidateGallery(Gallery galleryIn, Gallery galleryOut)
{
Assert.False(string.IsNullOrEmpty(galleryOut.ProvisioningState));
if (galleryIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in galleryIn.Tags)
{
Assert.Equal(kvp.Value, galleryOut.Tags[kvp.Key]);
}
}
if (!string.IsNullOrEmpty(galleryIn.Description))
{
Assert.Equal(galleryIn.Description, galleryOut.Description);
}
Assert.False(string.IsNullOrEmpty(galleryOut?.Identifier?.UniqueName));
}
private void ValidateGalleryImage(GalleryImage imageIn, GalleryImage imageOut)
{
Assert.False(string.IsNullOrEmpty(imageOut.ProvisioningState));
if (imageIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in imageIn.Tags)
{
Assert.Equal(kvp.Value, imageOut.Tags[kvp.Key]);
}
}
Assert.Equal(imageIn.Identifier.Publisher, imageOut.Identifier.Publisher);
Assert.Equal(imageIn.Identifier.Offer, imageOut.Identifier.Offer);
Assert.Equal(imageIn.Identifier.Sku, imageOut.Identifier.Sku);
Assert.Equal(imageIn.Location, imageOut.Location);
Assert.Equal(imageIn.OsState, imageOut.OsState);
Assert.Equal(imageIn.OsType, imageOut.OsType);
if (imageIn.HyperVGeneration == null)
{
Assert.Equal(HyperVGenerationType.V1, imageOut.HyperVGeneration);
}
else
{
Assert.Equal(imageIn.HyperVGeneration, imageOut.HyperVGeneration);
}
if (!string.IsNullOrEmpty(imageIn.Description))
{
Assert.Equal(imageIn.Description, imageOut.Description);
}
}
private void ValidateGalleryImageVersion(GalleryImageVersion imageVersionIn,
GalleryImageVersion imageVersionOut)
{
Assert.False(string.IsNullOrEmpty(imageVersionOut.ProvisioningState));
if (imageVersionIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in imageVersionIn.Tags)
{
Assert.Equal(kvp.Value, imageVersionOut.Tags[kvp.Key]);
}
}
Assert.Equal(imageVersionIn.Location, imageVersionOut.Location);
Assert.False(string.IsNullOrEmpty(imageVersionOut.StorageProfile.Source.Id),
"imageVersionOut.PublishingProfile.Source.ManagedImage.Id is null or empty.");
Assert.NotNull(imageVersionOut.PublishingProfile.EndOfLifeDate);
Assert.NotNull(imageVersionOut.PublishingProfile.PublishedDate);
Assert.NotNull(imageVersionOut.StorageProfile);
}
private Gallery GetTestInputGallery()
{
return new Gallery
{
Location = galleryHomeLocation,
Description = "This is a sample gallery description"
};
}
private GalleryImage GetTestInputGalleryImage()
{
return new GalleryImage
{
Identifier = new GalleryImageIdentifier
{
Publisher = "testPub",
Offer = "testOffer",
Sku = "testSku"
},
Location = galleryHomeLocation,
OsState = OperatingSystemStateTypes.Generalized,
OsType = OperatingSystemTypes.Windows,
Description = "This is the gallery image description.",
HyperVGeneration = null
};
}
private GalleryImageVersion GetTestInputGalleryImageVersion(string sourceImageId)
{
return new GalleryImageVersion
{
Location = galleryHomeLocation,
PublishingProfile = new GalleryImageVersionPublishingProfile
{
ReplicaCount = 1,
StorageAccountType = StorageAccountType.StandardLRS,
TargetRegions = new List<TargetRegion> {
new TargetRegion {
Name = galleryHomeLocation,
RegionalReplicaCount = 1,
StorageAccountType = StorageAccountType.StandardLRS
}
},
EndOfLifeDate = DateTime.Today.AddDays(10).Date
},
StorageProfile = new GalleryImageVersionStorageProfile
{
Source = new GalleryArtifactVersionSource
{
Id = sourceImageId
}
}
};
}
private VirtualMachine CreateCRPImage(string rgName, string imageName, ref string sourceImageId)
{
string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforgallery");
string asName = ComputeManagementTestUtilities.GenerateName("asforgallery");
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method.
VirtualMachine inputVM = null;
VirtualMachine createdVM = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM);
Image imageInput = new Image()
{
Location = m_location,
Tags = new Dictionary<string, string>()
{
{"RG", "rg"},
{"testTag", "1"},
},
StorageProfile = new ImageStorageProfile()
{
OsDisk = new ImageOSDisk()
{
BlobUri = createdVM.StorageProfile.OsDisk.Vhd.Uri,
OsState = OperatingSystemStateTypes.Generalized,
OsType = OperatingSystemTypes.Windows,
},
ZoneResilient = true
},
HyperVGeneration = HyperVGenerationTypes.V1
};
m_CrpClient.Images.CreateOrUpdate(rgName, imageName, imageInput);
Image getImage = m_CrpClient.Images.Get(rgName, imageName);
sourceImageId = getImage.Id;
return createdVM;
}
private string CreateApplicationMediaLink(string rgName, string fileName)
{
string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforgallery");
string asName = ComputeManagementTestUtilities.GenerateName("asforgallery");
StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method.
string applicationMediaLink = @"https://saforgallery1969.blob.core.windows.net/sascontainer/test.txt\";
if (HttpMockServer.Mode == HttpRecorderMode.Record)
{
var accountKeyResult = m_SrpClient.StorageAccounts.ListKeysWithHttpMessagesAsync(rgName, storageAccountName).Result;
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, accountKeyResult.Body.Key1), useHttps: true);
var blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("sascontainer");
bool created = container.CreateIfNotExistsAsync().Result;
CloudPageBlob pageBlob = container.GetPageBlobReference(fileName);
byte[] blobContent = Encoding.UTF8.GetBytes("Application Package Test");
byte[] bytes = new byte[512]; // Page blob must be multiple of 512
System.Buffer.BlockCopy(blobContent, 0, bytes, 0, blobContent.Length);
pageBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length);
SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddDays(-1);
sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(2);
sasConstraints.Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write;
//Generate the shared access signature on the blob, setting the constraints directly on the signature.
string sasContainerToken = pageBlob.GetSharedAccessSignature(sasConstraints);
//Return the URI string for the container, including the SAS token.
applicationMediaLink = pageBlob.Uri + sasContainerToken;
}
return applicationMediaLink;
}
private GalleryApplication GetTestInputGalleryApplication()
{
return new GalleryApplication
{
Eula = "This is the gallery application EULA.",
Location = ComputeManagementTestUtilities.DefaultLocation,
SupportedOSType = OperatingSystemTypes.Windows,
PrivacyStatementUri = "www.privacystatement.com",
ReleaseNoteUri = "www.releasenote.com",
Description = "This is the gallery application description.",
};
}
private GalleryApplicationVersion GetTestInputGalleryApplicationVersion(string applicationMediaLink)
{
return new GalleryApplicationVersion
{
Location = ComputeManagementTestUtilities.DefaultLocation,
PublishingProfile = new GalleryApplicationVersionPublishingProfile
{
Source = new UserArtifactSource
{
MediaLink = applicationMediaLink
},
ManageActions = new UserArtifactManage
{
Install = "powershell -command \"Expand-Archive -Path test.zip -DestinationPath C:\\package\"",
Remove = "del C:\\package "
},
ReplicaCount = 1,
StorageAccountType = StorageAccountType.StandardLRS,
TargetRegions = new List<TargetRegion> {
new TargetRegion { Name = ComputeManagementTestUtilities.DefaultLocation, RegionalReplicaCount = 1, StorageAccountType = StorageAccountType.StandardLRS }
},
EndOfLifeDate = DateTime.Today.AddDays(10).Date
}
};
}
private void ValidateGalleryApplication(GalleryApplication applicationIn, GalleryApplication applicationOut)
{
if (applicationIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in applicationIn.Tags)
{
Assert.Equal(kvp.Value, applicationOut.Tags[kvp.Key]);
}
}
Assert.Equal(applicationIn.Eula, applicationOut.Eula);
Assert.Equal(applicationIn.PrivacyStatementUri, applicationOut.PrivacyStatementUri);
Assert.Equal(applicationIn.ReleaseNoteUri, applicationOut.ReleaseNoteUri);
Assert.Equal(applicationIn.Location.ToLower(), applicationOut.Location.ToLower());
Assert.Equal(applicationIn.SupportedOSType, applicationOut.SupportedOSType);
if (!string.IsNullOrEmpty(applicationIn.Description))
{
Assert.Equal(applicationIn.Description, applicationOut.Description);
}
}
private void ValidateGalleryApplicationVersion(GalleryApplicationVersion applicationVersionIn, GalleryApplicationVersion applicationVersionOut)
{
Assert.False(string.IsNullOrEmpty(applicationVersionOut.ProvisioningState));
if (applicationVersionIn.Tags != null)
{
foreach (KeyValuePair<string, string> kvp in applicationVersionIn.Tags)
{
Assert.Equal(kvp.Value, applicationVersionOut.Tags[kvp.Key]);
}
}
Assert.Equal(applicationVersionIn.Location.ToLower(), applicationVersionOut.Location.ToLower());
Assert.False(string.IsNullOrEmpty(applicationVersionOut.PublishingProfile.Source.MediaLink),
"applicationVersionOut.PublishingProfile.Source.MediaLink is null or empty.");
Assert.NotNull(applicationVersionOut.PublishingProfile.EndOfLifeDate);
Assert.NotNull(applicationVersionOut.PublishingProfile.PublishedDate);
Assert.NotNull(applicationVersionOut.Id);
}
}
}
| |
// 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.Runtime.InteropServices;
using Xunit;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedFile.CreateFromFile.
/// </summary>
public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase
{
/// <summary>
/// Tests invalid arguments to the CreateFromFile path parameter.
/// </summary>
[Fact]
public void InvalidArguments_Path()
{
// null is an invalid path
Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null));
Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open));
Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName()));
Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096));
Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile fileStream parameter.
/// </summary>
[Fact]
public void InvalidArguments_FileStream()
{
// null is an invalid stream
Assert.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mode parameter.
/// </summary>
[Fact]
public void InvalidArguments_Mode()
{
// FileMode out of range
Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42));
Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null));
Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096));
Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.Append never allowed
Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append));
Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null));
Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096));
Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate));
// FileMode.Truncate can't be used with default capacity, as resulting file will be empty
using (TempFile file = new TempFile(GetTestFilePath()))
{
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate));
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile access parameter.
/// </summary>
[Fact]
public void InvalidArguments_Access()
{
// Out of range access values with a path
Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2)));
Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42)));
// Write-only access is not allowed on maps (only on views)
Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write));
// Test the same things, but with a FileStream instead of a path
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Out of range values with a stream
Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true));
Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true));
// Write-only access is not allowed
Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream. The combinations should all be valid.
/// </summary>
[Theory]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, Capacity, mmfAccess);
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Unix we don't actually create the OS map until the view is created; this results in the permissions
// error being thrown from CreateView* instead of from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor());
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mapName parameter.
/// </summary>
[Fact]
public void InvalidArguments_MapName()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Empty string is an invalid map name
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Test to verify that map names are left unsupported on Unix.
/// </summary>
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void MapNamesNotSupported_Unix(string mapName)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile capacity parameter.
/// </summary>
[Fact]
public void InvalidArguments_Capacity()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read));
// Positive capacity required when creating a map from an empty file
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read));
// With Read, the capacity can't be larger than the backing file's size.
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
// Now with a FileStream...
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// The subsequent tests are only valid we if we start with an empty FileStream, which we should have.
// This also verifies the previous failed tests didn't change the length of the file.
Assert.Equal(0, fs.Length);
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Default (0) capacity with an empty file
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Larger capacity than the underlying file, but read-only such that we can't expand the file
fs.SetLength(4096);
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Capacity can't be less than the file size (for such cases a view can be created with the smaller size)
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
// Capacity can't be less than the file size
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile inheritability parameter.
/// </summary>
[Theory]
[InlineData((HandleInheritability)(-1))]
[InlineData((HandleInheritability)(42))]
public void InvalidArguments_Inheritability(HandleInheritability inheritability)
{
// Out of range values for inheritability
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true));
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.Open, FileMode.OpenOrCreate },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// Test each of the four path-based CreateFromFile overloads
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
// Finally, re-test the last overload, this time with an empty file to start
using (TempFile file = new TempFile(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.CreateNew },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModeCreateNew(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads
// that take a capacity, since the default capacity doesn't work with an empty file.
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access))
{
ValidateMemoryMappedFile(mmf, capacity, access);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Create and Truncate modes,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.Create, FileMode.Truncate },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
public void ValidArgumentCombinationsWithPath_ModesCreateOrTruncate(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// For FileMode.Create/Truncate, try existing files. Only the overloads that take a capacity are valid because
// both of these modes will cause the input file to be made empty, and an empty file doesn't work with the default capacity.
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity, access))
{
ValidateMemoryMappedFile(mmf, capacity, access);
}
// For FileMode.Create, also try letting it create a new file (Truncate needs the file to have existed)
if (mode == FileMode.Create)
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="modes">The modes to yield.</param>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath(
FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses)
{
foreach (FileMode mode in modes)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity;
foreach (MemoryMappedFileAccess access in accesses)
{
if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) &&
!IsWritable(access))
{
continue;
}
yield return new object[] { mode, mapName, capacity, access };
}
}
}
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile that accepts a FileStream.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite },
new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable },
new bool[] { false, true })]
public void ValidArgumentCombinationsWithStream(
string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen)
{
// Create a file of the right size, then create the map for it.
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
// Start with an empty file and let the map grow it to the right size. This requires write access.
if (IsWritable(access))
{
using (FileStream fs = File.Create(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
/// <param name="inheritabilities">The inheritabilities to yield.</param>
/// <param name="inheritabilities">The leaveOpen values to yield.</param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream(
string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
string mapName = tmpMapName == "CreateUniqueMapName()" ?
CreateUniqueMapName() :
tmpMapName;
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ?
s_pageSize.Value :
tmpCapacity;
foreach (MemoryMappedFileAccess access in accesses)
{
foreach (HandleInheritability inheritability in inheritabilities)
{
foreach (bool leaveOpen in leaveOpens)
{
yield return new object[] { mapName, capacity, access, inheritability, leaveOpen };
}
}
}
}
}
}
/// <summary>
/// Test that a map using the default capacity (0) grows to the size of the underlying file.
/// </summary>
[Fact]
public void DefaultCapacityIsFileLength()
{
const int DesiredCapacity = 8192;
const int DefaultCapacity = 0;
// With path
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
// With stream
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode
/// that requires the file to exist.
/// </summary>
[Theory]
[InlineData(FileMode.Truncate)]
[InlineData(FileMode.Open)]
public void FileDoesNotExist(FileMode mode)
{
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath()));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null, 4096));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with an existing file and a mode
/// that requires the file to not exist.
/// </summary>
[Fact]
public void FileAlreadyExists()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// FileMode.CreateNew invalid when the file already exists
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName()));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a read-write file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(PlatformID.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(PlatformID.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap()
{
// Already opened with another read-write map
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test to validate we can create multiple concurrent read-only maps from the same file path.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_SucceedsWithReadOnly()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
{
Assert.Equal(acc1.Capacity, acc2.Capacity);
}
}
/// <summary>
/// Test the exceptional behavior of *Execute access levels.
/// </summary>
[PlatformSpecific(PlatformID.Windows)] // Unix model for executable differs from Windows
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute)]
public void FileNotOpenedForExecute(MemoryMappedFileAccess access)
{
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
{
// The FileStream created by the map doesn't have GENERIC_EXECUTE set
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access));
// The FileStream opened explicitly doesn't have GENERIC_EXECUTE set
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true));
}
}
}
/// <summary>
/// On Unix, modifying a file that is ReadOnly will fail under normal permissions.
/// If the test is being run under the superuser, however, modification of a ReadOnly
/// file is allowed.
/// </summary>
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[InlineData(MemoryMappedFileAccess.CopyOnWrite)]
public void WriteToReadOnlyFile(MemoryMappedFileAccess access)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
FileAttributes original = File.GetAttributes(file.Path);
File.SetAttributes(file.Path, FileAttributes.ReadOnly);
try
{
if (access == MemoryMappedFileAccess.Read || (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access))
ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read);
else
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access));
}
finally
{
File.SetAttributes(file.Path, original);
}
}
}
[DllImport("libc", SetLastError = true)]
private static extern int geteuid();
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_Basic(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create and close the map
MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose();
// The handle should now be open iff leaveOpen
Assert.NotEqual(leaveOpen, handle.IsClosed);
}
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_OutstandingViews(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create the map, create each of the views, then close the map
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity))
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity))
{
// Explicitly close the map. The handle should now be open iff leaveOpen.
mmf.Dispose();
Assert.NotEqual(leaveOpen, handle.IsClosed);
// But the views should still be usable.
ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite);
ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite);
}
}
}
/// <summary>
/// Test to validate we can create multiple maps from the same FileStream.
/// </summary>
[Fact]
public void MultipleMapsForTheSameFileStream()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor())
{
// The capacity of the two maps should be equal
Assert.Equal(acc1.Capacity, acc2.Capacity);
var rand = new Random();
for (int i = 1; i <= 10; i++)
{
// Write a value to one map, then read it from the other,
// ping-ponging between the two.
int pos = rand.Next((int)acc1.Capacity - 1);
MemoryMappedViewAccessor reader = acc1, writer = acc2;
if (i % 2 == 0)
{
reader = acc2;
writer = acc1;
}
writer.Write(pos, (byte)i);
writer.Flush();
Assert.Equal(i, reader.ReadByte(pos));
}
}
}
/// <summary>
/// Test to verify that the map's size increases the underlying file size if the map's capacity is larger.
/// </summary>
[Fact]
public void FileSizeExpandsToCapacity()
{
const int InitialCapacity = 256;
using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity))
{
// Create a map with a larger capacity, and verify the file has expanded.
MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose();
using (FileStream fs = File.OpenRead(file.Path))
{
Assert.Equal(InitialCapacity * 2, fs.Length);
}
// Do the same thing again but with a FileStream.
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(InitialCapacity * 4, fs.Length);
}
}
}
/// <summary>
/// Test the exceptional behavior when attempting to create a map so large it's not supported.
/// </summary>
[PlatformSpecific(~PlatformID.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately)
[Fact]
public void TooLargeCapacity()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew))
{
try
{
long length = long.MaxValue;
MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested.
}
catch (IOException)
{
// Expected exception for too large a capacity
}
}
}
/// <summary>
/// Test to verify map names are handled appropriately, causing a conflict when they're active but
/// reusable in a sequential manner.
/// </summary>
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void ReusingNames_Windows(string name)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity));
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
}
}
}
}
| |
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using System;
using System.Diagnostics;
using System.Threading;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BinaryDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.BinaryDocValuesUpdate;
using NumericDocValuesUpdate = Lucene.Net.Index.DocValuesUpdate.NumericDocValuesUpdate;
using Query = Lucene.Net.Search.Query;
/// <summary>
/// <see cref="DocumentsWriterDeleteQueue"/> is a non-blocking linked pending deletes
/// queue. In contrast to other queue implementation we only maintain the
/// tail of the queue. A delete queue is always used in a context of a set of
/// DWPTs and a global delete pool. Each of the DWPT and the global pool need to
/// maintain their 'own' head of the queue (as a <see cref="DeleteSlice"/> instance per DWPT).
/// The difference between the DWPT and the global pool is that the DWPT starts
/// maintaining a head once it has added its first document since for its segments
/// private deletes only the deletes after that document are relevant. The global
/// pool instead starts maintaining the head once this instance is created by
/// taking the sentinel instance as its initial head.
/// <para/>
/// Since each <see cref="DeleteSlice"/> maintains its own head and the list is only
/// single linked the garbage collector takes care of pruning the list for us.
/// All nodes in the list that are still relevant should be either directly or
/// indirectly referenced by one of the DWPT's private <see cref="DeleteSlice"/> or by
/// the global <see cref="BufferedUpdates"/> slice.
/// <para/>
/// Each DWPT as well as the global delete pool maintain their private
/// DeleteSlice instance. In the DWPT case updating a slice is equivalent to
/// atomically finishing the document. The slice update guarantees a "happens
/// before" relationship to all other updates in the same indexing session. When a
/// DWPT updates a document it:
///
/// <list type="number">
/// <item><description>consumes a document and finishes its processing</description></item>
/// <item><description>updates its private <see cref="DeleteSlice"/> either by calling
/// <see cref="UpdateSlice(DeleteSlice)"/> or <see cref="Add(Term, DeleteSlice)"/> (if the
/// document has a delTerm)</description></item>
/// <item><description>applies all deletes in the slice to its private <see cref="BufferedUpdates"/>
/// and resets it</description></item>
/// <item><description>increments its internal document id</description></item>
/// </list>
///
/// The DWPT also doesn't apply its current documents delete term until it has
/// updated its delete slice which ensures the consistency of the update. If the
/// update fails before the <see cref="DeleteSlice"/> could have been updated the deleteTerm
/// will also not be added to its private deletes neither to the global deletes.
///
/// </summary>
internal sealed class DocumentsWriterDeleteQueue
{
private Node tail; // LUCENENET NOTE: can't use type without specifying type parameter, also not volatile due to Interlocked
// LUCENENET NOTE: no need for AtomicReferenceFieldUpdater, we can use Interlocked instead
private readonly DeleteSlice globalSlice;
private readonly BufferedUpdates globalBufferedUpdates;
/* only acquired to update the global deletes */
private readonly ReentrantLock globalBufferLock = new ReentrantLock();
internal readonly long generation;
internal DocumentsWriterDeleteQueue()
: this(0)
{
}
internal DocumentsWriterDeleteQueue(long generation)
: this(new BufferedUpdates(), generation)
{
}
internal DocumentsWriterDeleteQueue(BufferedUpdates globalBufferedUpdates, long generation)
{
this.globalBufferedUpdates = globalBufferedUpdates;
this.generation = generation;
/*
* we use a sentinel instance as our initial tail. No slice will ever try to
* apply this tail since the head is always omitted.
*/
tail = new Node(null); // sentinel
globalSlice = new DeleteSlice(tail);
}
internal void AddDelete(params Query[] queries)
{
Add(new QueryArrayNode(queries));
TryApplyGlobalSlice();
}
internal void AddDelete(params Term[] terms)
{
Add(new TermArrayNode(terms));
TryApplyGlobalSlice();
}
internal void AddNumericUpdate(NumericDocValuesUpdate update)
{
Add(new NumericUpdateNode(update));
TryApplyGlobalSlice();
}
internal void AddBinaryUpdate(BinaryDocValuesUpdate update)
{
Add(new BinaryUpdateNode(update));
TryApplyGlobalSlice();
}
/// <summary>
/// invariant for document update
/// </summary>
internal void Add(Term term, DeleteSlice slice)
{
TermNode termNode = new TermNode(term);
Add(termNode);
/*
* this is an update request where the term is the updated documents
* delTerm. in that case we need to guarantee that this insert is atomic
* with regards to the given delete slice. this means if two threads try to
* update the same document with in turn the same delTerm one of them must
* win. By taking the node we have created for our del term as the new tail
* it is guaranteed that if another thread adds the same right after us we
* will apply this delete next time we update our slice and one of the two
* competing updates wins!
*/
slice.sliceTail = termNode;
Debug.Assert(slice.sliceHead != slice.sliceTail, "slice head and tail must differ after add");
TryApplyGlobalSlice(); // TODO doing this each time is not necessary maybe
// we can do it just every n times or so?
}
internal void Add(Node item)
{
/*
* this non-blocking / 'wait-free' linked list add was inspired by Apache
* Harmony's ConcurrentLinkedQueue Implementation.
*/
while (true)
{
Node currentTail = this.tail;
Node tailNext = currentTail.next;
if (tail == currentTail)
{
if (tailNext != null)
{
/*
* we are in intermediate state here. the tails next pointer has been
* advanced but the tail itself might not be updated yet. help to
* advance the tail and try again updating it.
*/
Interlocked.CompareExchange(ref tail, tailNext, currentTail); // can fail
}
else
{
/*
* we are in quiescent state and can try to insert the item to the
* current tail if we fail to insert we just retry the operation since
* somebody else has already added its item
*/
if (currentTail.CasNext(null, item))
{
/*
* now that we are done we need to advance the tail while another
* thread could have advanced it already so we can ignore the return
* type of this CAS call
*/
Interlocked.CompareExchange(ref tail, item, currentTail);
return;
}
}
}
}
}
internal bool AnyChanges()
{
globalBufferLock.@Lock();
try
{
/*
* check if all items in the global slice were applied
* and if the global slice is up-to-date
* and if globalBufferedUpdates has changes
*/
return globalBufferedUpdates.Any() || !globalSlice.IsEmpty || globalSlice.sliceTail != tail || tail.next != null;
}
finally
{
globalBufferLock.Unlock();
}
}
internal void TryApplyGlobalSlice()
{
if (globalBufferLock.TryLock())
{
/*
* The global buffer must be locked but we don't need to update them if
* there is an update going on right now. It is sufficient to apply the
* deletes that have been added after the current in-flight global slices
* tail the next time we can get the lock!
*/
try
{
if (UpdateSlice(globalSlice))
{
// System.out.println(Thread.currentThread() + ": apply globalSlice");
globalSlice.Apply(globalBufferedUpdates, BufferedUpdates.MAX_INT32);
}
}
finally
{
globalBufferLock.Unlock();
}
}
}
internal FrozenBufferedUpdates FreezeGlobalBuffer(DeleteSlice callerSlice)
{
globalBufferLock.@Lock();
/*
* Here we freeze the global buffer so we need to lock it, apply all
* deletes in the queue and reset the global slice to let the GC prune the
* queue.
*/
Node currentTail = tail; // take the current tail make this local any
// Changes after this call are applied later
// and not relevant here
if (callerSlice != null)
{
// Update the callers slices so we are on the same page
callerSlice.sliceTail = currentTail;
}
try
{
if (globalSlice.sliceTail != currentTail)
{
globalSlice.sliceTail = currentTail;
globalSlice.Apply(globalBufferedUpdates, BufferedUpdates.MAX_INT32);
}
FrozenBufferedUpdates packet = new FrozenBufferedUpdates(globalBufferedUpdates, false);
globalBufferedUpdates.Clear();
return packet;
}
finally
{
globalBufferLock.Unlock();
}
}
internal DeleteSlice NewSlice()
{
return new DeleteSlice(tail);
}
internal bool UpdateSlice(DeleteSlice slice)
{
if (slice.sliceTail != tail) // If we are the same just
{
slice.sliceTail = tail;
return true;
}
return false;
}
internal class DeleteSlice
{
// No need to be volatile, slices are thread captive (only accessed by one thread)!
internal Node sliceHead; // we don't apply this one
internal Node sliceTail;
internal DeleteSlice(Node currentTail)
{
Debug.Assert(currentTail != null);
Debug.Assert(currentTail.next == null);
/*
* Initially this is a 0 length slice pointing to the 'current' tail of
* the queue. Once we update the slice we only need to assign the tail and
* have a new slice
*/
sliceHead = sliceTail = currentTail;
}
internal virtual void Apply(BufferedUpdates del, int docIDUpto)
{
if (sliceHead == sliceTail)
{
// 0 length slice
return;
}
/*
* When we apply a slice we take the head and get its next as our first
* item to apply and continue until we applied the tail. If the head and
* tail in this slice are not equal then there will be at least one more
* non-null node in the slice!
*/
Node current = sliceHead;
do
{
current = current.next;
Debug.Assert(current != null, "slice property violated between the head on the tail must not be a null node");
current.Apply(del, docIDUpto);
// System.out.println(Thread.currentThread().getName() + ": pull " + current + " docIDUpto=" + docIDUpto);
} while (current != sliceTail);
Reset();
}
internal virtual void Reset()
{
// Reset to a 0 length slice
sliceHead = sliceTail;
}
/// <summary>
/// Returns <code>true</code> iff the given item is identical to the item
/// hold by the slices tail, otherwise <code>false</code>.
/// </summary>
internal virtual bool IsTailItem(object item)
{
return sliceTail.item == item;
}
internal virtual bool IsEmpty
{
get
{
return sliceHead == sliceTail;
}
}
}
public int NumGlobalTermDeletes
{
get { return globalBufferedUpdates.numTermDeletes.Get(); }
}
internal void Clear()
{
globalBufferLock.@Lock();
try
{
Node currentTail = tail;
globalSlice.sliceHead = globalSlice.sliceTail = currentTail;
globalBufferedUpdates.Clear();
}
finally
{
globalBufferLock.Unlock();
}
}
internal class Node // LUCENENET specific - made internal instead of private because it is used in internal APIs
{
internal /*volatile*/ Node next;
internal readonly object item;
internal Node(object item)
{
this.item = item;
}
//internal static readonly AtomicReferenceFieldUpdater<Node, Node> NextUpdater = AtomicReferenceFieldUpdater.newUpdater(typeof(Node), typeof(Node), "next");
internal virtual void Apply(BufferedUpdates bufferedDeletes, int docIDUpto)
{
throw new InvalidOperationException("sentinel item must never be applied");
}
internal virtual bool CasNext(Node cmp, Node val)
{
// LUCENENET NOTE: Interlocked.CompareExchange(location, value, comparand) is backwards from
// AtomicReferenceFieldUpdater.compareAndSet(obj, expect, update), so swapping val and cmp.
// Return true if the result of the CompareExchange is the same as the comparison.
return ReferenceEquals(Interlocked.CompareExchange(ref next, val, cmp), cmp);
}
}
private sealed class TermNode : Node
{
internal TermNode(Term term)
: base(term)
{
}
internal override void Apply(BufferedUpdates bufferedDeletes, int docIDUpto)
{
bufferedDeletes.AddTerm((Term)item, docIDUpto);
}
public override string ToString()
{
return "del=" + item;
}
}
private sealed class QueryArrayNode : Node
{
internal QueryArrayNode(Query[] query)
: base(query)
{
}
internal override void Apply(BufferedUpdates bufferedUpdates, int docIDUpto)
{
foreach (Query query in (Query[])item)
{
bufferedUpdates.AddQuery(query, docIDUpto);
}
}
}
private sealed class TermArrayNode : Node
{
internal TermArrayNode(Term[] term)
: base(term)
{
}
internal override void Apply(BufferedUpdates bufferedUpdates, int docIDUpto)
{
foreach (Term term in (Term[])item)
{
bufferedUpdates.AddTerm(term, docIDUpto);
}
}
public override string ToString()
{
return "dels=" + Arrays.ToString((Term[])item);
}
}
private sealed class NumericUpdateNode : Node
{
internal NumericUpdateNode(NumericDocValuesUpdate update)
: base(update)
{
}
internal override void Apply(BufferedUpdates bufferedUpdates, int docIDUpto)
{
bufferedUpdates.AddNumericUpdate((NumericDocValuesUpdate)item, docIDUpto);
}
public override string ToString()
{
return "update=" + item;
}
}
private sealed class BinaryUpdateNode : Node
{
internal BinaryUpdateNode(BinaryDocValuesUpdate update)
: base(update)
{
}
internal override void Apply(BufferedUpdates bufferedUpdates, int docIDUpto)
{
bufferedUpdates.AddBinaryUpdate((BinaryDocValuesUpdate)item, docIDUpto);
}
public override string ToString()
{
return "update=" + (BinaryDocValuesUpdate)item;
}
}
private bool ForceApplyGlobalSlice()
{
globalBufferLock.@Lock();
Node currentTail = tail;
try
{
if (globalSlice.sliceTail != currentTail)
{
globalSlice.sliceTail = currentTail;
globalSlice.Apply(globalBufferedUpdates, BufferedUpdates.MAX_INT32);
}
return globalBufferedUpdates.Any();
}
finally
{
globalBufferLock.Unlock();
}
}
public int BufferedUpdatesTermsSize
{
get
{
globalBufferLock.@Lock();
try
{
ForceApplyGlobalSlice();
return globalBufferedUpdates.terms.Count;
}
finally
{
globalBufferLock.Unlock();
}
}
}
public long BytesUsed
{
get { return globalBufferedUpdates.bytesUsed.Get(); }
}
public override string ToString()
{
return "DWDQ: [ generation: " + generation + " ]";
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
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 License
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace JsonFx.Serialization
{
/// <summary>
/// Provides base implementation for standard deserializers
/// </summary>
public abstract class DataReader<T> : IDataReader
{
#region Fields
private readonly DataReaderSettings settings;
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="settings"></param>
protected DataReader(DataReaderSettings settings)
{
if (settings == null)
{
throw new NullReferenceException("settings");
}
this.settings = settings;
}
#endregion Init
#region Properties
/// <summary>
/// Gets the supported content type of the serialized data
/// </summary>
public abstract IEnumerable<string> ContentType
{
get;
}
/// <summary>
/// Gets the settings used for deserialization
/// </summary>
public DataReaderSettings Settings
{
get { return this.settings; }
}
#endregion Properties
#region Read Methods
/// <summary>
/// Deserializes the data from the given input
/// </summary>
/// <param name="input">the input reader</param>
/// <param name="ignored">a value used to trigger Type inference for <typeparamref name="TResult"/> (e.g. for deserializing anonymous objects)</param>
/// <typeparam name="TResult">the expected type of the serialized data</typeparam>
public virtual TResult Read<TResult>(TextReader input, TResult ignored)
{
return this.Read<TResult>(input);
}
/// <summary>
/// Deserializes the data from the given input
/// </summary>
/// <param name="input">the input reader</param>
/// <typeparam name="TResult">the expected type of the serialized data</typeparam>
public virtual TResult Read<TResult>(TextReader input)
{
object value = this.Read(input, typeof(TResult));
return (value is TResult) ? (TResult)value : default(TResult);
}
/// <summary>
/// Deserializes the data from the given input
/// </summary>
/// <param name="input">the input reader</param>
public virtual object Read(TextReader input)
{
return this.Read(input, null);
}
/// <summary>
/// Deserializes the data from the given input
/// </summary>
/// <param name="input">the input reader</param>
/// <param name="targetType">the expected type of the serialized data</param>
public virtual object Read(TextReader input, Type targetType)
{
ITextTokenizer<T> tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new InvalidOperationException("Tokenizer is invalid");
}
return this.ReadSingle(tokenizer, tokenizer.GetTokens(input), targetType);
}
/// <summary>
/// Deserializes the data from the given input
/// </summary>
/// <param name="input">the input text</param>
/// <param name="ignored">a value used to trigger Type inference for <typeparamref name="TResult"/> (e.g. for deserializing anonymous objects)</param>
/// <typeparam name="TResult">the expected type of the serialized data</typeparam>
public virtual TResult Read<TResult>(string input, TResult ignored)
{
return this.Read<TResult>(input);
}
/// <summary>
/// Deserializes the data from the given input
/// </summary>
/// <param name="input">the input text</param>
/// <typeparam name="TResult">the expected type of the serialized data</typeparam>
public virtual TResult Read<TResult>(string input)
{
object value = this.Read(input, typeof(TResult));
return (value is TResult) ? (TResult)value : default(TResult);
}
/// <summary>
/// Deserializes the data from the given input
/// </summary>
/// <param name="input">the input text</param>
public virtual object Read(string input)
{
return this.Read(input, null);
}
/// <summary>
/// Deserializes the data from the given input
/// </summary>
/// <param name="input">the input text</param>
/// <param name="targetType">the expected type of the serialized data</param>
public virtual object Read(string input, Type targetType)
{
ITextTokenizer<T> tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new ArgumentNullException("tokenizer");
}
return this.ReadSingle(tokenizer, tokenizer.GetTokens(input), targetType);
}
/// <summary>
/// Deserializes a potentially endless sequence of objects from a stream source
/// </summary>
/// <param name="input">a streamed source of objects</param>
/// <returns>a sequence of objects</returns>
/// <remarks>
/// character stream => token stream => object stream
/// </remarks>
public IEnumerable ReadMany(TextReader input)
{
ITextTokenizer<T> tokenizer = this.GetTokenizer();
if (tokenizer == null)
{
throw new ArgumentNullException("tokenizer");
}
ITokenAnalyzer<T> analyzer = this.GetAnalyzer();
if (analyzer == null)
{
throw new ArgumentNullException("analyzer");
}
try
{
// chars stream => token stream => object stream
return analyzer.Analyze(tokenizer.GetTokens(input));
}
catch (DeserializationException)
{
throw;
}
catch (Exception ex)
{
throw new DeserializationException(ex.Message, tokenizer.Index, tokenizer.Line, tokenizer.Column, ex);
}
}
private object ReadSingle(ITextTokenizer<T> tokenizer, IEnumerable<Token<T>> tokens, Type targetType)
{
ITokenAnalyzer<T> analyzer = this.GetAnalyzer();
if (analyzer == null)
{
throw new ArgumentNullException("analyzer");
}
try
{
IEnumerator enumerator = analyzer.Analyze(tokens, targetType).GetEnumerator();
if (!enumerator.MoveNext())
{
return null;
}
// character stream => token stream => object stream
object value = enumerator.Current;
// enforce only one object in stream
if (!this.Settings.AllowTrailingContent && enumerator.MoveNext())
{
throw new DeserializationException("Invalid trailing content", tokenizer.Index, tokenizer.Line, tokenizer.Column);
}
return value;
}
catch (DeserializationException)
{
throw;
}
catch (Exception ex)
{
throw new DeserializationException(ex.Message, tokenizer.Index, tokenizer.Line, tokenizer.Column, ex);
}
}
#endregion Read Methods
#region Methods
protected abstract ITextTokenizer<T> GetTokenizer();
protected abstract ITokenAnalyzer<T> GetAnalyzer();
#endregion Methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDateTime
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
public static partial class DatetimeExtensions
{
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetNull(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetNullAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetInvalid(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetInvalidAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetOverflow(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetOverflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetOverflowAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetOverflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUnderflow(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetUnderflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUnderflowAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetUnderflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutUtcMaxDateTime(this IDatetime operations, DateTime? datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetime)s).PutUtcMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUtcMaxDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUtcMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get max datetime value 9999-12-31t23:59:59.9999999z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUtcLowercaseMaxDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetUtcLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value 9999-12-31t23:59:59.9999999z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUtcLowercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUtcUppercaseMaxDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetUtcUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value 9999-12-31T23:59:59.9999999Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUtcUppercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutLocalPositiveOffsetMaxDateTime(this IDatetime operations, DateTime? datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetime)s).PutLocalPositiveOffsetMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLocalPositiveOffsetMaxDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLocalPositiveOffsetMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetLocalPositiveOffsetLowercaseMaxDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalPositiveOffsetLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetLocalPositiveOffsetLowercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetLocalPositiveOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetLocalPositiveOffsetUppercaseMaxDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalPositiveOffsetUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetLocalPositiveOffsetUppercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetLocalPositiveOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutLocalNegativeOffsetMaxDateTime(this IDatetime operations, DateTime? datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetime)s).PutLocalNegativeOffsetMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max datetime value with positive numoffset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLocalNegativeOffsetMaxDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLocalNegativeOffsetMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetLocalNegativeOffsetUppercaseMaxDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalNegativeOffsetUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31T23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetLocalNegativeOffsetUppercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetLocalNegativeOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetLocalNegativeOffsetLowercaseMaxDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalNegativeOffsetLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value with positive num offset
/// 9999-12-31t23:59:59.9999999-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetLocalNegativeOffsetLowercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetLocalNegativeOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutUtcMinDateTime(this IDatetime operations, DateTime? datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetime)s).PutUtcMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUtcMinDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUtcMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUtcMinDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetUtcMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00Z
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUtcMinDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetUtcMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutLocalPositiveOffsetMinDateTime(this IDatetime operations, DateTime? datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetime)s).PutLocalPositiveOffsetMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLocalPositiveOffsetMinDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetLocalPositiveOffsetMinDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalPositiveOffsetMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00+14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetLocalPositiveOffsetMinDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutLocalNegativeOffsetMinDateTime(this IDatetime operations, DateTime? datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetime)s).PutLocalNegativeOffsetMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutLocalNegativeOffsetMinDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetLocalNegativeOffsetMinDateTime(this IDatetime operations)
{
return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalNegativeOffsetMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get min datetime value 0001-01-01T00:00:00-14:00
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetLocalNegativeOffsetMinDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateTime?> result = await operations.GetLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NicamHelper.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// Defines the NicamHelper class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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 Sitecore.Ecommerce.Classes
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Globalization;
using Publishing;
using SecurityModel;
using Sitecore.Security;
using Sitecore.Security.Accounts;
using Sitecore.Security.Authentication;
using Xml.Xsl;
/// <summary>
/// </summary>
public static class NicamHelper
{
/// <summary>
/// Gets the logged in status for the current user
/// </summary>
public static bool IsLoggedIn
{
get
{
User user = Sitecore.Context.User;
return
user != null
&& !Sitecore.Context.User.Name.Equals(GetValidUserInDomain("Anonymous"))
&& user.IsInRole(Consts.ExtranetRole)
&& user.GetDomainName().Equals(Sitecore.Context.Domain.Name);
}
}
/// <summary>
/// Gets the title of the current context item in HTML
/// </summary>
/// <returns>
/// </returns>
public static string GetTitle()
{
Item itmCurrent = Sitecore.Context.Item;
if (itmCurrent != null)
{
if (itmCurrent.Fields[Consts.MenuTitleFieldname] != null &&
!string.IsNullOrEmpty(itmCurrent.Fields[Consts.MenuTitleFieldname].Value))
{
return HtmlEncode(itmCurrent.Fields[Consts.MenuTitleFieldname].Value);
}
return HtmlEncode(itmCurrent.DisplayName);
}
return "Ecommerce";
}
/// <summary>
/// Gets a HTML encoded string
/// </summary>
/// <param name="str">
/// </param>
/// <returns>
/// </returns>
public static string HtmlEncode(string str)
{
if (string.IsNullOrEmpty(str))
{
return string.Empty;
}
return HttpUtility.HtmlEncode(str);
}
/// <summary>
/// </summary>
/// <param name="rootPath">
/// </param>
/// <param name="fieldname">
/// </param>
/// <param name="emptyItem">
/// </param>
/// <returns>
/// </returns>
public static IEnumerable<KeyValuePair<string, string>> GetList(string rootPath, string fieldname,
bool emptyItem)
{
Item root = Sitecore.Context.Database.GetItem(rootPath);
if (root != null)
{
if (emptyItem)
{
yield return new KeyValuePair<string, string>(string.Empty, " - ");
}
foreach (Item itm in root.Children)
{
string key = string.IsNullOrEmpty(fieldname) ? itm.DisplayName : itm[fieldname];
yield return new KeyValuePair<string, string>(itm.ID.ToString(), key);
}
}
}
/// <summary>
/// </summary>
/// <param name="rootPath">
/// </param>
/// <param name="fieldname">
/// </param>
/// <returns>
/// </returns>
public static IEnumerable<KeyValuePair<string, string>> GetList(string rootPath, string fieldname)
{
return GetList(rootPath, fieldname, false);
}
/// <summary>
/// </summary>
/// <param name="rootPath">
/// </param>
/// <returns>
/// </returns>
public static IEnumerable<KeyValuePair<string, string>> GetList(string rootPath)
{
return GetList(rootPath, null);
}
/// <summary>
/// </summary>
/// <param name="listItems">
/// </param>
/// <returns>
/// </returns>
public static string ComposeSitecoreList(ListItemCollection listItems)
{
string selctedItems = string.Empty;
foreach (ListItem listItem in listItems)
{
if (listItem.Selected)
{
selctedItems += "|" + listItem.Value;
}
}
if (!string.IsNullOrEmpty(selctedItems))
{
selctedItems = selctedItems.Substring(1);
}
return selctedItems;
}
/// <summary>
/// </summary>
/// <param name="userOptions">
/// </param>
/// <param name="userProfile">
/// </param>
public static void RegisterUser(StringDictionary userOptions, StringDictionary userProfile)
{
User newUser = User.Create(userOptions["UserName"], userOptions["Password"]);
newUser.Roles.Add(Role.FromName(userOptions["Roles"]));
UserProfile profile = newUser.Profile;
using (new SecurityDisabler())
{
Item item = Client.CoreDatabase.GetItem(userOptions["UserProfile"]);
profile.ProfileItemId = item.ID.ToString();
profile.FullName = userOptions["FullName"];
profile.Email = userOptions["Email"];
profile.Comment = string.Empty;
profile.Portrait = userOptions["Portrait"];
foreach (string key in userProfile.Keys)
{
profile.SetCustomProperty(key, userProfile[key]);
}
profile.Save();
}
}
/// <summary>
/// </summary>
/// <param name="user">
/// </param>
/// <param name="userOptions">
/// </param>
/// <param name="userProfile">
/// </param>
public static void UpdateUserProfile(User user, StringDictionary userOptions, StringDictionary userProfile)
{
if (User.Exists(user.Name))
{
UserProfile profile = user.Profile;
using (new SecurityDisabler())
{
Item item = Client.CoreDatabase.GetItem(userOptions["UserProfile"]);
profile.ProfileItemId = item.ID.ToString();
profile.FullName = userOptions["FullName"];
profile.Email = userOptions["Email"];
profile.Comment = string.Empty;
profile.Portrait = userOptions["Portrait"];
foreach (string key in userProfile.Keys)
{
profile.SetCustomProperty(key, userProfile[key]);
}
profile.Save();
}
}
}
/// <summary>
/// </summary>
/// <param name="user">
/// </param>
/// <param name="oldPassword">
/// </param>
/// <param name="newPassword">
/// </param>
/// <returns>
/// </returns>
public static bool ChangeUserPassword(User user, string oldPassword, string newPassword)
{
MembershipUser memeberShipUser = Membership.GetUser(user.Name);
return memeberShipUser.ChangePassword(oldPassword, newPassword);
}
/// <summary>
/// </summary>
/// <param name="userName">
/// </param>
/// <returns>
/// </returns>
public static string GetValidUserInDomain(string userName)
{
return string.Concat(Sitecore.Context.Domain.Name, @"\", userName);
}
/// <summary>
/// </summary>
/// <param name="userName">
/// </param>
/// <param name="password">
/// </param>
/// <returns>
/// </returns>
public static bool Login(string userName, string password)
{
try
{
return AuthenticationManager.Login(userName, password);
}
catch
{
return false;
}
}
/// <summary>
/// </summary>
public static void Logout()
{
AuthenticationManager.Logout();
}
/// <summary>
/// </summary>
/// <param name="list">
/// </param>
/// <param name="rootPath">
/// </param>
/// <param name="fieldName">
/// </param>
/// <param name="selectedValue">
/// </param>
/// <param name="selectedText">
/// </param>
/// <param name="emptyItem">
/// </param>
public static void BindToListControl(ListControl list, string rootPath, string fieldName, string selectedValue,
string selectedText, bool emptyItem)
{
IEnumerable<KeyValuePair<string, string>> listDataSource = GetList(rootPath, fieldName, emptyItem);
BindToListControl(list, listDataSource, selectedValue, selectedText);
}
/// <summary>
/// </summary>
/// <param name="list">
/// </param>
/// <param name="listDataSource">
/// </param>
/// <param name="selectedValue">
/// </param>
/// <param name="selectedText">
/// </param>
public static void BindToListControl(ListControl list, IEnumerable<KeyValuePair<string, string>> listDataSource,
string selectedValue, string selectedText)
{
list.Items.Clear();
list.DataSource = listDataSource;
list.DataValueField = "Key";
list.DataTextField = "Value";
list.DataBind();
if (!string.IsNullOrEmpty(selectedValue))
{
string[] selectedValues = selectedValue.Split('|');
foreach (string val in selectedValues)
{
if (!string.IsNullOrEmpty(val))
{
ListItem selctedItem = list.Items.FindByValue(val);
if (selctedItem != null)
{
selctedItem.Selected = true;
}
}
}
return;
}
if (!string.IsNullOrEmpty(selectedText))
{
ListItem selectedItem = list.Items.FindByText(selectedText);
if (selectedItem != null)
{
selectedItem.Selected = true;
}
return;
}
}
/// <summary>
/// </summary>
/// <param name="list">
/// </param>
/// <param name="rootPath">
/// </param>
/// <param name="fieldName">
/// </param>
/// <param name="selectedValue">
/// </param>
/// <param name="selectedText">
/// </param>
public static void BindToListControl(ListControl list, string rootPath, string fieldName, string selectedValue,
string selectedText)
{
BindToListControl(list, rootPath, fieldName, selectedValue, selectedText, false);
}
/// <summary>
/// </summary>
/// <param name="name">
/// </param>
/// <returns>
/// </returns>
public static string SafeRequest(string name)
{
return HttpContext.Current.Request[name] ?? string.Empty;
}
/// <summary>
/// </summary>
/// <param name="name">
/// </param>
/// <returns>
/// </returns>
public static string SafeRequestForm(string name)
{
return HttpContext.Current.Request.Form[name] ?? string.Empty;
}
/// <summary>
/// </summary>
/// <param name="name">
/// </param>
/// <returns>
/// </returns>
public static string SafeRequestQs(string name)
{
return HttpContext.Current.Request.QueryString[name] ?? string.Empty;
}
/// <summary>
/// </summary>
/// <param name="name">
/// </param>
/// <returns>
/// </returns>
public static string SafeRequestSession(string name)
{
return HttpContext.Current.Session[name] != null
? HttpContext.Current.Session[name].ToString()
: string.Empty;
}
/// <summary>
/// </summary>
/// <param name="url">
/// </param>
/// <returns>
/// </returns>
public static string UrlEncode(string url)
{
return url != null ? HttpUtility.UrlEncode(url) : string.Empty;
}
/// <summary>
/// </summary>
/// <param name="url">
/// </param>
/// <returns>
/// </returns>
public static string UrlDecode(string url)
{
return url != null ? HttpUtility.UrlDecode(url) : string.Empty;
}
/// <summary>
/// </summary>
/// <param name="page">
/// </param>
/// <param name="qsParameter">
/// </param>
/// <param name="qs">
/// </param>
/// <returns>
/// </returns>
public static string RedirectUrl(string page, string qsParameter, string qs)
{
string url = UrlEncode(qs);
url = string.Concat(page, "?", qsParameter, "=", url);
return url;
}
/// <summary>
/// </summary>
/// <param name="reviewTitle">
/// </param>
/// <param name="reviewText">
/// </param>
/// <param name="reviewRate">
/// </param>
public static void AddReview(string reviewTitle, string reviewText, string reviewRate)
{
using (new SecurityDisabler())
{
Item currentItm = Sitecore.Context.Item;
Database masterDb = Factory.GetDatabase("master");
if (currentItm != null && masterDb != null)
{
// ------------------------------------------
// validation
// ------------------------------------------
bool reviewValidate = false;
if (!reviewTitle.Equals(string.Empty) &&
!reviewText.Equals(string.Empty) &&
!reviewRate.Equals(string.Empty))
{
reviewValidate = true;
}
if (reviewValidate)
{
Item reviewsFolderItm =
masterDb.Items[string.Concat(currentItm.Paths.FullPath, "/", Consts.ReviewFolderName)];
Database webDB = Factory.GetDatabase("web");
Item reviewsFolderItmOnWeb =
webDB.Items[string.Concat(currentItm.Paths.FullPath, "/", Consts.ReviewFolderName)];
if (reviewsFolderItm == null)
{
if (reviewsFolderItmOnWeb != null)
{
reviewsFolderItmOnWeb.Delete();
}
string templatePath = string.Concat(Consts.TemplatesPath, "/",
Consts.ReviewFolderTemplateName);
TemplateItem reviewsFolderTemplate = masterDb.Templates[templatePath];
Item curItmInMasterDb = masterDb.Items[currentItm.Paths.FullPath];
reviewsFolderItm = curItmInMasterDb.Add("Reviews", reviewsFolderTemplate);
}
else
{
if (reviewsFolderItmOnWeb != null)
{
if (!reviewsFolderItmOnWeb.ID.ToString().Equals(reviewsFolderItm.ID.ToString()))
{
reviewsFolderItmOnWeb.Delete();
}
}
}
if (reviewsFolderItm != null)
{
// ------------------------------------------
// create name from date and time
// ------------------------------------------
string reviewName = DateUtil.ToIsoDate(DateTime.Now, false);
// ------------------------------------------
// create item from template
// ------------------------------------------
string templatePath = string.Concat(Consts.TemplatesPath, "/", Consts.ReviewItemTemplateName);
TemplateItem reviewTemplate = masterDb.Templates[templatePath];
if (reviewTemplate != null)
{
Item itm = reviewsFolderItm.Add(reviewName, reviewTemplate);
// ------------------------------------------
// review item fields
// ------------------------------------------
using (new EditContext(itm, true, false))
{
itm.Fields["Title"].Value = reviewTitle;
itm.Fields["Description"].Value = reviewText;
itm.Fields["Rate"].Value = reviewRate;
}
itm.Locking.Unlock();
// ------------------------------------------
// publish item
// ------------------------------------------
PublishOneItem(itm.Parent);
}
}
}
}
}
}
/// <summary>
/// </summary>
/// <param name="item">
/// </param>
private static void PublishOneItem(Item item)
{
Language lang = Sitecore.Context.Language;
Database masterDb = Factory.GetDatabase("master");
Database webDB = Factory.GetDatabase("web");
var opt = new PublishOptions(masterDb, webDB, PublishMode.SingleItem, lang, DateTime.Now);
opt.RootItem = item;
opt.Deep = true;
var pb = new Publisher(opt);
pb.PublishAsync();
}
/// <summary>
/// </summary>
/// <param name="currentItm">
/// </param>
/// <returns>
/// </returns>
public static double RatePage(Item currentItm)
{
double rateDouble = 0;
if (currentItm != null)
{
double totalMarks;
double totalVotes;
if (currentItm.Fields["Total Marks"] == null || currentItm.Fields["Total Votes"] == null)
{
return rateDouble;
}
Double.TryParse(currentItm.Fields["Total Marks"].Value, out totalMarks);
Double.TryParse(currentItm.Fields["Total Votes"].Value, out totalVotes);
if (totalMarks == 0 || totalVotes == 0)
{
return rateDouble;
}
double d = totalMarks / totalVotes;
rateDouble = Math.Round(d);
}
return rateDouble;
}
/// <summary>
/// </summary>
/// <param name="id">
/// </param>
/// <returns>
/// </returns>
public static double RatePage(string id)
{
Item currentItm = Sitecore.Context.Database.GetItem(id);
return RatePage(currentItm);
}
/// <summary>
/// </summary>
/// <param name="id">
/// </param>
/// <param name="voice">
/// </param>
/// <param name="rate">
/// </param>
/// <returns>
/// </returns>
public static bool VoteForPage(string id, int voice, int rate)
{
Database db = Factory.GetDatabase("master");
if (db != null)
{
Item votePage = db.Items.GetItem(id);
if (votePage != null && votePage.Fields["Total Marks"] != null &&
votePage.Fields["Total Votes"].Value != null)
{
int totalMarks;
int totalVotes;
int.TryParse(votePage.Fields["Total Marks"].Value, out totalMarks);
int.TryParse(votePage.Fields["Total Votes"].Value, out totalVotes);
totalMarks += rate;
totalVotes += voice;
using (new SecurityDisabler())
{
using (new EditContext(votePage))
{
votePage.Fields["Total Marks"].Value = totalMarks.ToString();
votePage.Fields["Total Votes"].Value = totalVotes.ToString();
}
}
// Publishing
PublishOneItem(votePage);
return true;
}
}
return false;
}
/// <summary>
/// </summary>
/// <param name="itemId">
/// </param>
/// <param name="sectionName">
/// </param>
/// <returns>
/// </returns>
public static TemplateFieldItem[] GetSectionFields(string itemId, string sectionName)
{
Item itm = Sitecore.Context.Database.GetItem(itemId);
return itm != null ? Array.FindAll(itm.Template.Fields, fld => fld.Section.Name.Equals("Specification") && itm.Fields[fld.Name].Value != string.Empty) : null;
}
/// <summary>
/// </summary>
/// <param name="templateName">
/// </param>
/// <returns>
/// </returns>
public static ID GetTemplateID(string templateName)
{
TemplateItem templateItem = GetTemplateItem(templateName);
if (templateItem != null)
{
return templateItem.ID;
}
return null;
}
/// <summary>
/// </summary>
/// <param name="templateName">
/// </param>
/// <returns>
/// </returns>
public static TemplateItem GetTemplateItem(string templateName)
{
string fullTemplatePath = String.Concat(Consts.TemplatesRootPath, @"/", templateName);
return Sitecore.Context.Database.Templates[fullTemplatePath];
}
/// <summary>
/// </summary>
/// <param name="words">
/// </param>
/// <returns>
/// </returns>
public static string SafeSearchString(string words)
{
return !string.IsNullOrEmpty(words) ? words.Replace("'", string.Empty).Replace("\"", string.Empty) : string.Empty;
}
/// <summary>
/// </summary>
/// <param name="foundItems">
/// </param>
/// <returns>
/// </returns>
public static IEnumerable<Item> SortByUpdatedDate(IEnumerable<Item> foundItems)
{
IOrderedEnumerable<Item> sortedItems = from item in foundItems
orderby item.Fields[FieldIDs.Updated].Value descending
select item;
return sortedItems;
}
/// <summary>
/// </summary>
/// <param name="items">
/// </param>
/// <param name="top">
/// </param>
/// <returns>
/// </returns>
public static IEnumerable<Item> ReturnTopResults(IEnumerable<Item> items, int top)
{
IEnumerable<Item> topItems = items.Take(top);
return topItems;
}
/// <summary>
/// </summary>
/// <param name="queries">
/// </param>
/// <returns>
/// </returns>
public static List<Item> DoQueries(StringCollection queries)
{
var list = new List<Item>();
foreach (string queryString in queries)
{
List<Item> items = DoQuery(queryString);
list.AddRange(items);
}
return list;
}
/// <summary>
/// </summary>
/// <param name="queryString">
/// </param>
/// <returns>
/// </returns>
public static List<Item> DoQuery(string queryString)
{
var list = new List<Item>();
Item[] items = Sitecore.Context.Database.SelectItems(queryString);
list.AddRange(items);
return list;
}
/// <summary>
/// </summary>
/// <param name="rootItemId">
/// </param>
/// <returns>
/// </returns>
public static string GetChildrenStr(string rootItemId)
{
var str = new StringBuilder();
Item rootItm = Sitecore.Context.Database.GetItem(rootItemId);
if (rootItm != null)
{
foreach (Item itm in rootItm.Children)
{
str.Append(string.Concat(itm.ID.ToString(), "|"));
}
}
return str.ToString();
}
}
}
| |
// 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 gagr = Google.Api.Gax.ResourceNames;
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.BigQuery.Storage.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedBigQueryReadClientTest
{
[xunit::FactAttribute]
public void CreateReadSessionRequestObject()
{
moq::Mock<BigQueryRead.BigQueryReadClient> mockGrpcClient = new moq::Mock<BigQueryRead.BigQueryReadClient>(moq::MockBehavior.Strict);
CreateReadSessionRequest request = new CreateReadSessionRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ReadSession = new ReadSession(),
MaxStreamCount = 1813871107,
};
ReadSession expectedResponse = new ReadSession
{
ReadSessionName = ReadSessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]"),
ExpireTime = new wkt::Timestamp(),
DataFormat = DataFormat.Arrow,
AvroSchema = new AvroSchema(),
ArrowSchema = new ArrowSchema(),
TableAsTableName = TableName.FromProjectDatasetTable("[PROJECT]", "[DATASET]", "[TABLE]"),
TableModifiers = new ReadSession.Types.TableModifiers(),
ReadOptions = new ReadSession.Types.TableReadOptions(),
Streams = { new ReadStream(), },
EstimatedTotalBytesScanned = 3051848153574264650L,
};
mockGrpcClient.Setup(x => x.CreateReadSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BigQueryReadClient client = new BigQueryReadClientImpl(mockGrpcClient.Object, null);
ReadSession response = client.CreateReadSession(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateReadSessionRequestObjectAsync()
{
moq::Mock<BigQueryRead.BigQueryReadClient> mockGrpcClient = new moq::Mock<BigQueryRead.BigQueryReadClient>(moq::MockBehavior.Strict);
CreateReadSessionRequest request = new CreateReadSessionRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ReadSession = new ReadSession(),
MaxStreamCount = 1813871107,
};
ReadSession expectedResponse = new ReadSession
{
ReadSessionName = ReadSessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]"),
ExpireTime = new wkt::Timestamp(),
DataFormat = DataFormat.Arrow,
AvroSchema = new AvroSchema(),
ArrowSchema = new ArrowSchema(),
TableAsTableName = TableName.FromProjectDatasetTable("[PROJECT]", "[DATASET]", "[TABLE]"),
TableModifiers = new ReadSession.Types.TableModifiers(),
ReadOptions = new ReadSession.Types.TableReadOptions(),
Streams = { new ReadStream(), },
EstimatedTotalBytesScanned = 3051848153574264650L,
};
mockGrpcClient.Setup(x => x.CreateReadSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReadSession>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BigQueryReadClient client = new BigQueryReadClientImpl(mockGrpcClient.Object, null);
ReadSession responseCallSettings = await client.CreateReadSessionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReadSession responseCancellationToken = await client.CreateReadSessionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateReadSession()
{
moq::Mock<BigQueryRead.BigQueryReadClient> mockGrpcClient = new moq::Mock<BigQueryRead.BigQueryReadClient>(moq::MockBehavior.Strict);
CreateReadSessionRequest request = new CreateReadSessionRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ReadSession = new ReadSession(),
MaxStreamCount = 1813871107,
};
ReadSession expectedResponse = new ReadSession
{
ReadSessionName = ReadSessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]"),
ExpireTime = new wkt::Timestamp(),
DataFormat = DataFormat.Arrow,
AvroSchema = new AvroSchema(),
ArrowSchema = new ArrowSchema(),
TableAsTableName = TableName.FromProjectDatasetTable("[PROJECT]", "[DATASET]", "[TABLE]"),
TableModifiers = new ReadSession.Types.TableModifiers(),
ReadOptions = new ReadSession.Types.TableReadOptions(),
Streams = { new ReadStream(), },
EstimatedTotalBytesScanned = 3051848153574264650L,
};
mockGrpcClient.Setup(x => x.CreateReadSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BigQueryReadClient client = new BigQueryReadClientImpl(mockGrpcClient.Object, null);
ReadSession response = client.CreateReadSession(request.Parent, request.ReadSession, request.MaxStreamCount);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateReadSessionAsync()
{
moq::Mock<BigQueryRead.BigQueryReadClient> mockGrpcClient = new moq::Mock<BigQueryRead.BigQueryReadClient>(moq::MockBehavior.Strict);
CreateReadSessionRequest request = new CreateReadSessionRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ReadSession = new ReadSession(),
MaxStreamCount = 1813871107,
};
ReadSession expectedResponse = new ReadSession
{
ReadSessionName = ReadSessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]"),
ExpireTime = new wkt::Timestamp(),
DataFormat = DataFormat.Arrow,
AvroSchema = new AvroSchema(),
ArrowSchema = new ArrowSchema(),
TableAsTableName = TableName.FromProjectDatasetTable("[PROJECT]", "[DATASET]", "[TABLE]"),
TableModifiers = new ReadSession.Types.TableModifiers(),
ReadOptions = new ReadSession.Types.TableReadOptions(),
Streams = { new ReadStream(), },
EstimatedTotalBytesScanned = 3051848153574264650L,
};
mockGrpcClient.Setup(x => x.CreateReadSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReadSession>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BigQueryReadClient client = new BigQueryReadClientImpl(mockGrpcClient.Object, null);
ReadSession responseCallSettings = await client.CreateReadSessionAsync(request.Parent, request.ReadSession, request.MaxStreamCount, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReadSession responseCancellationToken = await client.CreateReadSessionAsync(request.Parent, request.ReadSession, request.MaxStreamCount, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateReadSessionResourceNames()
{
moq::Mock<BigQueryRead.BigQueryReadClient> mockGrpcClient = new moq::Mock<BigQueryRead.BigQueryReadClient>(moq::MockBehavior.Strict);
CreateReadSessionRequest request = new CreateReadSessionRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ReadSession = new ReadSession(),
MaxStreamCount = 1813871107,
};
ReadSession expectedResponse = new ReadSession
{
ReadSessionName = ReadSessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]"),
ExpireTime = new wkt::Timestamp(),
DataFormat = DataFormat.Arrow,
AvroSchema = new AvroSchema(),
ArrowSchema = new ArrowSchema(),
TableAsTableName = TableName.FromProjectDatasetTable("[PROJECT]", "[DATASET]", "[TABLE]"),
TableModifiers = new ReadSession.Types.TableModifiers(),
ReadOptions = new ReadSession.Types.TableReadOptions(),
Streams = { new ReadStream(), },
EstimatedTotalBytesScanned = 3051848153574264650L,
};
mockGrpcClient.Setup(x => x.CreateReadSession(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BigQueryReadClient client = new BigQueryReadClientImpl(mockGrpcClient.Object, null);
ReadSession response = client.CreateReadSession(request.ParentAsProjectName, request.ReadSession, request.MaxStreamCount);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateReadSessionResourceNamesAsync()
{
moq::Mock<BigQueryRead.BigQueryReadClient> mockGrpcClient = new moq::Mock<BigQueryRead.BigQueryReadClient>(moq::MockBehavior.Strict);
CreateReadSessionRequest request = new CreateReadSessionRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ReadSession = new ReadSession(),
MaxStreamCount = 1813871107,
};
ReadSession expectedResponse = new ReadSession
{
ReadSessionName = ReadSessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]"),
ExpireTime = new wkt::Timestamp(),
DataFormat = DataFormat.Arrow,
AvroSchema = new AvroSchema(),
ArrowSchema = new ArrowSchema(),
TableAsTableName = TableName.FromProjectDatasetTable("[PROJECT]", "[DATASET]", "[TABLE]"),
TableModifiers = new ReadSession.Types.TableModifiers(),
ReadOptions = new ReadSession.Types.TableReadOptions(),
Streams = { new ReadStream(), },
EstimatedTotalBytesScanned = 3051848153574264650L,
};
mockGrpcClient.Setup(x => x.CreateReadSessionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ReadSession>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BigQueryReadClient client = new BigQueryReadClientImpl(mockGrpcClient.Object, null);
ReadSession responseCallSettings = await client.CreateReadSessionAsync(request.ParentAsProjectName, request.ReadSession, request.MaxStreamCount, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ReadSession responseCancellationToken = await client.CreateReadSessionAsync(request.ParentAsProjectName, request.ReadSession, request.MaxStreamCount, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SplitReadStreamRequestObject()
{
moq::Mock<BigQueryRead.BigQueryReadClient> mockGrpcClient = new moq::Mock<BigQueryRead.BigQueryReadClient>(moq::MockBehavior.Strict);
SplitReadStreamRequest request = new SplitReadStreamRequest
{
ReadStreamName = ReadStreamName.FromProjectLocationSessionStream("[PROJECT]", "[LOCATION]", "[SESSION]", "[STREAM]"),
Fraction = 6.953526182705065E+17,
};
SplitReadStreamResponse expectedResponse = new SplitReadStreamResponse
{
PrimaryStream = new ReadStream(),
RemainderStream = new ReadStream(),
};
mockGrpcClient.Setup(x => x.SplitReadStream(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
BigQueryReadClient client = new BigQueryReadClientImpl(mockGrpcClient.Object, null);
SplitReadStreamResponse response = client.SplitReadStream(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SplitReadStreamRequestObjectAsync()
{
moq::Mock<BigQueryRead.BigQueryReadClient> mockGrpcClient = new moq::Mock<BigQueryRead.BigQueryReadClient>(moq::MockBehavior.Strict);
SplitReadStreamRequest request = new SplitReadStreamRequest
{
ReadStreamName = ReadStreamName.FromProjectLocationSessionStream("[PROJECT]", "[LOCATION]", "[SESSION]", "[STREAM]"),
Fraction = 6.953526182705065E+17,
};
SplitReadStreamResponse expectedResponse = new SplitReadStreamResponse
{
PrimaryStream = new ReadStream(),
RemainderStream = new ReadStream(),
};
mockGrpcClient.Setup(x => x.SplitReadStreamAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SplitReadStreamResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
BigQueryReadClient client = new BigQueryReadClientImpl(mockGrpcClient.Object, null);
SplitReadStreamResponse responseCallSettings = await client.SplitReadStreamAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SplitReadStreamResponse responseCancellationToken = await client.SplitReadStreamAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System;
using System.Linq;
namespace UIWidgets
{
/// <summary>
/// ListViewGameObjects event.
/// </summary>
[System.Serializable]
public class ListViewGameObjectsEvent : UnityEvent<int,GameObject>
{
}
[AddComponentMenu("UI/ListViewGameObjects", 255)]
/// <summary>
/// List view with GameObjects.
/// </summary>
public class ListViewGameObjects : ListViewBase {
[SerializeField]
List<GameObject> objects = new List<GameObject>();
/// <summary>
/// Gets the objects.
/// </summary>
/// <value>The objects.</value>
public List<GameObject> Objects {
get {
return new List<GameObject>(objects);
}
private set {
UpdateItems(value);
}
}
List<UnityAction<PointerEventData>> callbacksEnter = new List<UnityAction<PointerEventData>>();
List<UnityAction<PointerEventData>> callbacksExit = new List<UnityAction<PointerEventData>>();
/// <summary>
/// Sort function.
/// </summary>
public Func<IEnumerable<GameObject>,IEnumerable<GameObject>> SortFunc = null;
/// <summary>
/// What to do when the object selected.
/// </summary>
public ListViewGameObjectsEvent OnSelectObject = new ListViewGameObjectsEvent();
/// <summary>
/// What to do when the object deselected.
/// </summary>
public ListViewGameObjectsEvent OnDeselectObject = new ListViewGameObjectsEvent();
/// <summary>
/// What to do when the event system send a pointer enter Event.
/// </summary>
public ListViewGameObjectsEvent OnPointerEnterObject = new ListViewGameObjectsEvent();
/// <summary>
/// What to do when the event system send a pointer exit Event.
/// </summary>
public ListViewGameObjectsEvent OnPointerExitObject = new ListViewGameObjectsEvent();
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
Start();
}
[System.NonSerialized]
bool isStartedListViewGameObjects = false;
/// <summary>
/// Start this instance.
/// </summary>
public override void Start()
{
if (isStartedListViewGameObjects)
{
return ;
}
isStartedListViewGameObjects = true;
base.Start();
DestroyGameObjects = true;
UpdateItems();
OnSelect.AddListener(OnSelectCallback);
OnDeselect.AddListener(OnDeselectCallback);
}
/// <summary>
/// Raises the select callback event.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="item">Item.</param>
void OnSelectCallback(int index, ListViewItem item)
{
OnSelectObject.Invoke(index, objects[index]);
}
/// <summary>
/// Raises the deselect callback event.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="item">Item.</param>
void OnDeselectCallback(int index, ListViewItem item)
{
OnDeselectObject.Invoke(index, objects[index]);
}
/// <summary>
/// Raises the pointer enter callback event.
/// </summary>
/// <param name="index">Index.</param>
void OnPointerEnterCallback(int index)
{
OnPointerEnterObject.Invoke(index, objects[index]);
}
/// <summary>
/// Raises the pointer exit callback event.
/// </summary>
/// <param name="index">Index.</param>
void OnPointerExitCallback(int index)
{
OnPointerExitObject.Invoke(index, objects[index]);
}
/// <summary>
/// Updates the items.
/// </summary>
public override void UpdateItems()
{
UpdateItems(objects);
}
/// <summary>
/// Add the specified item.
/// </summary>
/// <param name="item">Item.</param>
/// <returns>Index of added item.</returns>
public virtual int Add(GameObject item)
{
var newObjects = Objects;
newObjects.Add(item);
UpdateItems(newObjects);
var index = objects.IndexOf(item);
return index;
}
/// <summary>
/// Remove the specified item.
/// </summary>
/// <param name="item">Item.</param>
/// <returns>Index of removed item.</returns>
public virtual int Remove(GameObject item)
{
var index = objects.IndexOf(item);
if (index==-1)
{
return index;
}
var newObjects = Objects;
newObjects.Remove(item);
UpdateItems(newObjects);
return index;
}
void RemoveCallback(ListViewItem item, int index)
{
if (item==null)
{
return ;
}
if (index < callbacksEnter.Count)
{
item.onPointerEnter.RemoveListener(callbacksEnter[index]);
}
if (index < callbacksExit.Count)
{
item.onPointerExit.RemoveListener(callbacksExit[index]);
}
}
/// <summary>
/// Removes the callbacks.
/// </summary>
void RemoveCallbacks()
{
base.Items.ForEach(RemoveCallback);
callbacksEnter.Clear();
callbacksExit.Clear();
}
/// <summary>
/// Adds the callbacks.
/// </summary>
void AddCallbacks()
{
base.Items.ForEach(AddCallback);
}
/// <summary>
/// Adds the callback.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="index">Index.</param>
void AddCallback(ListViewItem item, int index)
{
callbacksEnter.Add(ev => OnPointerEnterCallback(index));
callbacksExit.Add(ev => OnPointerExitCallback(index));
item.onPointerEnter.AddListener(callbacksEnter[index]);
item.onPointerExit.AddListener(callbacksExit[index]);
}
/// <summary>
/// Sorts the items.
/// </summary>
/// <returns>The items.</returns>
/// <param name="newItems">New items.</param>
List<GameObject> SortItems(IEnumerable<GameObject> newItems)
{
var temp = newItems;
if (SortFunc!=null)
{
temp = SortFunc(temp);
}
return temp.ToList();
}
/// <summary>
/// Clear items of this instance.
/// </summary>
public override void Clear()
{
if (DestroyGameObjects)
{
objects.ForEach(Destroy);
}
UpdateItems(new List<GameObject>());
}
/// <summary>
/// Updates the items.
/// </summary>
/// <param name="newItems">New items.</param>
void UpdateItems(List<GameObject> newItems)
{
RemoveCallbacks();
newItems = SortItems(newItems);
var new_selected_indicies = SelectedIndicies
.Select(x => objects.Count > x ? newItems.IndexOf(objects[x]) : -1)
.Where(x => x!=-1).ToList();
SelectedIndicies.Except(new_selected_indicies).ForEach(Deselect);
objects = newItems;
base.Items = newItems.Convert(x => x.GetComponent<ListViewItem>() ?? x.AddComponent<ListViewItem>());
SelectedIndicies = new_selected_indicies;
AddCallbacks();
}
/// <summary>
/// This function is called when the MonoBehaviour will be destroyed.
/// </summary>
protected override void OnDestroy()
{
OnSelect.RemoveListener(OnSelectCallback);
OnDeselect.RemoveListener(OnDeselectCallback);
RemoveCallbacks();
base.OnDestroy();
}
#if UNITY_EDITOR
[UnityEditor.MenuItem("GameObject/UI/ListViewGameObjects", false, 1070)]
static void CreateObject()
{
Utilites.CreateWidgetFromAsset("ListViewGameObjects");
}
#endif
}
}
| |
namespace Volante.Impl
{
using System;
using System.Collections;
using System.Collections.Generic;
using Volante;
public class LinkImpl<T> : ILink<T> where T : class,IPersistent
{
private void Modify()
{
if (owner != null)
owner.Modify();
}
public int Count
{
get
{
return used;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public void CopyTo(T[] dst, int i)
{
Pin();
Array.Copy(arr, 0, dst, i, used);
}
public virtual int Size()
{
return used;
}
public virtual int Length
{
get
{
return used;
}
set
{
if (value < used)
{
Array.Clear(arr, value, used - value);
Modify();
}
else
{
reserveSpace(value - used);
}
used = value;
}
}
public virtual T this[int i]
{
get
{
return Get(i);
}
set
{
Set(i, value);
}
}
void EnsureValidIndex(int i)
{
if (i < 0 || i >= used)
throw new IndexOutOfRangeException();
}
public virtual T Get(int i)
{
EnsureValidIndex(i);
return loadElem(i);
}
public virtual IPersistent GetRaw(int i)
{
EnsureValidIndex(i);
return arr[i];
}
public virtual void Set(int i, T obj)
{
EnsureValidIndex(i);
arr[i] = obj;
Modify();
}
public bool Remove(T obj)
{
int i = IndexOf(obj);
if (i >= 0)
{
RemoveAt(i);
return true;
}
return false;
}
public virtual void RemoveAt(int i)
{
EnsureValidIndex(i);
used -= 1;
Array.Copy(arr, i + 1, arr, i, used - i);
arr[used] = null;
Modify();
}
internal void reserveSpace(int len)
{
if (used + len > arr.Length)
{
int newLen = used + len > arr.Length * 2 ? used + len : arr.Length * 2;
IPersistent[] newArr = new IPersistent[newLen];
Array.Copy(arr, 0, newArr, 0, used);
arr = newArr;
}
Modify();
}
public virtual void Insert(int i, T obj)
{
EnsureValidIndex(i);
reserveSpace(1);
Array.Copy(arr, i, arr, i + 1, used - i);
arr[i] = obj;
used += 1;
}
public virtual void Add(T obj)
{
reserveSpace(1);
arr[used++] = obj;
}
public virtual void AddAll(T[] a)
{
AddAll(a, 0, a.Length);
}
public virtual void AddAll(T[] a, int from, int length)
{
reserveSpace(length);
Array.Copy(a, from, arr, used, length);
used += length;
}
public virtual void AddAll(ILink<T> link)
{
int n = link.Length;
reserveSpace(n);
for (int i = 0; i < n; i++)
{
arr[used++] = link.GetRaw(i);
}
}
public virtual Array ToRawArray()
{
//TODO: this seems like the right code, but changing it
//breaks a lot of code in Btree (it uses ILink internally
//for its implementation). Maybe they rely on having the
//original array
//T[] arrUsed = new T[used];
//Array.Copy(arr, arrUsed, used);
//return arrUsed;
return arr;
}
public virtual T[] ToArray()
{
T[] a = new T[used];
for (int i = used; --i >= 0; )
{
a[i] = loadElem(i);
}
return a;
}
public virtual bool Contains(T obj)
{
return IndexOf(obj) >= 0;
}
int IndexOfByOid(int oid)
{
for (int i = 0; i < used; i++)
{
IPersistent elem = arr[i];
if (elem != null && elem.Oid == oid)
return i;
}
return -1;
}
int IndexOfByObj(T obj)
{
IPersistent po = (IPersistent)obj;
for (int i = 0; i < used; i++)
{
IPersistent o = arr[i];
if (o == obj)
return i;
// TODO: compare by oid if o is PersistentStub ?
}
return -1;
}
public virtual int IndexOf(T obj)
{
int oid = obj.Oid;
int idx;
if (obj != null && oid != 0)
idx = IndexOfByOid(oid);
else
idx = IndexOfByObj(obj);
return idx;
}
public virtual bool ContainsElement(int i, T obj)
{
EnsureValidIndex(i);
IPersistent elem = arr[i];
T elTyped = elem as T;
if (elTyped == obj)
return true;
if (null == elem)
return false;
return elem.Oid != 0 && elem.Oid == obj.Oid;
}
public virtual void Clear()
{
Array.Clear(arr, 0, used);
used = 0;
Modify();
}
class LinkEnumerator : IEnumerator<T>
{
public void Dispose() { }
public bool HasMore()
{
return i + 1 < link.Length;
}
public bool ReachEnd()
{
return i == link.Length + 1;
}
public bool MoveNext()
{
if (HasMore())
{
i += 1;
return true;
}
i = link.Length + 1;
return false;
}
public T Current
{
get
{
if (ReachEnd())
throw new InvalidOperationException();
return link[i];
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public void Reset()
{
i = -1;
}
internal LinkEnumerator(ILink<T> link)
{
this.link = link;
i = -1;
}
private int i;
private ILink<T> link;
}
public IEnumerator<T> GetEnumerator()
{
return new LinkEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new LinkEnumerator(this);
}
public void Pin()
{
for (int i = 0, n = used; i < n; i++)
{
arr[i] = loadElem(i);
}
}
public void Unpin()
{
for (int i = 0, n = used; i < n; i++)
{
IPersistent elem = arr[i];
if (elem != null && !elem.IsRaw() && elem.IsPersistent())
arr[i] = new PersistentStub(elem.Database, elem.Oid);
}
}
private T loadElem(int i)
{
IPersistent elem = arr[i];
if (elem != null && elem.IsRaw())
elem = ((DatabaseImpl)elem.Database).lookupObject(elem.Oid, null);
return (T)elem;
}
public void SetOwner(IPersistent owner)
{
this.owner = owner;
}
internal LinkImpl()
{
}
internal LinkImpl(int initSize)
{
arr = new IPersistent[initSize];
}
internal LinkImpl(IPersistent[] arr, IPersistent owner)
{
this.arr = arr;
this.owner = owner;
used = arr.Length;
}
IPersistent[] arr;
int used;
[NonSerialized()]
IPersistent owner;
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace SharedHeaders
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BatchAccountOperations operations.
/// </summary>
internal partial class BatchAccountOperations : IServiceOperations<BatchManagementDummyClient>, IBatchAccountOperations
{
/// <summary>
/// Initializes a new instance of the BatchAccountOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BatchAccountOperations(BatchManagementDummyClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the BatchManagementDummyClient
/// </summary>
public BatchManagementDummyClient Client { get; private set; }
/// <summary>
/// Creates a new Batch account with the specified parameters. Existing
/// accounts cannot be updated with this API and should instead be updated with
/// the Update Batch Account API.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// A name for the Batch account which must be unique within the region. Batch
/// account names must be between 3 and 24 characters in length and must use
/// only numbers and lowercase letters. This name is used as part of the DNS
/// name that is used to access the Batch service in the region in which the
/// account is created. For example:
/// http://accountname.region.batch.azure.com/.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account creation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<BatchAccount,RetryHeader>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<BatchAccount,RetryHeader> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates the properties of an existing Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account update.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<BatchAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
object _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<object>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<BatchAccount>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchAccount>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationHeaderResponse<RetryHeader>> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationHeaderResponse<RetryHeader> _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, accountName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets information about the specified Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<BatchAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
object _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<object>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<BatchAccount>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchAccount>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a new Batch account with the specified parameters. Existing
/// accounts cannot be updated with this API and should instead be updated with
/// the Update Batch Account API.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// A name for the Batch account which must be unique within the region. Batch
/// account names must be between 3 and 24 characters in length and must use
/// only numbers and lowercase letters. This name is used as part of the DNS
/// name that is used to access the Batch service in the region in which the
/// account is created. For example:
/// http://accountname.region.batch.azure.com/.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account creation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<BatchAccount,RetryHeader>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
object _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<object>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<BatchAccount,RetryHeader>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BatchAccount>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<RetryHeader>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationHeaderResponse<RetryHeader>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
object _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<object>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationHeaderResponse<RetryHeader>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<RetryHeader>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright 2016 Jacob Trimble
//
// 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.Diagnostics;
using System.Reflection;
using ModMaker.Lua.Parser.Items;
namespace ModMaker.Lua.Runtime.LuaValues {
/// <summary>
/// Defines a base class for the standard LuaValue's. This uses the visitor pattern to pick the
/// correct function to call. This is the base type for all LuaValue's, for user-defined types,
/// see LuaUserData<T>.
/// </summary>
public abstract class LuaValueBase : ILuaValue, ILuaValueVisitor {
// TODO: Handle accessibility.
public virtual bool IsTrue { get { return true; } }
public abstract LuaValueType ValueType { get; }
/// <summary>
/// Creates a new LuaValue object wrapping the given value.
/// </summary>
/// <param name="value">The value to wrap.</param>
/// <returns>A new LuaValue object.</returns>
public static ILuaValue CreateValue(object value) {
if (value == null) {
return LuaNil.Nil;
}
if (value is ILuaValue luaValue) {
return luaValue;
}
if (value is Delegate delegate_) {
return new LuaOverloadFunction(
delegate_.Method.Name, new[] { delegate_.Method }, new[] { delegate_.Target });
}
bool? boolValue = value as bool?;
if (boolValue == true) {
return LuaBoolean.True;
} else if (boolValue == false) {
return LuaBoolean.False;
}
if (value is Type type) {
return new LuaType(type);
} else if (value is string stringValue) {
return new LuaString(stringValue);
} else if (value.GetType().IsPrimitive) {
return LuaNumber.Create(Convert.ToDouble(value));
} else {
return (ILuaValue)Activator.CreateInstance(
typeof(LuaUserData<>).MakeGenericType(value.GetType()), value);
}
}
public abstract bool Equals(ILuaValue other);
public override bool Equals(object obj) {
return obj is ILuaValue value && Equals(value);
}
public virtual int CompareTo(ILuaValue other) {
if (Equals(other)) {
return 0;
} else {
throw new InvalidOperationException(Errors.CannotArithmetic(ValueType));
}
}
public override int GetHashCode() {
return base.GetHashCode();
}
public virtual object GetValue() {
return this;
}
public virtual double? AsDouble() {
return null;
}
public virtual T As<T>() {
if (typeof(T).IsAssignableFrom(GetType())) {
return (T)(object)this;
}
object value = GetValue();
if (value == null) {
bool isNullable = typeof(T).IsGenericType &&
typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
if (typeof(T).IsValueType && !isNullable) {
throw new InvalidCastException(string.Format(Resources.BadCast, "null", typeof(T)));
} else {
return (T)value;
}
}
if (OverloadSelector.TypesCompatible(value.GetType(), typeof(T), out MethodInfo m)) {
// Cast the object if needed.
if (m != null) {
value = Helpers.DynamicInvoke(m, null, new[] { value });
}
return (T)value;
} else {
throw new InvalidCastException(string.Format(Resources.BadCast, value.GetType(),
typeof(T)));
}
}
public virtual ILuaValue GetIndex(ILuaValue index) {
throw new InvalidOperationException(Errors.CannotIndex(this.ValueType));
}
public virtual void SetIndex(ILuaValue index, ILuaValue value) {
throw new InvalidOperationException(Errors.CannotIndex(this.ValueType));
}
public virtual LuaMultiValue Invoke(ILuaValue self, bool memberCall, LuaMultiValue args) {
throw new InvalidOperationException(Errors.CannotCall(ValueType));
}
public abstract ILuaValue Arithmetic(BinaryOperationType type, ILuaValue other);
/// <summary>
/// Defines basic arithmetic for derived classes. This returns a non-null value when default,
/// or null if it is a visitor. This throws if not a visitor.
/// </summary>
/// <param name="type">The type of operation to perform.</param>
/// <param name="other">The other value to use.</param>
/// <returns>The result of the operation.</returns>
/// <exception cref="System.InvalidOperationException">
/// If the operation cannot be performed with the given values.
/// </exception>
/// <exception cref="System.InvalidArgumentException">
/// If the argument is an invalid value.
/// </exception>
protected ILuaValue _arithmeticBase(BinaryOperationType type, ILuaValue other) {
// Attempt to use a meta-method.
var ret = _attemptMetamethod(type, this, other);
if (ret != null) {
return ret;
}
// Do some default operations.
ret = _defaultArithmetic(type, other);
if (ret != null) {
return ret;
}
// If the other is not a visitor, throw.
if (!(other is ILuaValueVisitor)) {
throw new InvalidOperationException(Errors.CannotArithmetic(ValueType));
} else {
return null;
}
}
/// <summary>
/// Performs some default arithmetic like comparisons and returns the result. Returns null if
/// there is no default.
/// </summary>
/// <param name="type">The type of operation to perform.</param>
/// <param name="other">The other value to use.</param>
/// <returns>The result of the operation.</returns>
private ILuaValue _defaultArithmetic(BinaryOperationType type, ILuaValue other) {
switch (type) {
case BinaryOperationType.Concat:
return new LuaString(this.ToString() + other.ToString());
case BinaryOperationType.Gt:
return LuaBoolean.Create(CompareTo(other) > 0);
case BinaryOperationType.Lt:
return LuaBoolean.Create(CompareTo(other) < 0);
case BinaryOperationType.Gte:
return LuaBoolean.Create(CompareTo(other) >= 0);
case BinaryOperationType.Lte:
return LuaBoolean.Create(CompareTo(other) <= 0);
case BinaryOperationType.Equals:
return LuaBoolean.Create(Equals(other));
case BinaryOperationType.NotEquals:
return LuaBoolean.Create(!Equals(other));
case BinaryOperationType.And:
return !IsTrue ? this : other;
case BinaryOperationType.Or:
return IsTrue ? this : other;
default:
return null;
}
}
/// <summary>
/// Attempts to invoke a meta-method and returns the result.
/// </summary>
/// <param name="type">The type of operation.</param>
/// <param name="other">The other value.</param>
/// <returns>The result of the meta-method, or null if not found.</returns>
internal static ILuaValue _attemptMetamethod(BinaryOperationType type, ILuaValue self,
ILuaValue other) {
if (type == BinaryOperationType.And || type == BinaryOperationType.Or) {
return null;
}
// Search the first object.
ILuaValue ret = null;
var self2 = self as ILuaTable;
if (self2 != null && self2.MetaTable != null) {
var t = self2.MetaTable.GetItemRaw(LuaString._metamethods[type]);
if (t != null) {
ret = t.Invoke(LuaNil.Nil, false, new LuaMultiValue(self, other));
} else if (type == BinaryOperationType.Lte || type == BinaryOperationType.Gt) {
t = self2.MetaTable.GetItemRaw(LuaString._metamethods[BinaryOperationType.Lt]);
if (t != null) {
ret = t.Invoke(LuaNil.Nil, false, new LuaMultiValue(other, self)).Not();
}
}
}
// Search the second object.
var other2 = other as ILuaTable;
if (ret == null && other2 != null && other2.MetaTable != null) {
var t = other2.MetaTable.GetItemRaw(LuaString._metamethods[type]);
if (t != null) {
ret = t.Invoke(LuaNil.Nil, true, new LuaMultiValue(self, other));
} else if (type == BinaryOperationType.Lte || type == BinaryOperationType.Gt) {
t = other2.MetaTable.GetItemRaw(LuaString._metamethods[BinaryOperationType.Lt]);
if (t != null) {
ret = t.Invoke(LuaNil.Nil, true, new LuaMultiValue(other, self)).Not();
}
}
}
// Fix the arguments for comparisons.
if (ret != null) {
ret = ret.Single();
switch (type) {
case BinaryOperationType.Gt:
case BinaryOperationType.Gte:
case BinaryOperationType.NotEquals:
ret = LuaBoolean.Create(!ret.IsTrue);
break;
case BinaryOperationType.Equals:
case BinaryOperationType.Lt:
case BinaryOperationType.Lte:
ret = LuaBoolean.Create(ret.IsTrue);
break;
}
}
return ret;
}
public ILuaValue Not() {
return LuaBoolean.Create(!IsTrue);
}
public virtual ILuaValue Minus() {
throw new InvalidOperationException(Errors.CannotArithmetic(ValueType));
}
public virtual ILuaValue Length() {
throw new InvalidOperationException(Errors.CannotArithmetic(ValueType));
}
public virtual ILuaValue RawLength() {
return Length();
}
public virtual ILuaValue Single() {
return this;
}
public virtual ILuaValue Arithmetic(BinaryOperationType type, LuaBoolean self) {
throw new InvalidOperationException(Errors.CannotArithmetic(LuaValueType.Bool));
}
public virtual ILuaValue Arithmetic(BinaryOperationType type, LuaClass self) {
throw new InvalidOperationException(Errors.CannotArithmetic(LuaValueType.UserData));
}
public virtual ILuaValue Arithmetic(BinaryOperationType type, LuaFunction self) {
throw new InvalidOperationException(Errors.CannotArithmetic(LuaValueType.Function));
}
public virtual ILuaValue Arithmetic(BinaryOperationType type, LuaNil self) {
throw new InvalidOperationException(Errors.CannotArithmetic(LuaValueType.Nil));
}
public virtual ILuaValue Arithmetic(BinaryOperationType type, LuaNumber self) {
throw new InvalidOperationException(Errors.CannotArithmetic(this.ValueType));
}
public virtual ILuaValue Arithmetic(BinaryOperationType type, LuaString self) {
throw new InvalidOperationException(Errors.CannotArithmetic(LuaValueType.String));
}
public virtual ILuaValue Arithmetic(BinaryOperationType type, LuaTable self) {
var ret = _attemptMetamethod(type, self, this);
if (ret != null) {
return ret;
}
throw new InvalidOperationException(Errors.CannotArithmetic(LuaValueType.Table));
}
public virtual ILuaValue Arithmetic(BinaryOperationType type, LuaThread self) {
var ret = _attemptMetamethod(type, self, this);
if (ret != null) {
return ret;
}
throw new InvalidOperationException(Errors.CannotArithmetic(LuaValueType.Thread));
}
public abstract ILuaValue Arithmetic<T>(BinaryOperationType type, LuaUserData<T> self);
}
/// <summary>
/// A type-safe wrapper for a LuaValue.
/// </summary>
/// <typeparam name="T">The type of data stored.</typeparam>
[DebuggerDisplay("LuaValue {Value}")]
public abstract class LuaValueBase<T> : LuaValueBase, ILuaValue<T> {
/// <summary>
/// Creates a new LuaValueBase that wraps the given value.
/// </summary>
/// <param name="value">The value this will wrap.</param>
public LuaValueBase(T value) {
Value = value;
}
public T Value { get; }
public override object GetValue() {
return Value;
}
public override bool Equals(ILuaValue other) {
return other != null && other.GetType() == GetType() &&
Equals(Value, ((LuaValueBase<T>)other).Value);
}
public override bool Equals(object obj) {
if (obj is ILuaValue value) {
return Equals(value);
} else {
return Equals(Value, obj);
}
}
public override int CompareTo(ILuaValue other) {
if (other is LuaValueBase<T> temp && other.GetType() == GetType()) {
var comp = Comparer<T>.Default;
return comp.Compare(Value, temp.Value);
}
return base.CompareTo(other);
}
public override int GetHashCode() {
return Value == null ? 0 : Value.GetHashCode();
}
public override string ToString() {
if (Value == null) {
return "nil";
} else {
return Value.ToString();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.ServiceAuth;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Avatar
{
public class AvatarServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAvatarService m_AvatarService;
public AvatarServerPostHandler(IAvatarService service, IServiceAuth auth) :
base("POST", "/avatar", auth)
{
m_AvatarService = service;
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
switch (method)
{
case "getavatar":
return GetAvatar(request);
case "setavatar":
return SetAvatar(request);
case "resetavatar":
return ResetAvatar(request);
case "setitems":
return SetItems(request);
case "removeitems":
return RemoveItems(request);
}
m_log.DebugFormat("[AVATAR HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.Debug("[AVATAR HANDLER]: Exception {0}" + e);
}
return FailureResult();
}
byte[] GetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (UUID.TryParse(request["UserID"].ToString(), out user))
{
AvatarData avatar = m_AvatarService.GetAvatar(user);
if (avatar == null)
return FailureResult();
Dictionary<string, object> result = new Dictionary<string, object>();
if (avatar == null)
result["result"] = "null";
else
result["result"] = avatar.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
return FailureResult();
}
byte[] SetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
RemoveRequestParamsNotForStorage(request);
AvatarData avatar = new AvatarData(request);
if (m_AvatarService.SetAvatar(user, avatar))
return SuccessResult();
return FailureResult();
}
byte[] ResetAvatar(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
if (!request.ContainsKey("UserID"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
RemoveRequestParamsNotForStorage(request);
if (m_AvatarService.ResetAvatar(user))
return SuccessResult();
return FailureResult();
}
/// <summary>
/// Remove parameters that were used to invoke the method and should not in themselves be persisted.
/// </summary>
/// <param name='request'></param>
private void RemoveRequestParamsNotForStorage(Dictionary<string, object> request)
{
request.Remove("VERSIONMAX");
request.Remove("VERSIONMIN");
request.Remove("METHOD");
request.Remove("UserID");
}
byte[] SetItems(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
string[] names, values;
if (!request.ContainsKey("UserID") || !request.ContainsKey("Names") || !request.ContainsKey("Values"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
if (!(request["Names"] is List<string> || request["Values"] is List<string>))
return FailureResult();
RemoveRequestParamsNotForStorage(request);
List<string> _names = (List<string>)request["Names"];
names = _names.ToArray();
List<string> _values = (List<string>)request["Values"];
values = _values.ToArray();
if (m_AvatarService.SetItems(user, names, values))
return SuccessResult();
return FailureResult();
}
byte[] RemoveItems(Dictionary<string, object> request)
{
UUID user = UUID.Zero;
string[] names;
if (!request.ContainsKey("UserID") || !request.ContainsKey("Names"))
return FailureResult();
if (!UUID.TryParse(request["UserID"].ToString(), out user))
return FailureResult();
if (!(request["Names"] is List<string>))
return FailureResult();
List<string> _names = (List<string>)request["Names"];
names = _names.ToArray();
if (m_AvatarService.RemoveItems(user, names))
return SuccessResult();
return FailureResult();
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Compute.Fluent.Disk.Definition
{
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
/// <summary>
/// The stage of the managed disk definition allowing to choose Linux OS source.
/// </summary>
public interface IWithLinuxDiskSource
{
/// <summary>
/// Specifies the source Linux OS managed disk.
/// </summary>
/// <param name="sourceDiskId">Source managed disk resource ID.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithLinuxFromDisk(string sourceDiskId);
/// <summary>
/// Specifies the source Linux OS managed disk.
/// </summary>
/// <param name="sourceDisk">Source managed disk.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithLinuxFromDisk(IDisk sourceDisk);
/// <summary>
/// Specifies the source Linux OS managed snapshot.
/// </summary>
/// <param name="sourceSnapshotId">Snapshot resource ID.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithLinuxFromSnapshot(string sourceSnapshotId);
/// <summary>
/// Specifies the source Linux OS managed snapshot.
/// </summary>
/// <param name="sourceSnapshot">Source snapshot.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithLinuxFromSnapshot(ISnapshot sourceSnapshot);
/// <summary>
/// Specifies the source specialized or generalized Linux OS VHD.
/// </summary>
/// <param name="vhdUrl">The source VHD URL.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithLinuxFromVhd(string vhdUrl);
}
/// <summary>
/// The first stage of a managed disk definition.
/// </summary>
public interface IBlank :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithRegion<Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithGroup>
{
}
/// <summary>
/// The stage of the managed disk definition allowing to choose source data disk VHD.
/// </summary>
public interface IWithDataDiskFromVhd
{
/// <summary>
/// Specifies the source data VHD.
/// </summary>
/// <param name="vhdUrl">The source VHD URL.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromVhd(string vhdUrl);
}
/// <summary>
/// The stage of a managed disk definition allowing to choose a Windows OS source.
/// </summary>
public interface IWithWindowsDiskSource
{
/// <summary>
/// Specifies a source Windows OS managed disk.
/// </summary>
/// <param name="sourceDiskId">Source managed disk resource ID.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithWindowsFromDisk(string sourceDiskId);
/// <summary>
/// Specifies a source Windows OS managed disk.
/// </summary>
/// <param name="sourceDisk">Source managed disk.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithWindowsFromDisk(IDisk sourceDisk);
/// <summary>
/// Specifies a source Windows OS managed snapshot.
/// </summary>
/// <param name="sourceSnapshotId">Snapshot resource ID.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithWindowsFromSnapshot(string sourceSnapshotId);
/// <summary>
/// Specifies a source Windows OS managed snapshot.
/// </summary>
/// <param name="sourceSnapshot">Source snapshot.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithWindowsFromSnapshot(ISnapshot sourceSnapshot);
/// <summary>
/// Specifies a source specialized or generalized Windows OS VHD.
/// </summary>
/// <param name="vhdUrl">The source VHD URL.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithWindowsFromVhd(string vhdUrl);
}
/// <summary>
/// The stage of the managed disk definition allowing to choose source data disk image.
/// </summary>
public interface IWithDataDiskFromImage
{
/// <summary>
/// Specifies the ID of an image containing source data disk image.
/// </summary>
/// <param name="imageId">Image resource ID.</param>
/// <param name="diskLun">LUN of the disk image.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromImage(string imageId, int diskLun);
/// <summary>
/// Specifies an image containing source data disk image.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="diskLun">LUN of the disk image.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromImage(IVirtualMachineImage image, int diskLun);
/// <summary>
/// Specifies a custom image containing a source data disk image.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="diskLun">LUN of the disk image.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromImage(IVirtualMachineCustomImage image, int diskLun);
}
/// <summary>
/// The stage of the managed disk definition allowing to choose managed disk containing data.
/// </summary>
public interface IWithDataDiskFromDisk
{
/// <summary>
/// Specifies the ID of source data managed disk.
/// </summary>
/// <param name="managedDiskId">Source managed disk resource ID.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromDisk(string managedDiskId);
/// <summary>
/// Specifies the source data managed disk.
/// </summary>
/// <param name="managedDisk">Source managed disk.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromDisk(IDisk managedDisk);
}
/// <summary>
/// The stage of the managed disk definition that specifies it hold data.
/// </summary>
public interface IWithData
{
/// <summary>
/// Begins definition of managed disk containing data.
/// </summary>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDataDiskSource WithData();
}
/// <summary>
/// The stage of a managed disk definition allowing to choose OS source or data source.
/// </summary>
public interface IWithDiskSource :
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithWindowsDiskSource,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithLinuxDiskSource,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithData
{
}
/// <summary>
/// The stage of the managed disk definition allowing to create the disk or optionally specify size.
/// </summary>
public interface IWithCreateAndSize :
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreate
{
/// <summary>
/// Specifies the disk size.
/// </summary>
/// <param name="sizeInGB">The disk size in GB.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize WithSizeInGB(int sizeInGB);
}
/// <summary>
/// The stage of the managed disk definition allowing to choose account type.
/// </summary>
public interface IWithSku
{
/// <summary>
/// Specifies the SKU.
/// </summary>
/// <param name="sku">The SKU.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreate WithSku(DiskSkuTypes sku);
}
/// <summary>
/// The stage of the managed disk definition allowing to choose data source.
/// </summary>
public interface IWithDataDiskSource :
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDataDiskFromVhd,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDataDiskFromDisk,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDataDiskFromSnapshot
{
/// <summary>
/// Specifies the disk size for an empty disk.
/// </summary>
/// <param name="sizeInGB">The disk size in GB.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreate WithSizeInGB(int sizeInGB);
}
/// <summary>
/// The stage of the managed disk definition allowing to specify availability zone.
/// </summary>
public interface IWithAvailabilityZone :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta
{
/// <summary>
/// Specifies the availability zone for the managed disk.
/// </summary>
/// <param name="zoneId">The zone identifier.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreate WithAvailabilityZone(AvailabilityZoneId zoneId);
}
/// <summary>
/// The stage of a managed disk definition allowing to specify the resource group.
/// </summary>
public interface IWithGroup :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.GroupableResource.Definition.IWithGroup<Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDiskSource>
{
}
/// <summary>
/// The stage of the managed disk definition allowing to choose source operating system image.
/// </summary>
public interface IWithOSDiskFromImage
{
/// <summary>
/// Specifies the ID of an image containing the operating system.
/// </summary>
/// <param name="imageId">Image resource ID.</param>
/// <param name="osType">Operating system type.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromImage(string imageId, OperatingSystemTypes osType);
/// <summary>
/// Specifies an image containing the operating system.
/// </summary>
/// <param name="image">The image.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromImage(IVirtualMachineImage image);
/// <summary>
/// Specifies a custom image containing the operating system.
/// </summary>
/// <param name="image">The image.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromImage(IVirtualMachineCustomImage image);
}
/// <summary>
/// The entirety of the managed disk definition.
/// </summary>
public interface IDefinition :
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IBlank,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithGroup,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDiskSource,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithWindowsDiskSource,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithLinuxDiskSource,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithData,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDataDiskSource,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDataDiskFromVhd,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDataDiskFromDisk,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithDataDiskFromSnapshot,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreate
{
}
/// <summary>
/// The stage of the managed disk definition allowing to choose managed snapshot containing data.
/// </summary>
public interface IWithDataDiskFromSnapshot
{
/// <summary>
/// Specifies the source data managed snapshot.
/// </summary>
/// <param name="snapshotId">Snapshot resource ID.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromSnapshot(string snapshotId);
/// <summary>
/// Specifies the source data managed snapshot.
/// </summary>
/// <param name="snapshot">Snapshot resource.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreateAndSize FromSnapshot(ISnapshot snapshot);
}
/// <summary>
/// The stage of the definition which contains all the minimum required inputs for
/// the resource to be created, but also allows
/// for any other optional settings to be specified.
/// </summary>
public interface IWithCreate :
Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.Compute.Fluent.IDisk>,
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithTags<Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithCreate>,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithSku,
Microsoft.Azure.Management.Compute.Fluent.Disk.Definition.IWithAvailabilityZone
{
}
}
| |
// Copyright 2017, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api;
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Logging.V2;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Logging.V2.Snippets
{
public class GeneratedLoggingServiceV2ClientSnippets
{
public async Task DeleteLogAsync()
{
// Snippet: DeleteLogAsync(LogNameOneof,CallSettings)
// Additional: DeleteLogAsync(LogNameOneof,CancellationToken)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]"));
// Make the request
await loggingServiceV2Client.DeleteLogAsync(logName);
// End snippet
}
public void DeleteLog()
{
// Snippet: DeleteLog(LogNameOneof,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]"));
// Make the request
loggingServiceV2Client.DeleteLog(logName);
// End snippet
}
public async Task DeleteLogAsync_RequestObject()
{
// Snippet: DeleteLogAsync(DeleteLogRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
DeleteLogRequest request = new DeleteLogRequest
{
LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")),
};
// Make the request
await loggingServiceV2Client.DeleteLogAsync(request);
// End snippet
}
public void DeleteLog_RequestObject()
{
// Snippet: DeleteLog(DeleteLogRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
DeleteLogRequest request = new DeleteLogRequest
{
LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")),
};
// Make the request
loggingServiceV2Client.DeleteLog(request);
// End snippet
}
public async Task WriteLogEntriesAsync()
{
// Snippet: WriteLogEntriesAsync(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CallSettings)
// Additional: WriteLogEntriesAsync(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CancellationToken)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]"));
MonitoredResource resource = new MonitoredResource();
IDictionary<string, string> labels = new Dictionary<string, string>();
IEnumerable<LogEntry> entries = new List<LogEntry>();
// Make the request
WriteLogEntriesResponse response = await loggingServiceV2Client.WriteLogEntriesAsync(logName, resource, labels, entries);
// End snippet
}
public void WriteLogEntries()
{
// Snippet: WriteLogEntries(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]"));
MonitoredResource resource = new MonitoredResource();
IDictionary<string, string> labels = new Dictionary<string, string>();
IEnumerable<LogEntry> entries = new List<LogEntry>();
// Make the request
WriteLogEntriesResponse response = loggingServiceV2Client.WriteLogEntries(logName, resource, labels, entries);
// End snippet
}
public async Task WriteLogEntriesAsync_RequestObject()
{
// Snippet: WriteLogEntriesAsync(WriteLogEntriesRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
WriteLogEntriesRequest request = new WriteLogEntriesRequest
{
Entries = { },
};
// Make the request
WriteLogEntriesResponse response = await loggingServiceV2Client.WriteLogEntriesAsync(request);
// End snippet
}
public void WriteLogEntries_RequestObject()
{
// Snippet: WriteLogEntries(WriteLogEntriesRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
WriteLogEntriesRequest request = new WriteLogEntriesRequest
{
Entries = { },
};
// Make the request
WriteLogEntriesResponse response = loggingServiceV2Client.WriteLogEntries(request);
// End snippet
}
public async Task ListLogEntriesAsync()
{
// Snippet: ListLogEntriesAsync(IEnumerable<string>,string,string,string,int?,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
IEnumerable<string> resourceNames = new List<string>();
string filter = "";
string orderBy = "";
// Make the request
PagedAsyncEnumerable<ListLogEntriesResponse, LogEntry> response =
loggingServiceV2Client.ListLogEntriesAsync(resourceNames, filter, orderBy);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((LogEntry item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListLogEntriesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogEntry item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogEntry> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogEntry item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListLogEntries()
{
// Snippet: ListLogEntries(IEnumerable<string>,string,string,string,int?,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
IEnumerable<string> resourceNames = new List<string>();
string filter = "";
string orderBy = "";
// Make the request
PagedEnumerable<ListLogEntriesResponse, LogEntry> response =
loggingServiceV2Client.ListLogEntries(resourceNames, filter, orderBy);
// Iterate over all response items, lazily performing RPCs as required
foreach (LogEntry item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListLogEntriesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogEntry item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogEntry> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogEntry item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task ListLogEntriesAsync_RequestObject()
{
// Snippet: ListLogEntriesAsync(ListLogEntriesRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
ListLogEntriesRequest request = new ListLogEntriesRequest
{
ResourceNames = { },
};
// Make the request
PagedAsyncEnumerable<ListLogEntriesResponse, LogEntry> response =
loggingServiceV2Client.ListLogEntriesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((LogEntry item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListLogEntriesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogEntry item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogEntry> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogEntry item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListLogEntries_RequestObject()
{
// Snippet: ListLogEntries(ListLogEntriesRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
ListLogEntriesRequest request = new ListLogEntriesRequest
{
ResourceNames = { },
};
// Make the request
PagedEnumerable<ListLogEntriesResponse, LogEntry> response =
loggingServiceV2Client.ListLogEntries(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (LogEntry item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListLogEntriesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (LogEntry item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<LogEntry> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (LogEntry item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task ListMonitoredResourceDescriptorsAsync_RequestObject()
{
// Snippet: ListMonitoredResourceDescriptorsAsync(ListMonitoredResourceDescriptorsRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest();
// Make the request
PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
loggingServiceV2Client.ListMonitoredResourceDescriptorsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MonitoredResourceDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMonitoredResourceDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListMonitoredResourceDescriptors_RequestObject()
{
// Snippet: ListMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest();
// Make the request
PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
loggingServiceV2Client.ListMonitoredResourceDescriptors(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (MonitoredResourceDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task ListLogsAsync()
{
// Snippet: ListLogsAsync(ParentNameOneof,string,int?,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]"));
// Make the request
PagedAsyncEnumerable<ListLogsResponse, string> response =
loggingServiceV2Client.ListLogsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((string item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListLogsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (string item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<string> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (string item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListLogs()
{
// Snippet: ListLogs(ParentNameOneof,string,int?,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]"));
// Make the request
PagedEnumerable<ListLogsResponse, string> response =
loggingServiceV2Client.ListLogs(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (string item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListLogsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (string item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<string> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (string item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task ListLogsAsync_RequestObject()
{
// Snippet: ListLogsAsync(ListLogsRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync();
// Initialize request argument(s)
ListLogsRequest request = new ListLogsRequest
{
ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")),
};
// Make the request
PagedAsyncEnumerable<ListLogsResponse, string> response =
loggingServiceV2Client.ListLogsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((string item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListLogsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (string item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<string> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (string item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListLogs_RequestObject()
{
// Snippet: ListLogs(ListLogsRequest,CallSettings)
// Create client
LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
// Initialize request argument(s)
ListLogsRequest request = new ListLogsRequest
{
ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")),
};
// Make the request
PagedEnumerable<ListLogsResponse, string> response =
loggingServiceV2Client.ListLogs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (string item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListLogsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (string item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<string> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (string item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Adxstudio.Xrm.Partner;
using Adxstudio.Xrm.Web.UI.JsonConfiguration;
using Adxstudio.Xrm.Web.UI.WebForms;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Newtonsoft.Json;
using GridMetadata = Adxstudio.Xrm.Web.UI.JsonConfiguration.GridMetadata;
namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView
{
/// <summary>
/// Metadata derived from the form XML pertaining to the specific cell.
/// </summary>
public class FormXmlCellMetadata : Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView.FormXmlCellMetadata
{
private static readonly Guid QuickformClassId = new Guid("5C5600E0-1D6E-4205-A272-BE80DA87FD42");
private readonly AttributeMetadata _attributeMetadata;
private readonly string _controlID;
private readonly string _dataFieldName;
private readonly bool _isNotesControl;
private readonly bool _isActivityTimelineControl;
private readonly bool _isWebResource;
private readonly string _webResourceAltText;
private readonly bool _webResourceBorder;
private readonly string _webResourceData;
private readonly int? _webResourceHeight;
private readonly string _webResourceHorizontalAlignment;
private readonly bool _webResourceIsHtml;
private readonly bool _webResourceIsImage;
private readonly bool _webResourceIsSilverlight;
private readonly bool _webResourcePassParameters;
private readonly string _webResourceScrolling;
private readonly bool _webResourceSecurity;
private readonly string _webResourceSizeType;
private readonly string _webResourceUrl;
private readonly string _webResourceVerticalAlignment;
private readonly int? _webResourceWidth;
private readonly Guid _classID;
private readonly string _validationText;
private readonly WebFormMetadata.ControlStyle _controlStyle;
private readonly string _geolocationValidatorErrorMessage;
private readonly Guid _lookupViewID;
private readonly bool _ignoreDefaultValue;
private readonly bool _addDescription;
private readonly string _description;
private readonly WebFormMetadata.DescriptionPosition _descriptionPosition;
private readonly bool _webformForcefieldIsRequired;
private readonly string _requiredFieldValidationErrorMessage;
private readonly string _validationRegularExpression;
private readonly string _validationRegularExpressionErrorMessage;
private readonly string _validationErrorMessage;
private readonly string _rangeValidationErrorMessage;
private readonly string _constantSumValidationErrorMessage;
private readonly string _rankOrderNoTiesValidationErrorMessage;
private readonly string _multipleChoiceValidationErrorMessage;
private readonly string _groupName;
private readonly string[] _constantSumAttributeNames;
private readonly bool _randomizeOptionSetValues;
private readonly int _minMultipleChoiceSelectedCount;
private readonly int _maxMultipleChoiceSelectedCount;
private readonly bool _forceAllFieldsRequired;
private readonly bool _enableValidationSummaryLinks;
private readonly string _validationSummaryLinkText;
private readonly int _constantSumMinimumTotal;
private readonly int _constantSumMaximumTotal;
private readonly string _cssClass;
private readonly Dictionary<string, string> _messages;
private readonly string _viewID;
private readonly string _viewRelationshipName;
private readonly string _viewTargetEntityType;
private readonly bool _viewEnableQuickFind;
private readonly bool _viewEnableViewPicker;
private readonly string _viewIds;
private readonly int? _viewRecordsPerPage;
private readonly bool _isSharePointDocuments;
private readonly bool _isSubgrid;
private readonly string _targetEntityName;
private readonly string _targetEntityPrimaryKeyName;
private readonly string _targetEntityPrimaryAttributeName;
private readonly GridMetadata _subgridSettings;
private readonly JsonConfiguration.NotesMetadata _notesSettings;
private readonly JsonConfiguration.TimelineMetadata _timelineSettings;
private readonly int? _notesPageSize;
private readonly SharePointGridMetadata _sharePointSettings;
private readonly int? _sharePointGridPageSize;
private readonly bool _lookupDisableQuickFind;
private readonly bool _lookupDisableViewPicker;
private readonly bool _lookupAllowFilterOff;
private readonly string _lookupAvailableViewIds;
private readonly string _lookupFilterRelationshipName;
private readonly string _lookupDependentAttributeName;
private readonly string _lookupDependentAttributeType;
private readonly OptionMetadataCollection _stateOptionSetOptions;
private readonly OptionMetadataCollection _statusOptionSetOptions;
private readonly bool _labelNotAssociated;
private readonly bool _isQuickForm;
private readonly CrmQuickForm _quickForm;
private readonly Guid? _lookupReferenceEntityFormId = null;
private readonly bool _isFullnameControl;
private readonly bool _isAddressCompositeControl;
/// <summary>
/// Default text displayed in the field's validator control.
/// </summary>
public readonly string DefaultValidationText = "*";
/// <summary>
/// Indicates if the control is read-only.
/// </summary>
public bool ReadOnly { get; set; }
/// <summary>
/// The control's label text.
/// </summary>
public new string Label { get; set; }
/// <summary>
/// The parent control so cell templates can access properties on the control.
/// </summary>
public WebControls.CrmEntityFormView FormView { get; set; }
/// <summary>
/// Custom Metadata derived from the entity form metadata for the specified cell.
/// </summary>
/// <param name="cellNode"></param>
/// <param name="entityMetadata"></param>
/// <param name="languageCode"></param>
/// <param name="toolTipEnabled"></param>
/// <param name="recommendedFieldsRequired"></param>
/// <param name="validationText"></param>
/// <param name="webFormMetadata"></param>
/// <param name="forceAllFieldsRequired"></param>
/// <param name="enableValidationSummaryLinks"></param>
/// <param name="validationSummaryLinkText"></param>
/// <param name="messages"> </param>
public FormXmlCellMetadata(XNode cellNode, EntityMetadata entityMetadata, int languageCode, bool? toolTipEnabled, bool? recommendedFieldsRequired, string validationText, IEnumerable<Entity> webFormMetadata, bool? forceAllFieldsRequired, bool? enableValidationSummaryLinks, string validationSummaryLinkText, Dictionary<string, string> messages, int baseOrganizationLanguageCode = 0)
: base(cellNode, entityMetadata, languageCode)
{
_targetEntityName = entityMetadata.LogicalName;
_targetEntityPrimaryKeyName = entityMetadata.PrimaryIdAttribute;
_targetEntityPrimaryAttributeName = entityMetadata.PrimaryNameAttribute;
_messages = messages ?? new Dictionary<string, string>();
_enableValidationSummaryLinks = enableValidationSummaryLinks ?? true;
_validationSummaryLinkText = string.IsNullOrWhiteSpace(validationSummaryLinkText) ? string.Empty : validationSummaryLinkText;
_forceAllFieldsRequired = forceAllFieldsRequired ?? false;
_stateOptionSetOptions = new OptionMetadataCollection();
_statusOptionSetOptions = new OptionMetadataCollection();
Label = base.Label;
if (string.IsNullOrWhiteSpace(Label))
{
string label;
cellNode.TryGetLanguageSpecificLabelValue(this.LanguageCode, out label, baseOrganizationLanguageCode);
Label = label;
}
if (!cellNode.TryGetAttributeValue("control", "id", out _controlID))
{
return;
}
string classIdString;
if (cellNode.TryGetAttributeValue("control", "classid", out classIdString))
{
_classID = new Guid(classIdString);
}
bool readOnly;
if (cellNode.TryGetBooleanAttributeValue("control", "disabled", out readOnly))
{
// Preserve any existing true value of Disabled.
ReadOnly = readOnly;
}
bool visible;
if (!cellNode.TryGetBooleanAttributeValue(".", "visible", out visible))
{
visible = true; // The control is visible by default.
}
Disabled = !visible; // if not visible then disabled
if (validationText != null) _validationText = validationText;
string defaultTabId;
cellNode.TryGetElementValue("control/parameters/DefaultTabId", out defaultTabId);
if (_controlID == "notescontrol" && (!string.IsNullOrEmpty(defaultTabId) && defaultTabId == "ActivitiesTab"))
{
_isActivityTimelineControl = true;
cellNode.TryGetIntegerAttributeValue(".", "rowspan", out _notesPageSize);
// The base class will disable this cell because there's no datafieldname.
// The notes control, however, cannot be disabled so we can just set disabled to false.
Disabled = false;
if (webFormMetadata != null)
{
var timelineWebFormMetadata = webFormMetadata.FirstOrDefault(wfm => wfm.GetAttributeValue<OptionSetValue>("adx_type") != null && wfm.GetAttributeValue<OptionSetValue>("adx_type").Value == 756150000);
if (timelineWebFormMetadata != null)
{
var timelineSettingsJson = timelineWebFormMetadata.GetAttributeValue<string>("adx_timeline_settings");
if (!string.IsNullOrWhiteSpace(timelineSettingsJson))
{
try
{
_timelineSettings = JsonConvert.DeserializeObject<JsonConfiguration.TimelineMetadata>(timelineSettingsJson,
new JsonSerializerSettings { ContractResolver = JsonConfigurationContractResolver.Instance, TypeNameHandling = TypeNameHandling.Objects, Binder = new ActionSerializationBinder() });
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("FormXmlCellMetadata Constructor {0}", e.ToString()));
}
}
}
}
}
else if (_controlID == "notescontrol")
{
_isNotesControl = true;
cellNode.TryGetIntegerAttributeValue(".", "rowspan", out _notesPageSize);
// The base class will disable this cell because there's no datafieldname.
// The notes control, however, cannot be disabled so we can just set disabled to false.
Disabled = false;
if (webFormMetadata != null)
{
var notesWebFormMetadata = webFormMetadata.FirstOrDefault(wfm => wfm.GetAttributeValue<OptionSetValue>("adx_type") != null && wfm.GetAttributeValue<OptionSetValue>("adx_type").Value == 100000005);
if (notesWebFormMetadata != null)
{
var notesSettingsJson = notesWebFormMetadata.GetAttributeValue<string>("adx_notes_settings");
if (!string.IsNullOrWhiteSpace(notesSettingsJson))
{
try
{
_notesSettings = JsonConvert.DeserializeObject<JsonConfiguration.NotesMetadata>(notesSettingsJson,
new JsonSerializerSettings { ContractResolver = JsonConfigurationContractResolver.Instance, TypeNameHandling = TypeNameHandling.Objects, Binder = new ActionSerializationBinder() });
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("FormXmlCellMetadata Constructor {0}", e.ToString()));
}
}
}
}
}
else if (_controlID.StartsWith("WebResource_"))
{
_isWebResource = true;
// HACK: There is no data in the formxml that tells us what the web resource type is,
// so we're using a very fragile logical deduction based on the parameters passed.
_webResourceIsHtml = cellNode.TryGetBooleanElementValue("control/parameters/Border", out _webResourceBorder);
_webResourceIsImage = cellNode.TryGetElementValue("control/parameters/HorizontalAlignment", out _webResourceHorizontalAlignment);
_webResourceIsSilverlight = cellNode.TryGetBooleanElementValue("control/parameters/PassParameters", out _webResourcePassParameters) && !_webResourceIsHtml;
cellNode.TryGetElementValue("control/parameters/AltText", out _webResourceAltText);
cellNode.TryGetElementValue("control/parameters/Data", out _webResourceData);
cellNode.TryGetIntegerElementValue("control/parameters/Height", out _webResourceHeight);
cellNode.TryGetElementValue("control/parameters/Scrolling", out _webResourceScrolling);
cellNode.TryGetBooleanElementValue("control/parameters/Security", out _webResourceSecurity);
cellNode.TryGetElementValue("control/parameters/SizeType", out _webResourceSizeType);
cellNode.TryGetElementValue("control/parameters/Url", out _webResourceUrl);
cellNode.TryGetElementValue("control/parameters/VerticalAlignment", out _webResourceVerticalAlignment);
cellNode.TryGetIntegerElementValue("control/parameters/Width", out _webResourceWidth);
}
else if (cellNode.TryGetElementValue("control/parameters/ViewId", out _viewID))
{
// The base class will disable this cell because there's no datafieldname.
// The subgrid control, however, cannot be disabled so we can just set disabled to false.
Disabled = false;
cellNode.TryGetElementValue("control/parameters/RelationshipName", out _viewRelationshipName);
cellNode.TryGetElementValue("control/parameters/TargetEntityType", out _viewTargetEntityType);
cellNode.TryGetBooleanElementValue("control/parameters/EnableQuickFind", out _viewEnableQuickFind);
cellNode.TryGetBooleanElementValue("control/parameters/EnableViewPicker", out _viewEnableViewPicker);
cellNode.TryGetIntegerElementValue("control/parameters/RecordsPerPage", out _viewRecordsPerPage);
cellNode.TryGetElementValue("control/parameters/ViewIds", out _viewIds);
if (_viewTargetEntityType == "sharepointdocumentlocation")
{
_isSharePointDocuments = true;
cellNode.TryGetIntegerAttributeValue(".", "rowspan", out _sharePointGridPageSize);
}
else
{
_isSubgrid = true;
}
if (_isSubgrid && webFormMetadata != null)
{
string subgridName;
if (cellNode.TryGetAttributeValue("control", "id", out subgridName))
{
var subgridWebFormMetadata = webFormMetadata.FirstOrDefault(wfm => wfm.GetAttributeValue<string>("adx_subgrid_name") == subgridName);
if (subgridWebFormMetadata != null)
{
var subgridSettingsJson = subgridWebFormMetadata.GetAttributeValue<string>("adx_subgrid_settings");
if (!string.IsNullOrWhiteSpace(subgridSettingsJson))
{
try
{
_subgridSettings = JsonConvert.DeserializeObject<GridMetadata>(subgridSettingsJson,
new JsonSerializerSettings
{
ContractResolver = JsonConfigurationContractResolver.Instance,
TypeNameHandling = TypeNameHandling.Objects,
Converters = new List<JsonConverter> { new GuidConverter() },
Binder = new ActionSerializationBinder(),
NullValueHandling = NullValueHandling.Ignore
});
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("FormXmlCellMetadata Constructor {0}", e.ToString()));
}
}
}
}
}
}
else if (_classID == QuickformClassId) // QuickForm
{
_isQuickForm = true;
cellNode.TryGetAttributeValue("control", "datafieldname", out _dataFieldName);
if (string.IsNullOrWhiteSpace(_dataFieldName))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "QuickForm XML is invalid. The attribute datafieldname value is missing or is null.");
return;
}
string quickFormsString;
cellNode.TryGetElementValue("control/parameters/QuickForms", out quickFormsString);
if (string.IsNullOrWhiteSpace(quickFormsString))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "QuickForm XML is invalid. The parameter QuickForms is missing or is null.");
return;
}
var quickFormsIdsXml = XDocument.Parse(quickFormsString);
var quickFormIdElements = quickFormsIdsXml.Descendants("QuickFormId");
var quickFormIds = new List<CrmQuickForm.QuickFormId>();
foreach (var quickFormIdElement in quickFormIdElements)
{
Guid quickFormId;
string quickFormIdString;
string entityName;
quickFormIdElement.TryGetAttributeValue(".", "entityname", out entityName);
quickFormIdElement.TryGetElementValue(".", out quickFormIdString);
if (string.IsNullOrWhiteSpace(entityName))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "QuickForm XML is invalid. The element QuickFormId is missing or is null.");
continue;
}
if (string.IsNullOrWhiteSpace(quickFormIdString))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "QuickForm XML is invalid. The element QuickFormId is missing or is null.");
continue;
}
if (!Guid.TryParse(quickFormIdString, out quickFormId))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "QuickForm XML is invalid. The element QuickFormId is not a valid Guid.");
continue;
}
quickFormIds.Add(new CrmQuickForm.QuickFormId(entityName, quickFormId));
}
if (!quickFormIds.Any()) return;
_quickForm = new CrmQuickForm(_dataFieldName, quickFormIds.ToArray());
}
else if (_controlID == "fullname")
{
_isFullnameControl = true;
}
else if (this._controlID.StartsWith("address") && this._controlID.EndsWith("composite"))
{
this._isAddressCompositeControl = true;
}
else
{
if (!cellNode.TryGetAttributeValue("control", "datafieldname", out _dataFieldName))
{
return;
}
if (webFormMetadata != null)
{
webFormMetadata = webFormMetadata.ToList();
var attributeWebFormMetadata =
webFormMetadata.FirstOrDefault(wfm => wfm.GetAttributeValue<string>("adx_attributelogicalname") == _dataFieldName);
if (attributeWebFormMetadata != null)
{
if (attributeWebFormMetadata.GetAttributeValue<OptionSetValue>("adx_type") != null
&& attributeWebFormMetadata.GetAttributeValue<OptionSetValue>("adx_type").Value == 100000000
&& attributeWebFormMetadata.GetAttributeValue<EntityReference>("adx_entityformforcreate") != null
&& attributeWebFormMetadata.GetAttributeValue<OptionSetValue>("statuscode") != null
&& attributeWebFormMetadata.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Enums.EntityFormStatusCode.Active)
_lookupReferenceEntityFormId = attributeWebFormMetadata.GetAttributeValue<EntityReference>("adx_entityformforcreate").Id;
_groupName = attributeWebFormMetadata.GetAttributeValue<string>("adx_groupname") ?? string.Empty;
_cssClass = attributeWebFormMetadata.GetAttributeValue<string>("adx_cssclass") ?? string.Empty;
var overrideLabel = attributeWebFormMetadata.GetAttributeValue<string>("adx_label");
if (!string.IsNullOrWhiteSpace(overrideLabel))
{
var label = Localization.GetLocalizedString(overrideLabel, LanguageCode);
if (!string.IsNullOrEmpty(label))
{
Label = label;
}
}
var controlStyle = attributeWebFormMetadata.GetAttributeValue<OptionSetValue>("adx_controlstyle");
if (controlStyle != null)
{
switch (controlStyle.Value)
{
case (int)WebFormMetadata.ControlStyle.VerticalRadioButtonList:
_controlStyle = WebFormMetadata.ControlStyle.VerticalRadioButtonList;
break;
case (int)WebFormMetadata.ControlStyle.HorizontalRadioButtonList:
_controlStyle = WebFormMetadata.ControlStyle.HorizontalRadioButtonList;
break;
case (int)WebFormMetadata.ControlStyle.GeolocationLookupValidator:
_controlStyle = WebFormMetadata.ControlStyle.GeolocationLookupValidator;
_geolocationValidatorErrorMessage =
Localization.GetLocalizedString(
attributeWebFormMetadata.GetAttributeValue<string>("adx_geolocationvalidatorerrormessage"), LanguageCode);
break;
case (int)WebFormMetadata.ControlStyle.ConstantSum:
_controlStyle = WebFormMetadata.ControlStyle.ConstantSum;
_constantSumAttributeNames =
webFormMetadata.Where(
w =>
w.GetAttributeValue<OptionSetValue>("adx_controlstyle") != null &&
w.GetAttributeValue<OptionSetValue>("adx_controlstyle").Value ==
(int)WebFormMetadata.ControlStyle.ConstantSum && w.GetAttributeValue<string>("adx_groupname") == _groupName)
.Select(w => w.GetAttributeValue<string>("adx_attributelogicalname"))
.ToArray();
break;
case (int)WebFormMetadata.ControlStyle.RankOrderNoTies:
_controlStyle = WebFormMetadata.ControlStyle.RankOrderNoTies;
break;
case (int)WebFormMetadata.ControlStyle.RankOrderAllowTies:
_controlStyle = WebFormMetadata.ControlStyle.RankOrderAllowTies;
break;
case (int)WebFormMetadata.ControlStyle.MultipleChoiceMatrix:
_controlStyle = WebFormMetadata.ControlStyle.MultipleChoiceMatrix;
break;
case (int)WebFormMetadata.ControlStyle.MultipleChoice:
_controlStyle = WebFormMetadata.ControlStyle.MultipleChoice;
break;
case (int)WebFormMetadata.ControlStyle.StackRank:
_controlStyle = WebFormMetadata.ControlStyle.StackRank;
break;
case (int)WebFormMetadata.ControlStyle.LookupDropdown:
_controlStyle = WebFormMetadata.ControlStyle.LookupDropdown;
break;
}
}
_ignoreDefaultValue = attributeWebFormMetadata.GetAttributeValue<bool?>("adx_ignoredefaultvalue") ?? false;
_addDescription = attributeWebFormMetadata.GetAttributeValue<bool?>("adx_adddescription") ?? false;
var useAttributeDescription =
attributeWebFormMetadata.GetAttributeValue<bool?>("adx_useattributedescriptionproperty") ?? false;
if (useAttributeDescription)
{
var localizedDescription =
AttributeMetadata.Description.LocalizedLabels.SingleOrDefault(label => label.LanguageCode == LanguageCode);
if (localizedDescription != null)
{
_description = localizedDescription.Label;
}
}
else
{
_description =
Localization.GetLocalizedString(attributeWebFormMetadata.GetAttributeValue<string>("adx_description"),
LanguageCode);
}
var descriptionPosition = attributeWebFormMetadata.GetAttributeValue<OptionSetValue>("adx_descriptionposition");
if (descriptionPosition != null)
{
switch (descriptionPosition.Value)
{
case (int)WebFormMetadata.DescriptionPosition.AboveControl:
_descriptionPosition = WebFormMetadata.DescriptionPosition.AboveControl;
break;
case (int)WebFormMetadata.DescriptionPosition.BelowControl:
_descriptionPosition = WebFormMetadata.DescriptionPosition.BelowControl;
break;
case (int)WebFormMetadata.DescriptionPosition.AboveLabel:
_descriptionPosition = WebFormMetadata.DescriptionPosition.AboveLabel;
break;
}
}
_minMultipleChoiceSelectedCount =
attributeWebFormMetadata.GetAttributeValue<int?>("adx_minmultiplechoiceselectedcount") ?? 0;
_maxMultipleChoiceSelectedCount =
attributeWebFormMetadata.GetAttributeValue<int?>("adx_maxmultiplechoiceselectedcount") ?? 0;
_constantSumMinimumTotal = attributeWebFormMetadata.GetAttributeValue<int?>("adx_constantsumminimumtotal") ?? 0;
_constantSumMaximumTotal = attributeWebFormMetadata.GetAttributeValue<int?>("adx_constantsummaximumtotal") ?? 100;
_randomizeOptionSetValues = attributeWebFormMetadata.GetAttributeValue<bool?>("adx_randomizeoptionsetvalues") ??
false;
_webformForcefieldIsRequired = attributeWebFormMetadata.GetAttributeValue<bool?>("adx_fieldisrequired") ?? false;
_requiredFieldValidationErrorMessage =
Localization.GetLocalizedString(
attributeWebFormMetadata.GetAttributeValue<string>("adx_requiredfieldvalidationerrormessage"), LanguageCode);
_validationRegularExpression =
attributeWebFormMetadata.GetAttributeValue<string>("adx_validationregularexpression") ?? string.Empty;
_validationRegularExpressionErrorMessage =
Localization.GetLocalizedString(
attributeWebFormMetadata.GetAttributeValue<string>("adx_validationregularexpressionerrormessage"), LanguageCode);
_validationErrorMessage =
Localization.GetLocalizedString(
attributeWebFormMetadata.GetAttributeValue<string>("adx_validationerrormessage"), LanguageCode);
_rangeValidationErrorMessage =
Localization.GetLocalizedString(
attributeWebFormMetadata.GetAttributeValue<string>("adx_rangevalidationerrormessage"), LanguageCode);
_constantSumValidationErrorMessage =
Localization.GetLocalizedString(
attributeWebFormMetadata.GetAttributeValue<string>("adx_constantsumvalidationerrormessage"), LanguageCode);
_rankOrderNoTiesValidationErrorMessage =
Localization.GetLocalizedString(
attributeWebFormMetadata.GetAttributeValue<string>("adx_rankordernotiesvalidationerrormessage"), LanguageCode);
_multipleChoiceValidationErrorMessage =
Localization.GetLocalizedString(
attributeWebFormMetadata.GetAttributeValue<string>("adx_multiplechoicevalidationerrormessage"), LanguageCode);
}
}
// Not all the necessary attribute metadata properties were provided in the CellMetadata so
// we need to do some additional retreival and processing here
var attributeMetadata =
_attributeMetadata =
entityMetadata.Attributes.FirstOrDefault(attribute => attribute.LogicalName == _dataFieldName);
if (attributeMetadata == null)
{
return;
}
switch (attributeMetadata.AttributeType)
{
case AttributeTypeCode.Lookup:
{
string lookupViewID;
if (cellNode.TryGetElementValue("control/parameters/DefaultViewId", out lookupViewID))
{
Guid.TryParse(lookupViewID, out _lookupViewID);
}
cellNode.TryGetBooleanElementValue("control/parameters/DisableQuickFind", out _lookupDisableQuickFind);
cellNode.TryGetBooleanElementValue("control/parameters/DisableViewPicker", out _lookupDisableViewPicker);
cellNode.TryGetBooleanElementValue("control/parameters/AllowFilterOff", out _lookupAllowFilterOff);
cellNode.TryGetElementValue("control/parameters/AvailableViewIds", out _lookupAvailableViewIds);
cellNode.TryGetElementValue("control/parameters/FilterRelationshipName", out _lookupFilterRelationshipName);
cellNode.TryGetElementValue("control/parameters/DependentAttributeName", out _lookupDependentAttributeName);
cellNode.TryGetElementValue("control/parameters/DependentAttributeType", out _lookupDependentAttributeType);
var lookupAttributeMetadata = attributeMetadata as LookupAttributeMetadata;
if (lookupAttributeMetadata == null)
{
return;
}
LookupTargets = lookupAttributeMetadata.Targets;
}
break;
case AttributeTypeCode.Customer:
{
var lookupAttributeMetadata = attributeMetadata as LookupAttributeMetadata;
if (lookupAttributeMetadata == null)
{
return;
}
LookupTargets = lookupAttributeMetadata.Targets;
}
break;
case AttributeTypeCode.Owner:
{
ReadOnly = true;
var lookupAttributeMetadata = attributeMetadata as LookupAttributeMetadata;
if (lookupAttributeMetadata == null)
{
return;
}
LookupTargets = lookupAttributeMetadata.Targets;
}
break;
case AttributeTypeCode.Boolean:
{
var booleanAttributeMetadata = attributeMetadata as BooleanAttributeMetadata;
cellNode.TryGetAttributeValue("control", "datafieldname", out _dataFieldName);
if (booleanAttributeMetadata == null)
{
return;
}
string classIDstring;
cellNode.TryGetAttributeValue("control", "classid", out classIDstring);
_classID = new Guid(classIDstring);
BooleanOptionSetMetadata = booleanAttributeMetadata.OptionSet;
DefaultValue = booleanAttributeMetadata.DefaultValue;
}
break;
case AttributeTypeCode.String:
{
var stringAttributeMetadata = attributeMetadata as StringAttributeMetadata;
if (stringAttributeMetadata == null)
{
return;
}
MaxLength = stringAttributeMetadata.MaxLength ?? 0;
}
break;
case AttributeTypeCode.Picklist:
{
var picklistAttributeMetadata = attributeMetadata as PicklistAttributeMetadata;
if (picklistAttributeMetadata == null)
{
return;
}
DefaultValue = picklistAttributeMetadata.DefaultFormValue;
}
break;
case AttributeTypeCode.DateTime:
{
var dateTimeAttributeMetadata = attributeMetadata as DateTimeAttributeMetadata;
if (dateTimeAttributeMetadata == null)
{
return;
}
DateTimeBehavior = dateTimeAttributeMetadata.DateTimeBehavior;
}
break;
case AttributeTypeCode.Decimal:
{
var decimalAttributeMetadata = attributeMetadata as DecimalAttributeMetadata;
if (decimalAttributeMetadata == null)
{
return;
}
Precision = decimalAttributeMetadata.Precision;
}
break;
case AttributeTypeCode.Double:
{
var doubleAttributeMetadata = attributeMetadata as DoubleAttributeMetadata;
if (doubleAttributeMetadata == null)
{
return;
}
Precision = doubleAttributeMetadata.Precision;
}
break;
case AttributeTypeCode.Money:
{
var moneyAttributeMetadata = attributeMetadata as MoneyAttributeMetadata;
if (moneyAttributeMetadata == null)
{
return;
}
IsBaseCurrency = moneyAttributeMetadata.IsBaseCurrency.GetValueOrDefault();
Precision = moneyAttributeMetadata.Precision;
PrecisionSource = moneyAttributeMetadata.PrecisionSource;
}
break;
case AttributeTypeCode.Memo:
{
var memoAttributeMetadata = attributeMetadata as MemoAttributeMetadata;
if (memoAttributeMetadata == null)
{
return;
}
MaxLength = memoAttributeMetadata.MaxLength ?? 0;
}
break;
case AttributeTypeCode.State:
{
_labelNotAssociated = true;
ReadOnly = true;
var stateAttributeMetadata = attributeMetadata as StateAttributeMetadata;
if (stateAttributeMetadata == null)
{
return;
}
_stateOptionSetOptions = stateAttributeMetadata.OptionSet.Options;
}
break;
case AttributeTypeCode.Status:
{
_labelNotAssociated = true;
ReadOnly = true;
var statusAttributeMetadata = attributeMetadata as StatusAttributeMetadata;
if (statusAttributeMetadata == null)
{
return;
}
_statusOptionSetOptions = statusAttributeMetadata.OptionSet.Options;
}
break;
}
ToolTip = toolTipEnabled != false ? base.ToolTip : null;
if (recommendedFieldsRequired == true &&
(attributeMetadata.RequiredLevel.Value == AttributeRequiredLevel.Recommended))
{
IsRequired = true;
}
else if (_forceAllFieldsRequired)
{
IsRequired = true;
}
else
{
IsRequired = base.IsRequired;
}
}
}
///<summary>
/// Stores the BooleanOptionSetMetadata for an attribute of type boolean.
///</summary>
public BooleanOptionSetMetadata BooleanOptionSetMetadata { get; private set; }
/// <summary>
/// Tooltip text of the control.
/// </summary>
public new string ToolTip
{
get; private set;
}
/// <summary>
/// Date Time Behaviour of the control.
/// </summary>
public DateTimeBehavior DateTimeBehavior
{
get; private set;
}
/// <summary>
/// Validation text displayed next to the control when validation fails. Default value is '*'.
/// </summary>
public string ValidationText
{
get { return _validationText ?? DefaultValidationText; }
}
/// <summary>
/// Denotes if the field is required to contain a value.
/// </summary>
public new bool IsRequired
{
get; set;
}
/// <summary>
/// The id of the control.
/// </summary>
public virtual string ControlID
{
get { return _controlID; }
}
/// <summary>
/// Class id of the cell in the form XML.
/// </summary>
public virtual Guid ClassID
{
get { return _classID; }
}
/// <summary>
/// Gets whether the attribute represents the base currency or the transaction currency (if this is a currency attribute).
/// </summary>
public virtual bool IsBaseCurrency { get; private set; }
/// <summary>
/// Indicates if the cell contains a notes control.
/// </summary>
public virtual bool IsNotesControl
{
get { return _isNotesControl; }
}
/// <summary>
/// Indicates if the cell contains a full name control.
/// </summary>
public virtual bool IsFullNameControl
{
get { return _isFullnameControl; }
}
/// <summary>
/// Indicates if the cell contains a Address Composite Control.
/// </summary>
public virtual bool IsAddressCompositeControl
{
get { return _isAddressCompositeControl; }
}
/// <summary>
/// Indicates if the cell contains an activity timeline control.
/// </summary>
public virtual bool IsActivityTimelineControl
{
get { return _isActivityTimelineControl; }
}
/// <summary>
/// Indicates if the cell contains a web resource.
/// </summary>
public virtual bool IsWebResource
{
get { return _isWebResource; }
}
/// <summary>
/// Array of targets of a given lookup control.
/// </summary>
public string[] LookupTargets { get; private set; }
/// <summary>
/// Maximum length of the control value.
/// </summary>
public int MaxLength { get; private set; }
/// <summary>
/// Precision of a Decimal Number, Floating Point Number or Currency field.
/// </summary>
public int? Precision { get; private set; }
/// <summary>
/// Gets the precision source for the attribute.
/// </summary>
public int? PrecisionSource { get; private set; }
/// <summary>
/// Alternate Text of the web resource.
/// </summary>
public virtual string WebResourceAltText
{
get { return _webResourceAltText; }
}
/// <summary>
/// Indicates if a border should be rendered on the web resource container.
/// </summary>
public virtual bool WebResourceBorder
{
get { return _webResourceBorder; }
}
/// <summary>
/// The data of the web resource.
/// </summary>
public virtual string WebResourceData
{
get { return _webResourceData; }
}
/// <summary>
/// The height of the web resource container.
/// </summary>
public virtual int? WebResourceHeight
{
get { return _webResourceHeight; }
}
/// <summary>
/// Horizontal alignment of the web resource.
/// </summary>
public virtual string WebResourceHorizontalAlignment
{
get { return _webResourceHorizontalAlignment; }
}
/// <summary>
/// Indicates if the web resource type is HTML.
/// </summary>
public virtual bool WebResourceIsHtml
{
get { return _webResourceIsHtml; }
}
/// <summary>
/// Indicates if the web resource type is Image.
/// </summary>
public virtual bool WebResourceIsImage
{
get { return _webResourceIsImage; }
}
/// <summary>
/// Indicates if the web resource type is Silverlight.
/// </summary>
public virtual bool WebResourceIsSilverlight
{
get { return _webResourceIsSilverlight; }
}
/// <summary>
/// Indicates if the web resource passes parameters.
/// </summary>
public virtual bool WebResourcePassParameters
{
get { return _webResourcePassParameters; }
}
/// <summary>
/// Scrolling of the web resource.
/// </summary>
public virtual string WebResourceScrolling
{
get { return _webResourceScrolling; }
}
/// <summary>
/// Security of the web resource.
/// </summary>
public virtual bool WebResourceSecurity
{
get { return _webResourceSecurity; }
}
/// <summary>
/// Size type of the web resource.
/// </summary>
public virtual string WebResourceSizeType
{
get { return _webResourceSizeType; }
}
/// <summary>
/// URL of the web resource.
/// </summary>
public virtual string WebResourceUrl
{
get { return _webResourceUrl; }
}
/// <summary>
/// Vertical alignment of the web resource.
/// </summary>
public virtual string WebResourceVerticalAlignment
{
get { return _webResourceVerticalAlignment; }
}
/// <summary>
/// Width of the web resource.
/// </summary>
public virtual int? WebResourceWidth
{
get { return _webResourceWidth; }
}
/// <summary>
/// Default value of the field.
/// </summary>
public object DefaultValue { get; private set; }
/// <summary>
/// Web Form Metadata property used to specify a control style for a field to provide advanced functionality.
/// </summary>
public virtual WebFormMetadata.ControlStyle ControlStyle
{
get { return _controlStyle; }
}
/// <summary>
/// Web Form Metadata property used to specify the error message to be displayed when the geolocation validator validation fails.
/// </summary>
public string GeolocationValidatorErrorMessage
{
get { return _geolocationValidatorErrorMessage; }
}
/// <summary>
/// The id of the saved query view used to retrieve data to populate the lookup field. An Empty Guid indicates we need to find the default view.
/// </summary>
public Guid LookupViewID
{
get { return _lookupViewID; }
}
/// <summary>
/// Web Form metadata provides the option to ignore a field's default value. Useful for Two Option control radio buttons.
/// </summary>
public bool IgnoreDefaultValue
{
get { return _ignoreDefaultValue; }
}
/// <summary>
/// Web Form Metadata property used to indicate a description should be added.
/// </summary>
public bool AddDescription
{
get { return _addDescription; }
}
/// <summary>
/// Web Form Metadata property used to add a description or special instructions for a field.
/// </summary>
public string Description
{
get { return _description; }
}
/// <summary>
/// Web Form Metadata property used to specify the position of the description relative to the position of the field is is associated with.
/// </summary>
public WebFormMetadata.DescriptionPosition DescriptionPosition
{
get { return _descriptionPosition; }
}
/// <summary>
/// Web Form Metadata property used to make a field required.
/// </summary>
public bool WebFormForceFieldIsRequired
{
get { return _webformForcefieldIsRequired; }
}
/// <summary>
/// Web Form Metadata property used to add a custom error message for a field's Required Field Validator.
/// </summary>
public string RequiredFieldValidationErrorMessage
{
get { return _requiredFieldValidationErrorMessage; }
}
/// <summary>
/// Web Form Metadata property used to add a Regular Expression Validator for a field.
/// </summary>
public string ValidationRegularExpression
{
get { return _validationRegularExpression; }
}
/// <summary>
/// Web Form Metadata property used to add an error message for the Regular Expression Validator for a field.
/// </summary>
public string ValidationRegularExpressionErrorMessage
{
get { return _validationRegularExpressionErrorMessage; }
}
/// <summary>
/// Web Form Metadata property used to add an error message for the Range Validator for a field.
/// </summary>
public string RangeValidationErrorMessage
{
get { return _rangeValidationErrorMessage; }
}
/// <summary>
/// Web Form Metadata property used to add an error message for the Custom Validator for a field.
/// </summary>
public string ValidationErrorMessage
{
get { return _validationErrorMessage; }
}
/// <summary>
/// Web Form Metadata property used to add an error message for the Constant Sum Custom Validator.
/// </summary>
public string ConstantSumValidationErrorMessage
{
get { return _constantSumValidationErrorMessage; }
}
/// <summary>
/// Web Form Metadata property used to add an error message for the Rank Order No Ties Custom Validator.
/// </summary>
public string RankOrderNoTiesValidationErrorMessage
{
get { return _rankOrderNoTiesValidationErrorMessage; }
}
/// <summary>
/// Web Form Metadata property used to add an error message for the Multiple Choice Custom Validator.
/// </summary>
public string MultipleChoiceValidationErrorMessage
{
get { return _multipleChoiceValidationErrorMessage; }
}
/// <summary>
/// Web Form Metadata property used to group fields by adding a CSS class name to like fields to allow custom processing.
/// </summary>
public string GroupName
{
get { return _groupName; }
}
/// <summary>
/// Array of attribute names of the constant sum group
/// </summary>
public string[] ConstantSumAttributeNames
{
get { return _constantSumAttributeNames; }
}
/// <summary>
/// Randomizes the rendering order of the option set values.
/// </summary>
public bool RandomizeOptionSetValues
{
get { return _randomizeOptionSetValues; }
}
/// <summary>
/// Minimum required number of multiple choice check boxes in a group that must be selected.
/// </summary>
public int MinMultipleChoiceSelectedCount
{
get { return _minMultipleChoiceSelectedCount; }
}
/// <summary>
/// Maximum allowable number of multiple choice check boxes in a group that can be selected.
/// </summary>
public int MaxMultipleChoiceSelectedCount
{
get { return _maxMultipleChoiceSelectedCount; }
}
/// <summary>
/// Enable or disable the rendering of anchor links in the validation summary.
/// </summary>
public bool EnableValidationSummaryLinks
{
get { return _enableValidationSummaryLinks; }
}
/// <summary>
/// Validation summary render hyperlinks to control anchors using this text.
/// </summary>
public string ValidationSummaryLinkText
{
get { return _validationSummaryLinkText; }
}
/// <summary>
/// Minimum allowable total of the constant sum.
/// </summary>
public int ConstantSumMinimumTotal
{
get { return _constantSumMinimumTotal; }
}
/// <summary>
/// Maximum allowable total of the constant sum.
/// </summary>
public int ConstantSumMaximumTotal
{
get { return _constantSumMaximumTotal; }
}
/// <summary>
/// Web Form Metadata property used to add a CSS class name(s) to a field.
/// </summary>
public string CssClass
{
get { return _cssClass; }
}
/// <summary>
/// Collecton of Format Strings specified in the CrmEntityFormView templating used for validation messages.
/// </summary>
public Dictionary<string, string> Messages
{
get { return _messages; }
}
/// <summary>
/// Indicates if the cell contains a SharePoint documents control.
/// </summary>
public virtual bool IsSharePointDocuments
{
get { return _isSharePointDocuments; }
}
/// <summary>
/// Indicates if the cell contains a subgrid control.
/// </summary>
public virtual bool IsSubgrid
{
get { return _isSubgrid; }
}
/// <summary>
/// The ID of the savedquery view for the subgrid control.
/// </summary>
public virtual string ViewID
{
get { return _viewID; }
}
/// <summary>
/// The relationship name of the savedquery view for the subgrid control.
/// </summary>
public virtual string ViewRelationshipName
{
get { return _viewRelationshipName; }
}
/// <summary>
/// The entity type of the savedquery view for the subgrid control.
/// </summary>
public virtual string ViewTargetEntityType
{
get { return _viewTargetEntityType; }
}
/// <summary>
/// Indicates if the quick find search is enabled or not on the savedquery view for the subgrid control.
/// </summary>
public virtual bool ViewEnableQuickFind
{
get { return _viewEnableQuickFind; }
}
/// <summary>
/// Indicates if the view picker is enabled or not on the savedquery view for the subgrid control.
/// </summary>
public virtual bool ViewEnableViewPicker
{
get { return _viewEnableViewPicker; }
}
/// <summary>
/// The IDs of the savedquery views available for the view picker for the subgrid control.
/// </summary>
public virtual string ViewIds
{
get { return _viewIds; }
}
/// <summary>
/// The number of records per page of the savedquery view for the subgrid control.
/// </summary>
public virtual int? ViewRecordsPerPage
{
get { return _viewRecordsPerPage; }
}
/// <summary>
/// The logical name of the form's target entity.
/// </summary>
public virtual string TargetEntityName
{
get { return _targetEntityName; }
}
/// <summary>
/// The logical name of the form's target entity primary key.
/// </summary>
public virtual string TargetEntityPrimaryKeyName
{
get { return _targetEntityPrimaryKeyName; }
}
/// <summary>
/// The logical name of the form's target entity primary attribute.
/// </summary>
public virtual string TargetEntityPrimaryAttributeName
{
get { return _targetEntityPrimaryAttributeName; }
}
/// <summary>
/// The settings of a subgrid.
/// </summary>
public virtual JsonConfiguration.GridMetadata SubgridSettings
{
get { return _subgridSettings; }
}
/// <summary>
/// The settings of a notes control.
/// </summary>
public virtual JsonConfiguration.NotesMetadata NotesSettings
{
get { return _notesSettings; }
}
/// <summary>
/// The settings of a timeline control.
/// </summary>
public virtual JsonConfiguration.TimelineMetadata TimelineSettings
{
get { return _timelineSettings; }
}
/// <summary>
/// The number of notes per page to display for a notes control.
/// </summary>
public virtual int? NotesPageSize
{
get { return _notesPageSize; }
}
/// <summary>
/// The settings of a SharePoint grid.
/// </summary>
public virtual SharePointGridMetadata SharePointSettings
{
get { return _sharePointSettings; }
}
/// <summary>
/// The number of folders and files per page to display for a SharePoint grid.
/// </summary>
public virtual int? SharePointGridPageSize
{
get { return _sharePointGridPageSize; }
}
/// <summary>
/// Indicates if the quick find search is enabled or not on the savedquery view for the lookup control.
/// </summary>
public virtual bool LookupDisableQuickFind
{
get { return _lookupDisableQuickFind; }
}
/// <summary>
/// Indicates if the view picker is enabled or not on the savedquery view for the lookup control.
/// </summary>
public virtual bool LookupDisableViewPicker
{
get { return _lookupDisableViewPicker; }
}
/// <summary>
/// Indicates if the users can toggle the filter on the savedquery view for the lookup control.
/// </summary>
public virtual bool LookupAllowFilterOff
{
get { return _lookupAllowFilterOff; }
}
/// <summary>
/// A comma delimited list of ID's of savedquery views that to allow a user to select from views on the lookup control.
/// </summary>
public virtual string LookupAvailableViewIds
{
get { return _lookupAvailableViewIds; }
}
/// <summary>
/// The relationship schema name used to build a filter on a savedquery view for the lookup control.
/// </summary>
public virtual string LookupFilterRelationshipName
{
get { return _lookupFilterRelationshipName; }
}
/// <summary>
/// The attribute logical name of the property that contains the ID of the record to be applied to build the filter on a savedquery view for the lookup control.
/// </summary>
public virtual string LookupDependentAttributeName
{
get { return _lookupDependentAttributeName; }
}
/// <summary>
/// The entity logical name of used to build the filter on a savedquery view for the lookup control.
/// </summary>
public virtual string LookupDependentAttributeType
{
get { return _lookupDependentAttributeType; }
}
/// <summary>
/// The OptionSetValues of the state option set.
/// </summary>
public virtual OptionMetadataCollection StateOptionSetOptions
{
get { return _stateOptionSetOptions; }
}
/// <summary>
/// The OptionSetValues of the status reason option set.
/// </summary>
public virtual OptionMetadataCollection StatusOptionSetOptions
{
get { return _statusOptionSetOptions; }
}
/// <summary>
/// Indicates if the label should not be associated to a control
/// </summary>
public virtual bool LabelNotAssociated
{
get { return _labelNotAssociated; }
}
/// <summary>
/// Indicates if the cell contains a quick form
/// </summary>
public virtual bool IsQuickForm
{
get { return _isQuickForm; }
}
/// <summary>
/// The definition of the quick form
/// </summary>
public virtual CrmQuickForm QuickForm
{
get { return _quickForm; }
}
/// <summary>
/// Gets whether the value can be set when a record is created.
/// </summary>
public virtual bool IsValidForCreate
{
get { return _attributeMetadata == null || _attributeMetadata.IsValidForCreate.GetValueOrDefault(); }
}
/// <summary>
/// Gets whether the value can be updated.
/// </summary>
public virtual bool IsValidForUpdate
{
get { return _attributeMetadata == null || _attributeMetadata.IsValidForUpdate.GetValueOrDefault(); }
}
/// <summary>
/// Gets the lookup reference entity form id
/// </summary>
public virtual Guid? LookupReferenceEntityFormId
{
get { return _lookupReferenceEntityFormId; }
}
}
}
| |
using System;
using System.Diagnostics;
using System.Dynamic;
using System.Runtime.CompilerServices;
using System.Threading;
using L4p.Common.DumpToLogs;
using L4p.Common.Extensions;
using L4p.Common.Helpers;
using L4p.Common.IoCs;
using L4p.Common.Json;
using L4p.Common.Loggers;
using L4p.Common.PubSub.client.Io;
using L4p.Common.PubSub.comm;
using L4p.Common.PubSub.contexts;
using L4p.Common.PubSub.utils;
using L4p.Common.Schedulers;
namespace L4p.Common.PubSub.client
{
interface ISignalsManagerEx : ISignalsManager, IHaveDump
{
void GotHelloMsg(SignalsAgent asFriend, string agent, int snapshotId);
void GotGoodbyeMsg(SignalsAgent asFriend, string agent);
void GotPublishMsg(SignalsAgent asFriend, comm.PublishMsg pmsg);
void ClearAgentsList(SignalsAgent asFriend);
void FilterTopicMsgs(SignalsAgent asFriend, comm.TopicFilterMsg msg);
void CancelSubscription(SignalSlot asFriend, HandlerInfo handler);
void GenerateHelloMsg(HelloPulseBeat asFriend, int sequentialId);
void Idle(SignalsManagerEx asFriend);
}
public class SignalsManagerEx : ISignalsManagerEx
{
#region counters
class Counters
{
public int GotHelloMsg;
public int GotGoodbyeMsg;
public int GotPublishMsg;
public int TopicIsNotFound;
public int FailedToParseMsgJson;
public int HelloMsgSent;
public int GoodbyeMsgSent;
public int PublishedMsgs;
public int Subscribtions;
public int SubscribtionsWithFilters;
public int WholeTopicIsFiltered;
public int FiltersAreSet;
public int NoFiltersAreSet;
public int FilterTopicMsgIsSent;
}
#endregion
#region members
private readonly string _serviceName;
private readonly Counters _counters;
private readonly ILogFile _log;
private readonly ISignalsConfigRa _configRa;
private readonly ILocalRepo _lrepo;
private readonly IRemoteRepo _rrepo;
private readonly ITopicsRepo _topics;
private readonly ILocalDispatcher _locals;
private readonly IRemoteDispatcher _remotes;
private readonly IHeloPulseBeat _pulse;
private readonly ISignalsAgent _agent;
private readonly IMessangerEngine _messanger;
private readonly IJsonEngine _json;
private readonly ILocalFactory _factory;
private readonly IEventScheduler _scheduler;
private readonly ISessionContext _context;
private readonly IFiltersEngine _filters;
private readonly IAgentConnector _connector;
#endregion
#region construction
public static ISignalsManager New(SignalsConfig config = null)
{
config = config ?? new SignalsConfig();
return
new SignalsManagerEx(config);
}
private IIoC create_dependencies(SignalsConfig config)
{
var ioc = IoC.New();
var log = LogFile.New(SignalsComponent.LogName);
var configRa = SignalsConfigRa.New(config);
ioc.RegisterInstance<ILogFile>(log);
ioc.RegisterInstance<ISignalsConfigRa>(configRa);
ioc.RegisterInstance<ISignalsManagerEx>(this);
var myAgent = SignalsAgent.New(ioc);
ioc.SingleInstance(() => FiltersEngine.New(log));
ioc.SingleInstance(LocalRepo.New);
ioc.SingleInstance(RemoteRepo.New);
ioc.SingleInstance(TopicsRepo.NewSync);
ioc.SingleInstance(JsonEngine.New);
ioc.SingleInstance(AgentConnector.New);
ioc.SingleInstance(MessangerEngine.New);
ioc.SingleInstance(LocalDispatcher.New);
ioc.SingleInstance(() => RemoteDispatcher.New(myAgent.AgentUri, ioc));
ioc.SingleInstance(() => HelloPulseBeat.New(ioc));
ioc.SingleInstance(() => myAgent);
ioc.SingleInstance(MessangerEngine.New);
ioc.SingleInstance(LocalFactory.New);
ioc.SingleInstance(() => EventScheduler.New(log));
ioc.SingleInstance(SessionContext.New);
return ioc;
}
private SignalsManagerEx(SignalsConfig config)
{
_serviceName = GetType().AsServiceName();
var ioc = create_dependencies(config);
_counters = new Counters();
_log = ioc.Resolve<ILogFile>();
_configRa = ioc.Resolve<ISignalsConfigRa>();
_lrepo = ioc.Resolve<ILocalRepo>();
_rrepo = ioc.Resolve<IRemoteRepo>();
_topics = ioc.Resolve<ITopicsRepo>();
_locals = ioc.Resolve<ILocalDispatcher>();
_remotes = ioc.Resolve<IRemoteDispatcher>();
_pulse = ioc.Resolve<IHeloPulseBeat>();
_agent = ioc.Resolve<ISignalsAgent>();
_messanger = ioc.Resolve<IMessangerEngine>();
_json = ioc.Resolve<IJsonEngine>();
_factory = ioc.Resolve<ILocalFactory>();
_scheduler = ioc.Resolve<IEventScheduler>();
_context = ioc.Resolve<ISessionContext>();
_filters = ioc.Resolve<IFiltersEngine>();
_connector = ioc.Resolve<IAgentConnector>();
}
#endregion
#region private
private bool it_is_myself(string agentUri)
{
return
agentUri == _agent.AgentUri;
}
private void generate_hello_msg(int snapshotId, int sequentialId)
{
Validate.NotZero(snapshotId);
var msg = new comm.HelloMsg
{
AgentUri = _agent.AgentUri,
SnapshotId = snapshotId,
ServiceName = _serviceName,
SequentialId = sequentialId
};
_messanger.SendHelloMsg(msg);
Interlocked.Increment(ref _counters.HelloMsgSent);
}
private void generate_goodbye_msg()
{
var agentUri = _agent.AgentUri;
_messanger.SendGoodbyeMsg(agentUri);
Interlocked.Increment(ref _counters.GoodbyeMsgSent);
}
private void say_deferred_hello()
{
var config = _configRa.Values;
_pulse.SayHelloIn(config.Client.HelloMsgOnChangeSpan);
}
private static void register_dump_to_log(ISignalsManagerEx self, ILogFile log)
{
DumpManager.Register<SignalsComponent>(self.Dump);
}
private static void dump_state_to_log(ISignalsManagerEx self, ILogFile log)
{
var dump = self.Dump().ToJson();
log.Info("SignalsManagerEx dump: {0}", dump);
}
private void filter_topic_msgs(int snapshotId, comm.PublishMsg pmsg, HandlerInfo[] handlers, TopicDetails topicDetails)
{
comm.TopicFilterMsg filterMsg = null;
try
{
filterMsg = _filters.BuildFilterTopicMsg(_agent.AgentUri, snapshotId, pmsg, handlers, topicDetails);
}
catch (Exception ex)
{
_log.Warn(ex, "Failed to build filter topic message for {0}", pmsg.ToJson());
}
if (filterMsg == null)
{
Interlocked.Increment(ref topicDetails.Counters.FiledToBuildFilterTopicMsg);
return;
}
_remotes.FilterTopicMsgs(pmsg.FromAgent, filterMsg);
_log.Info("Topic '{0}': []--> filter to '{1}' {2}", pmsg.TopicName, _agent.AgentUri, filterMsg.AsDscrStr());
Interlocked.Increment(ref _counters.FilterTopicMsgIsSent);
}
#endregion
#region interface
[MethodImpl(MethodImplOptions.NoInlining)]
ISignalSlot ISignalsManager.SubscribeTo<T>(Action<T> callback, Func<T, bool> filter, StackFrame filterAt)
{
if (filterAt == null)
filterAt = new StackFrame(1);
var type = typeof(T);
var topic = _factory.make_topic(type);
var handler = _factory.make_handler(topic, callback, filter, filterAt);
_lrepo.AddHandler(handler);
Interlocked.Increment(ref topic.Details.Counters.Handlers);
var slot = SignalSlot.New(this, handler);
say_deferred_hello();
Interlocked.Increment(ref _counters.Subscribtions);
if (filter != null)
{
Interlocked.Increment(ref topic.Details.Counters.Filters);
Interlocked.Increment(ref _counters.SubscribtionsWithFilters);
}
_log.Info("Topic '{0}': ({1}) is subscribed to", topic.Name, topic.Guid);
return slot;
}
void ISignalsManager.Publish<T>(T msg)
{
Validate.NotNull(msg);
var topic = _factory.make_topic(typeof(T));
_log.Trace("Topic '{0}': []--> from '{1}'", topic.Name, _agent.AgentUri);
Interlocked.Increment(ref topic.Details.Counters.MsgPublished);
_locals.DispatchLocalMsg(topic, msg);
_remotes.DispatchRemoteMsg(topic, msg);
Interlocked.Increment(ref _counters.PublishedMsgs);
}
ISessionContext ISignalsManager.Context
{
get { return _context; }
}
void ISignalsManager.StartAgent()
{
var config = _configRa.Values;
_log.Trace("Starting signals manager at '{0}' ...", _serviceName);
_agent.Start(this);
_pulse.Start(this);
_scheduler.Start();
ISignalsManagerEx self = this;
_scheduler.Repeat(config.Client.DumpToLogPeriod,
() => dump_state_to_log(this, _log));
_scheduler.Repeat(config.Client.IdleSpan,
() => self.Idle(this));
_scheduler.FireOnce(1.Seconds(),
() => register_dump_to_log(this, _log));
_log.Info("Signals manager '{0}' is started at '{1}'; {2}",
SignalsComponent.Version, _serviceName, config.ToJson());
}
void ISignalsManager.StopAgent()
{
_log.Trace("Stopping signals manager at '{0}' ...", _serviceName);
_scheduler.Stop();
_pulse.Stop();
_agent.Stop();
generate_goodbye_msg();
_log.Info("Signals manager is stopped at '{0}'", _serviceName);
}
ExpandoObject IHaveDump.Dump(dynamic root)
{
if (root == null)
root = new ExpandoObject();
var config = _configRa.Values;
root.ServiceName = _serviceName;
root.Counters = _counters;
root.Config = config;
root.LRepo = _lrepo.Dump();
root.RRepo = _rrepo.Dump();
root.LocalDispatcher = _locals.Dump();
root.RemoteDispatcher = _remotes.Dump();
root.Messanger = _messanger.Dump();
root.PulseBeat = _pulse.Dump();
root.LocalFactory = _factory.Dump();
root.FiltersEngine = _filters.Dump();
root.Topics = _topics.Dump();
root.Connector = _connector.Dump();
return root;
}
void ISignalsManagerEx.GotHelloMsg(SignalsAgent asFriend, string agent, int snapshotId)
{
if (it_is_myself(agent))
return;
_log.Info("Got hello from '{0}' snapshotId={1}", agent, snapshotId);
Interlocked.Increment(ref _counters.GotHelloMsg);
_rrepo.SetSnapshotId(agent, snapshotId);
_messanger.AgentIsHere(agent);
}
void ISignalsManagerEx.GotGoodbyeMsg(SignalsAgent asFriend, string agent)
{
if (it_is_myself(agent))
return;
_log.Info("Got goodbye from '{0}'", agent);
Interlocked.Increment(ref _counters.GotGoodbyeMsg);
_rrepo.RemoveAgent(agent);
_messanger.AgentIsGone(agent);
}
void ISignalsManagerEx.GotPublishMsg(SignalsAgent asFriend, comm.PublishMsg pmsg)
{
_log.Trace("Topic '{0}': -->[] from '{1}'", pmsg.TopicName, pmsg.FromAgent);
Interlocked.Increment(ref _counters.GotPublishMsg);
var topicDetails = _topics.GetTopicDetails(pmsg.TopicGuid, pmsg.TopicName);
Interlocked.Increment(ref topicDetails.Counters.MsgGotPublished);
int snapshotId;
var handlers = _lrepo.GetHandlers(pmsg.TopicGuid, out snapshotId);
if (handlers.IsEmpty())
{
Interlocked.Increment(ref _counters.TopicIsNotFound);
Interlocked.Increment(ref topicDetails.Counters.NoHandlersFound);
filter_topic_msgs(snapshotId, pmsg, null, topicDetails);
return;
}
var topic = handlers[0].Topic;
var msg = _json.MsgFromJson(topic, pmsg.Json);
if (msg == null)
{
Interlocked.Increment(ref _counters.FailedToParseMsgJson);
return;
}
bool hasListeners = _locals.DispatchRemoteMsg(msg, handlers);
Interlocked.Increment(ref topicDetails.Counters.MsgDispatched);
if (hasListeners)
return;
filter_topic_msgs(snapshotId, pmsg, handlers, topicDetails);
}
void ISignalsManagerEx.ClearAgentsList(SignalsAgent asFriend)
{
_rrepo.Clear();
_log.Info("Got clear remote agents request (done)");
}
void ISignalsManagerEx.FilterTopicMsgs(SignalsAgent asFriend, comm.TopicFilterMsg msg)
{
_log.Trace("Topic '{0}': -->[] filter from '{1}'; {2}", msg.TopicName, msg.AgentToFilter, msg.AsDscrStr());
if (msg.Filters.IsEmpty())
{
_rrepo.FilterTopicMsgs(msg, null);
Interlocked.Increment(ref _counters.WholeTopicIsFiltered);
return;
}
var filters = _filters.BuildFilters(msg.Filters);
if (filters.IsEmpty())
{
Interlocked.Increment(ref _counters.NoFiltersAreSet);
return;
}
_rrepo.FilterTopicMsgs(msg, filters);
Interlocked.Increment(ref _counters.FiltersAreSet);
}
void ISignalsManagerEx.CancelSubscription(SignalSlot asFriend, HandlerInfo handler)
{
bool wasThere = _lrepo.RemoveHandler(handler);
if (wasThere == false)
return;
_log.Trace("Topic '{0}': subscription is canceled", handler.Topic.Name);
Interlocked.Decrement(ref _counters.Subscribtions);
say_deferred_hello();
}
void ISignalsManagerEx.GenerateHelloMsg(HelloPulseBeat asFriend, int sequentialId)
{
Validate.NotNull(asFriend);
int snapshotId = _lrepo.GetSnapshotId();
generate_hello_msg(snapshotId, sequentialId);
}
void ISignalsManagerEx.Idle(SignalsManagerEx asFriend)
{
_messanger.Idle();
}
#endregion
}
}
| |
//
// PKCS8.cs: PKCS #8 - Private-Key Information Syntax Standard
// ftp://ftp.rsasecurity.com/pub/pkcs/doc/pkcs-8.doc
//
// Author:
// Sebastien Pouliot <sebastien@xamarin.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
// Copyright 2013 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Security.Cryptography;
using Mono.Security.X509;
namespace Mono.Security.Cryptography {
#if !INSIDE_CORLIB
public
#endif
sealed class PKCS8 {
public enum KeyInfo {
PrivateKey,
EncryptedPrivateKey,
Unknown
}
private PKCS8 ()
{
}
static public KeyInfo GetType (byte[] data)
{
if (data == null)
throw new ArgumentNullException ("data");
KeyInfo ki = KeyInfo.Unknown;
try {
ASN1 top = new ASN1 (data);
if ((top.Tag == 0x30) && (top.Count > 0)) {
ASN1 firstLevel = top [0];
switch (firstLevel.Tag) {
case 0x02:
ki = KeyInfo.PrivateKey;
break;
case 0x30:
ki = KeyInfo.EncryptedPrivateKey;
break;
}
}
}
catch {
throw new CryptographicException ("invalid ASN.1 data");
}
return ki;
}
/*
* PrivateKeyInfo ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] IMPLICIT Attributes OPTIONAL
* }
*
* Version ::= INTEGER
*
* PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
*
* PrivateKey ::= OCTET STRING
*
* Attributes ::= SET OF Attribute
*/
public class PrivateKeyInfo {
private int _version;
private string _algorithm;
private byte[] _key;
private ArrayList _list;
public PrivateKeyInfo ()
{
_version = 0;
_list = new ArrayList ();
}
public PrivateKeyInfo (byte[] data) : this ()
{
Decode (data);
}
// properties
public string Algorithm {
get { return _algorithm; }
set { _algorithm = value; }
}
public ArrayList Attributes {
get { return _list; }
}
public byte[] PrivateKey {
get {
if (_key == null)
return null;
return (byte[]) _key.Clone ();
}
set {
if (value == null)
throw new ArgumentNullException ("PrivateKey");
_key = (byte[]) value.Clone ();
}
}
public int Version {
get { return _version; }
set {
if (value < 0)
throw new ArgumentOutOfRangeException ("negative version");
_version = value;
}
}
// methods
private void Decode (byte[] data)
{
ASN1 privateKeyInfo = new ASN1 (data);
if (privateKeyInfo.Tag != 0x30)
throw new CryptographicException ("invalid PrivateKeyInfo");
ASN1 version = privateKeyInfo [0];
if (version.Tag != 0x02)
throw new CryptographicException ("invalid version");
_version = version.Value [0];
ASN1 privateKeyAlgorithm = privateKeyInfo [1];
if (privateKeyAlgorithm.Tag != 0x30)
throw new CryptographicException ("invalid algorithm");
ASN1 algorithm = privateKeyAlgorithm [0];
if (algorithm.Tag != 0x06)
throw new CryptographicException ("missing algorithm OID");
_algorithm = ASN1Convert.ToOid (algorithm);
ASN1 privateKey = privateKeyInfo [2];
_key = privateKey.Value;
// attributes [0] IMPLICIT Attributes OPTIONAL
if (privateKeyInfo.Count > 3) {
ASN1 attributes = privateKeyInfo [3];
for (int i=0; i < attributes.Count; i++) {
_list.Add (attributes [i]);
}
}
}
public byte[] GetBytes ()
{
ASN1 privateKeyAlgorithm = new ASN1 (0x30);
privateKeyAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
privateKeyAlgorithm.Add (new ASN1 (0x05)); // ASN.1 NULL
ASN1 pki = new ASN1 (0x30);
pki.Add (new ASN1 (0x02, new byte [1] { (byte) _version }));
pki.Add (privateKeyAlgorithm);
pki.Add (new ASN1 (0x04, _key));
if (_list.Count > 0) {
ASN1 attributes = new ASN1 (0xA0);
foreach (ASN1 attribute in _list) {
attributes.Add (attribute);
}
pki.Add (attributes);
}
return pki.GetBytes ();
}
// static methods
static private byte[] RemoveLeadingZero (byte[] bigInt)
{
int start = 0;
int length = bigInt.Length;
if (bigInt [0] == 0x00) {
start = 1;
length--;
}
byte[] bi = new byte [length];
Buffer.BlockCopy (bigInt, start, bi, 0, length);
return bi;
}
static private byte[] Normalize (byte[] bigInt, int length)
{
if (bigInt.Length == length)
return bigInt;
else if (bigInt.Length > length)
return RemoveLeadingZero (bigInt);
else {
// pad with 0
byte[] bi = new byte [length];
Buffer.BlockCopy (bigInt, 0, bi, (length - bigInt.Length), bigInt.Length);
return bi;
}
}
/*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*/
static public RSA DecodeRSA (byte[] keypair)
{
ASN1 privateKey = new ASN1 (keypair);
if (privateKey.Tag != 0x30)
throw new CryptographicException ("invalid private key format");
ASN1 version = privateKey [0];
if (version.Tag != 0x02)
throw new CryptographicException ("missing version");
if (privateKey.Count < 9)
throw new CryptographicException ("not enough key parameters");
RSAParameters param = new RSAParameters ();
// note: MUST remove leading 0 - else MS wont import the key
param.Modulus = RemoveLeadingZero (privateKey [1].Value);
int keysize = param.Modulus.Length;
int keysize2 = (keysize >> 1); // half-size
// size must be normalized - else MS wont import the key
param.D = Normalize (privateKey [3].Value, keysize);
param.DP = Normalize (privateKey [6].Value, keysize2);
param.DQ = Normalize (privateKey [7].Value, keysize2);
param.Exponent = RemoveLeadingZero (privateKey [2].Value);
param.InverseQ = Normalize (privateKey [8].Value, keysize2);
param.P = Normalize (privateKey [4].Value, keysize2);
param.Q = Normalize (privateKey [5].Value, keysize2);
RSA rsa = null;
try {
rsa = RSA.Create ();
rsa.ImportParameters (param);
}
catch (CryptographicException) {
#if MONOTOUCH
// there's no machine-wide store available for iOS so we can drop the dependency on
// CspParameters (which drops other things, like XML key persistance, unless used elsewhere)
throw;
#else
// this may cause problem when this code is run under
// the SYSTEM identity on Windows (e.g. ASP.NET). See
// http://bugzilla.ximian.com/show_bug.cgi?id=77559
CspParameters csp = new CspParameters ();
csp.Flags = CspProviderFlags.UseMachineKeyStore;
rsa = new RSACryptoServiceProvider (csp);
rsa.ImportParameters (param);
#endif
}
return rsa;
}
/*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*/
static public byte[] Encode (RSA rsa)
{
RSAParameters param = rsa.ExportParameters (true);
ASN1 rsaPrivateKey = new ASN1 (0x30);
rsaPrivateKey.Add (new ASN1 (0x02, new byte [1] { 0x00 }));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Modulus));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Exponent));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.D));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.P));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Q));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DP));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DQ));
rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.InverseQ));
return rsaPrivateKey.GetBytes ();
}
// DSA only encode it's X private key inside an ASN.1 INTEGER (Hint: Tag == 0x02)
// which isn't enough for rebuilding the keypair. The other parameters
// can be found (98% of the time) in the X.509 certificate associated
// with the private key or (2% of the time) the parameters are in it's
// issuer X.509 certificate (not supported in the .NET framework).
static public DSA DecodeDSA (byte[] privateKey, DSAParameters dsaParameters)
{
ASN1 pvk = new ASN1 (privateKey);
if (pvk.Tag != 0x02)
throw new CryptographicException ("invalid private key format");
// X is ALWAYS 20 bytes (no matter if the key length is 512 or 1024 bits)
dsaParameters.X = Normalize (pvk.Value, 20);
DSA dsa = DSA.Create ();
dsa.ImportParameters (dsaParameters);
return dsa;
}
static public byte[] Encode (DSA dsa)
{
DSAParameters param = dsa.ExportParameters (true);
return ASN1Convert.FromUnsignedBigInteger (param.X).GetBytes ();
}
static public byte[] Encode (AsymmetricAlgorithm aa)
{
if (aa is RSA)
return Encode ((RSA)aa);
else if (aa is DSA)
return Encode ((DSA)aa);
else
throw new CryptographicException ("Unknown asymmetric algorithm {0}", aa.ToString ());
}
}
/*
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm EncryptionAlgorithmIdentifier,
* encryptedData EncryptedData
* }
*
* EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
*
* EncryptedData ::= OCTET STRING
*
* --
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
*
* -- from PKCS#5
* PBEParameter ::= SEQUENCE {
* salt OCTET STRING SIZE(8),
* iterationCount INTEGER
* }
*/
public class EncryptedPrivateKeyInfo {
private string _algorithm;
private byte[] _salt;
private int _iterations;
private byte[] _data;
public EncryptedPrivateKeyInfo () {}
public EncryptedPrivateKeyInfo (byte[] data) : this ()
{
Decode (data);
}
// properties
public string Algorithm {
get { return _algorithm; }
set { _algorithm = value; }
}
public byte[] EncryptedData {
get { return (_data == null) ? null : (byte[]) _data.Clone (); }
set { _data = (value == null) ? null : (byte[]) value.Clone (); }
}
public byte[] Salt {
get {
if (_salt == null) {
RandomNumberGenerator rng = RandomNumberGenerator.Create ();
_salt = new byte [8];
rng.GetBytes (_salt);
}
return (byte[]) _salt.Clone ();
}
set { _salt = (byte[]) value.Clone (); }
}
public int IterationCount {
get { return _iterations; }
set {
if (value < 0)
throw new ArgumentOutOfRangeException ("IterationCount", "Negative");
_iterations = value;
}
}
// methods
private void Decode (byte[] data)
{
ASN1 encryptedPrivateKeyInfo = new ASN1 (data);
if (encryptedPrivateKeyInfo.Tag != 0x30)
throw new CryptographicException ("invalid EncryptedPrivateKeyInfo");
ASN1 encryptionAlgorithm = encryptedPrivateKeyInfo [0];
if (encryptionAlgorithm.Tag != 0x30)
throw new CryptographicException ("invalid encryptionAlgorithm");
ASN1 algorithm = encryptionAlgorithm [0];
if (algorithm.Tag != 0x06)
throw new CryptographicException ("invalid algorithm");
_algorithm = ASN1Convert.ToOid (algorithm);
// parameters ANY DEFINED BY algorithm OPTIONAL
if (encryptionAlgorithm.Count > 1) {
ASN1 parameters = encryptionAlgorithm [1];
if (parameters.Tag != 0x30)
throw new CryptographicException ("invalid parameters");
ASN1 salt = parameters [0];
if (salt.Tag != 0x04)
throw new CryptographicException ("invalid salt");
_salt = salt.Value;
ASN1 iterationCount = parameters [1];
if (iterationCount.Tag != 0x02)
throw new CryptographicException ("invalid iterationCount");
_iterations = ASN1Convert.ToInt32 (iterationCount);
}
ASN1 encryptedData = encryptedPrivateKeyInfo [1];
if (encryptedData.Tag != 0x04)
throw new CryptographicException ("invalid EncryptedData");
_data = encryptedData.Value;
}
// Note: PKCS#8 doesn't define how to generate the key required for encryption
// so you're on your own. Just don't try to copy the big guys too much ;)
// Netscape: http://www.cs.auckland.ac.nz/~pgut001/pubs/netscape.txt
// Microsoft: http://www.cs.auckland.ac.nz/~pgut001/pubs/breakms.txt
public byte[] GetBytes ()
{
if (_algorithm == null)
throw new CryptographicException ("No algorithm OID specified");
ASN1 encryptionAlgorithm = new ASN1 (0x30);
encryptionAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
// parameters ANY DEFINED BY algorithm OPTIONAL
if ((_iterations > 0) || (_salt != null)) {
ASN1 salt = new ASN1 (0x04, _salt);
ASN1 iterations = ASN1Convert.FromInt32 (_iterations);
ASN1 parameters = new ASN1 (0x30);
parameters.Add (salt);
parameters.Add (iterations);
encryptionAlgorithm.Add (parameters);
}
// encapsulates EncryptedData into an OCTET STRING
ASN1 encryptedData = new ASN1 (0x04, _data);
ASN1 encryptedPrivateKeyInfo = new ASN1 (0x30);
encryptedPrivateKeyInfo.Add (encryptionAlgorithm);
encryptedPrivateKeyInfo.Add (encryptedData);
return encryptedPrivateKeyInfo.GetBytes ();
}
}
}
}
| |
using System;
using BEPUphysics.Entities;
using BEPUutilities;
using System.Diagnostics;
namespace BEPUphysics.Constraints.TwoEntity.Joints
{
/// <summary>
/// Connects two entities with a spherical joint. Acts like an unrestricted shoulder joint.
/// </summary>
public class BallSocketJoint : Joint, I3DImpulseConstraintWithError, I3DJacobianConstraint
{
private Vector3 accumulatedImpulse;
private Vector3 biasVelocity;
private Vector3 localAnchorA;
private Vector3 localAnchorB;
private Matrix3x3 massMatrix;
private Vector3 error;
private Matrix3x3 rACrossProduct;
private Matrix3x3 rBCrossProduct;
private Vector3 worldOffsetA, worldOffsetB;
/// <summary>
/// Constructs a spherical joint.
/// To finish the initialization, specify the connections (ConnectionA and ConnectionB)
/// as well as the offsets (OffsetA, OffsetB or LocalOffsetA, LocalOffsetB).
/// This constructor sets the constraint's IsActive property to false by default.
/// </summary>
public BallSocketJoint()
{
IsActive = false;
}
/// <summary>
/// Constructs a spherical joint.
/// </summary>
/// <param name="connectionA">First connected entity.</param>
/// <param name="connectionB">Second connected entity.</param>
/// <param name="anchorLocation">Location of the socket.</param>
public BallSocketJoint(Entity connectionA, Entity connectionB, Vector3 anchorLocation)
{
ConnectionA = connectionA;
ConnectionB = connectionB;
OffsetA = anchorLocation - ConnectionA.position;
OffsetB = anchorLocation - ConnectionB.position;
}
/// <summary>
/// Gets or sets the offset from the first entity's center of mass to the anchor point in its local space.
/// </summary>
public Vector3 LocalOffsetA
{
get { return localAnchorA; }
set
{
localAnchorA = value;
Matrix3x3.Transform(ref localAnchorA, ref connectionA.orientationMatrix, out worldOffsetA);
}
}
/// <summary>
/// Gets or sets the offset from the second entity's center of mass to the anchor point in its local space.
/// </summary>
public Vector3 LocalOffsetB
{
get { return localAnchorB; }
set
{
localAnchorB = value;
Matrix3x3.Transform(ref localAnchorB, ref connectionB.orientationMatrix, out worldOffsetB);
}
}
/// <summary>
/// Gets or sets the offset from the first entity's center of mass to the anchor point in world space.
/// </summary>
public Vector3 OffsetA
{
get { return worldOffsetA; }
set
{
worldOffsetA = value;
Matrix3x3.TransformTranspose(ref worldOffsetA, ref connectionA.orientationMatrix, out localAnchorA);
}
}
/// <summary>
/// Gets or sets the offset from the second entity's center of mass to the anchor point in world space.
/// </summary>
public Vector3 OffsetB
{
get { return worldOffsetB; }
set
{
worldOffsetB = value;
Matrix3x3.TransformTranspose(ref worldOffsetB, ref connectionB.orientationMatrix, out localAnchorB);
}
}
#region I3DImpulseConstraintWithError Members
/// <summary>
/// Gets the current relative velocity between the connected entities with respect to the constraint.
/// </summary>
public Vector3 RelativeVelocity
{
get
{
Vector3 cross;
Vector3 aVel, bVel;
Vector3.Cross(ref connectionA.angularVelocity, ref worldOffsetA, out cross);
Vector3.Add(ref connectionA.linearVelocity, ref cross, out aVel);
Vector3.Cross(ref connectionB.angularVelocity, ref worldOffsetB, out cross);
Vector3.Add(ref connectionB.linearVelocity, ref cross, out bVel);
return aVel - bVel;
}
}
/// <summary>
/// Gets the total impulse applied by this constraint.
/// </summary>
public Vector3 TotalImpulse
{
get { return accumulatedImpulse; }
}
/// <summary>
/// Gets the current constraint error.
/// </summary>
public Vector3 Error
{
get { return error; }
}
#endregion
#region I3DJacobianConstraint Members
/// <summary>
/// Gets the linear jacobian entry for the first connected entity.
/// </summary>
/// <param name="jacobianX">First linear jacobian entry for the first connected entity.</param>
/// <param name="jacobianY">Second linear jacobian entry for the first connected entity.</param>
/// <param name="jacobianZ">Third linear jacobian entry for the first connected entity.</param>
public void GetLinearJacobianA(out Vector3 jacobianX, out Vector3 jacobianY, out Vector3 jacobianZ)
{
jacobianX = Toolbox.RightVector;
jacobianY = Toolbox.UpVector;
jacobianZ = Toolbox.BackVector;
}
/// <summary>
/// Gets the linear jacobian entry for the second connected entity.
/// </summary>
/// <param name="jacobianX">First linear jacobian entry for the second connected entity.</param>
/// <param name="jacobianY">Second linear jacobian entry for the second connected entity.</param>
/// <param name="jacobianZ">Third linear jacobian entry for the second connected entity.</param>
public void GetLinearJacobianB(out Vector3 jacobianX, out Vector3 jacobianY, out Vector3 jacobianZ)
{
jacobianX = Toolbox.RightVector;
jacobianY = Toolbox.UpVector;
jacobianZ = Toolbox.BackVector;
}
/// <summary>
/// Gets the angular jacobian entry for the first connected entity.
/// </summary>
/// <param name="jacobianX">First angular jacobian entry for the first connected entity.</param>
/// <param name="jacobianY">Second angular jacobian entry for the first connected entity.</param>
/// <param name="jacobianZ">Third angular jacobian entry for the first connected entity.</param>
public void GetAngularJacobianA(out Vector3 jacobianX, out Vector3 jacobianY, out Vector3 jacobianZ)
{
jacobianX = rACrossProduct.Right;
jacobianY = rACrossProduct.Up;
jacobianZ = rACrossProduct.Forward;
}
/// <summary>
/// Gets the angular jacobian entry for the second connected entity.
/// </summary>
/// <param name="jacobianX">First angular jacobian entry for the second connected entity.</param>
/// <param name="jacobianY">Second angular jacobian entry for the second connected entity.</param>
/// <param name="jacobianZ">Third angular jacobian entry for the second connected entity.</param>
public void GetAngularJacobianB(out Vector3 jacobianX, out Vector3 jacobianY, out Vector3 jacobianZ)
{
jacobianX = rBCrossProduct.Right;
jacobianY = rBCrossProduct.Up;
jacobianZ = rBCrossProduct.Forward;
}
/// <summary>
/// Gets the mass matrix of the constraint.
/// </summary>
/// <param name="outputMassMatrix">Constraint's mass matrix.</param>
public void GetMassMatrix(out Matrix3x3 outputMassMatrix)
{
outputMassMatrix = massMatrix;
}
#endregion
/// <summary>
/// Calculates necessary information for velocity solving.
/// Called by preStep(float dt)
/// </summary>
/// <param name="dt">Time in seconds since the last update.</param>
public override void Update(float dt)
{
Matrix3x3.Transform(ref localAnchorA, ref connectionA.orientationMatrix, out worldOffsetA);
Matrix3x3.Transform(ref localAnchorB, ref connectionB.orientationMatrix, out worldOffsetB);
float errorReductionParameter;
springSettings.ComputeErrorReductionAndSoftness(dt, 1 / dt, out errorReductionParameter, out softness);
//Mass Matrix
Matrix3x3 k;
Matrix3x3 linearComponent;
Matrix3x3.CreateCrossProduct(ref worldOffsetA, out rACrossProduct);
Matrix3x3.CreateCrossProduct(ref worldOffsetB, out rBCrossProduct);
if (connectionA.isDynamic && connectionB.isDynamic)
{
Matrix3x3.CreateScale(connectionA.inverseMass + connectionB.inverseMass, out linearComponent);
Matrix3x3 angularComponentA, angularComponentB;
Matrix3x3.Multiply(ref rACrossProduct, ref connectionA.inertiaTensorInverse, out angularComponentA);
Matrix3x3.Multiply(ref rBCrossProduct, ref connectionB.inertiaTensorInverse, out angularComponentB);
Matrix3x3.Multiply(ref angularComponentA, ref rACrossProduct, out angularComponentA);
Matrix3x3.Multiply(ref angularComponentB, ref rBCrossProduct, out angularComponentB);
Matrix3x3.Subtract(ref linearComponent, ref angularComponentA, out k);
Matrix3x3.Subtract(ref k, ref angularComponentB, out k);
}
else if (connectionA.isDynamic && !connectionB.isDynamic)
{
Matrix3x3.CreateScale(connectionA.inverseMass, out linearComponent);
Matrix3x3 angularComponentA;
Matrix3x3.Multiply(ref rACrossProduct, ref connectionA.inertiaTensorInverse, out angularComponentA);
Matrix3x3.Multiply(ref angularComponentA, ref rACrossProduct, out angularComponentA);
Matrix3x3.Subtract(ref linearComponent, ref angularComponentA, out k);
}
else if (!connectionA.isDynamic && connectionB.isDynamic)
{
Matrix3x3.CreateScale(connectionB.inverseMass, out linearComponent);
Matrix3x3 angularComponentB;
Matrix3x3.Multiply(ref rBCrossProduct, ref connectionB.inertiaTensorInverse, out angularComponentB);
Matrix3x3.Multiply(ref angularComponentB, ref rBCrossProduct, out angularComponentB);
Matrix3x3.Subtract(ref linearComponent, ref angularComponentB, out k);
}
else
{
throw new InvalidOperationException("Cannot constrain two kinematic bodies.");
}
k.M11 += softness;
k.M22 += softness;
k.M33 += softness;
Matrix3x3.Invert(ref k, out massMatrix);
Vector3.Add(ref connectionB.position, ref worldOffsetB, out error);
Vector3.Subtract(ref error, ref connectionA.position, out error);
Vector3.Subtract(ref error, ref worldOffsetA, out error);
Vector3.Multiply(ref error, -errorReductionParameter, out biasVelocity);
//Ensure that the corrective velocity doesn't exceed the max.
float length = biasVelocity.LengthSquared();
if (length > maxCorrectiveVelocitySquared)
{
float multiplier = maxCorrectiveVelocity / (float)Math.Sqrt(length);
biasVelocity.X *= multiplier;
biasVelocity.Y *= multiplier;
biasVelocity.Z *= multiplier;
}
}
/// <summary>
/// Performs any pre-solve iteration work that needs exclusive
/// access to the members of the solver updateable.
/// Usually, this is used for applying warmstarting impulses.
/// </summary>
public override void ExclusiveUpdate()
{
//Warm starting
//Constraint.applyImpulse(myConnectionA, myConnectionB, ref rA, ref rB, ref accumulatedImpulse);
#if !WINDOWS
Vector3 linear = new Vector3();
#else
Vector3 linear;
#endif
if (connectionA.isDynamic)
{
linear.X = -accumulatedImpulse.X;
linear.Y = -accumulatedImpulse.Y;
linear.Z = -accumulatedImpulse.Z;
connectionA.ApplyLinearImpulse(ref linear);
Vector3 taImpulse;
Vector3.Cross(ref worldOffsetA, ref linear, out taImpulse);
connectionA.ApplyAngularImpulse(ref taImpulse);
}
if (connectionB.isDynamic)
{
connectionB.ApplyLinearImpulse(ref accumulatedImpulse);
Vector3 tbImpulse;
Vector3.Cross(ref worldOffsetB, ref accumulatedImpulse, out tbImpulse);
connectionB.ApplyAngularImpulse(ref tbImpulse);
}
}
/// <summary>
/// Calculates and applies corrective impulses.
/// Called automatically by space.
/// </summary>
public override float SolveIteration()
{
#if !WINDOWS
Vector3 lambda = new Vector3();
#else
Vector3 lambda;
#endif
//Velocity along the length.
Vector3 cross;
Vector3 aVel, bVel;
Vector3.Cross(ref connectionA.angularVelocity, ref worldOffsetA, out cross);
Vector3.Add(ref connectionA.linearVelocity, ref cross, out aVel);
Vector3.Cross(ref connectionB.angularVelocity, ref worldOffsetB, out cross);
Vector3.Add(ref connectionB.linearVelocity, ref cross, out bVel);
lambda.X = aVel.X - bVel.X + biasVelocity.X - softness * accumulatedImpulse.X;
lambda.Y = aVel.Y - bVel.Y + biasVelocity.Y - softness * accumulatedImpulse.Y;
lambda.Z = aVel.Z - bVel.Z + biasVelocity.Z - softness * accumulatedImpulse.Z;
//Turn the velocity into an impulse.
Matrix3x3.Transform(ref lambda, ref massMatrix, out lambda);
//ACcumulate the impulse
Vector3.Add(ref accumulatedImpulse, ref lambda, out accumulatedImpulse);
//Apply the impulse
//Constraint.applyImpulse(myConnectionA, myConnectionB, ref rA, ref rB, ref impulse);
#if !WINDOWS
Vector3 linear = new Vector3();
#else
Vector3 linear;
#endif
if (connectionA.isDynamic)
{
linear.X = -lambda.X;
linear.Y = -lambda.Y;
linear.Z = -lambda.Z;
connectionA.ApplyLinearImpulse(ref linear);
Vector3 taImpulse;
Vector3.Cross(ref worldOffsetA, ref linear, out taImpulse);
connectionA.ApplyAngularImpulse(ref taImpulse);
}
if (connectionB.isDynamic)
{
connectionB.ApplyLinearImpulse(ref lambda);
Vector3 tbImpulse;
Vector3.Cross(ref worldOffsetB, ref lambda, out tbImpulse);
connectionB.ApplyAngularImpulse(ref tbImpulse);
}
return (Math.Abs(lambda.X) +
Math.Abs(lambda.Y) +
Math.Abs(lambda.Z));
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Collections.Immutable
{
/// <summary>
/// A node in the AVL tree storing key/value pairs with Int32 keys.
/// </summary>
/// <remarks>
/// This is a trimmed down version of <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/>
/// with <c>TKey</c> fixed to be <see cref="int"/>. This avoids multiple interface-based dispatches while examining
/// each node in the tree during a lookup: an interface call to the comparer's <see cref="IComparer{T}.Compare"/> method,
/// and then an interface call to <see cref="int"/>'s <see cref="IComparable{T}.CompareTo"/> method as part of
/// the <see cref="T:System.Collections.Generic.GenericComparer`1"/>'s <see cref="IComparer{T}.Compare"/> implementation.
/// </remarks>
[DebuggerDisplay("{_key} = {_value}")]
internal sealed class SortedInt32KeyNode<TValue> : IBinaryTree
{
/// <summary>
/// The default empty node.
/// </summary>
internal static readonly SortedInt32KeyNode<TValue> EmptyNode = new SortedInt32KeyNode<TValue>();
/// <summary>
/// The Int32 key associated with this node.
/// </summary>
private readonly int _key;
/// <summary>
/// The value associated with this node.
/// </summary>
/// <remarks>
/// Sadly, this field could be readonly but doing so breaks serialization due to bug:
/// http://connect.microsoft.com/VisualStudio/feedback/details/312970/weird-argumentexception-when-deserializing-field-in-typedreferences-cannot-be-static-or-init-only
/// </remarks>
private TValue _value;
/// <summary>
/// A value indicating whether this node has been frozen (made immutable).
/// </summary>
/// <remarks>
/// Nodes must be frozen before ever being observed by a wrapping collection type
/// to protect collections from further mutations.
/// </remarks>
private bool _frozen;
/// <summary>
/// The depth of the tree beneath this node.
/// </summary>
private byte _height; // AVL tree height <= ~1.44 * log2(numNodes + 2)
/// <summary>
/// The left tree.
/// </summary>
private SortedInt32KeyNode<TValue> _left;
/// <summary>
/// The right tree.
/// </summary>
private SortedInt32KeyNode<TValue> _right;
/// <summary>
/// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is pre-frozen.
/// </summary>
private SortedInt32KeyNode()
{
_frozen = true; // the empty node is *always* frozen.
}
/// <summary>
/// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is not yet frozen.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <param name="frozen">Whether this node is prefrozen.</param>
private SortedInt32KeyNode(int key, TValue value, SortedInt32KeyNode<TValue> left, SortedInt32KeyNode<TValue> right, bool frozen = false)
{
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
_key = key;
_value = value;
_left = left;
_right = right;
_frozen = frozen;
_height = checked((byte)(1 + Math.Max(left._height, right._height)));
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty { get { return _left == null; } }
/// <summary>
/// Gets the height of the tree beneath this node.
/// </summary>
public int Height { get { return _height; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
public SortedInt32KeyNode<TValue> Left { get { return _left; } }
/// <summary>
/// Gets the right branch of this node.
/// </summary>
public SortedInt32KeyNode<TValue> Right { get { return _right; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Left { get { return _left; } }
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Right { get { return _right; } }
/// <summary>
/// Gets the number of elements contained by this node and below.
/// </summary>
int IBinaryTree.Count
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the value represented by the current node.
/// </summary>
public KeyValuePair<int, TValue> Value
{
get { return new KeyValuePair<int, TValue>(_key, _value); }
}
/// <summary>
/// Gets the values.
/// </summary>
internal IEnumerable<TValue> Values
{
get
{
foreach (var pair in this)
{
yield return pair.Value;
}
}
}
/// <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(this);
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
internal SortedInt32KeyNode<TValue> SetItem(int key, TValue value, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated)
{
Requires.NotNull(valueComparer, nameof(valueComparer));
return this.SetOrAdd(key, value, valueComparer, true, out replacedExistingValue, out mutated);
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
internal SortedInt32KeyNode<TValue> Remove(int key, out bool mutated)
{
return this.RemoveRecursive(key, out mutated);
}
/// <summary>
/// Gets the value or default.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The value.</returns>
[Pure]
internal TValue GetValueOrDefault(int key)
{
var match = this.Search(key);
return match.IsEmpty ? default(TValue) : match._value;
}
/// <summary>
/// Tries to get the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>True if the key was found.</returns>
[Pure]
internal bool TryGetValue(int key, out TValue value)
{
var match = this.Search(key);
if (match.IsEmpty)
{
value = default(TValue);
return false;
}
else
{
value = match._value;
return true;
}
}
/// <summary>
/// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes.
/// </summary>
internal void Freeze(Action<KeyValuePair<int, TValue>> freezeAction = null)
{
// If this node is frozen, all its descendants must already be frozen.
if (!_frozen)
{
if (freezeAction != null)
{
freezeAction(new KeyValuePair<int, TValue>(_key, _value));
}
_left.Freeze(freezeAction);
_right.Freeze(freezeAction);
_frozen = true;
}
}
/// <summary>
/// AVL rotate left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static SortedInt32KeyNode<TValue> RotateLeft(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._right.IsEmpty)
{
return tree;
}
var right = tree._right;
return right.Mutate(left: tree.Mutate(right: right._left));
}
/// <summary>
/// AVL rotate right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static SortedInt32KeyNode<TValue> RotateRight(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._left.IsEmpty)
{
return tree;
}
var left = tree._left;
return left.Mutate(right: tree.Mutate(left: left._right));
}
/// <summary>
/// AVL rotate double-left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static SortedInt32KeyNode<TValue> DoubleLeft(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._right.IsEmpty)
{
return tree;
}
SortedInt32KeyNode<TValue> rotatedRightChild = tree.Mutate(right: RotateRight(tree._right));
return RotateLeft(rotatedRightChild);
}
/// <summary>
/// AVL rotate double-right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static SortedInt32KeyNode<TValue> DoubleRight(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._left.IsEmpty)
{
return tree;
}
SortedInt32KeyNode<TValue> rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left));
return RotateRight(rotatedLeftChild);
}
/// <summary>
/// Returns a value indicating whether the tree is in balance.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns>
[Pure]
private static int Balance(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return tree._right._height - tree._left._height;
}
/// <summary>
/// Determines whether the specified tree is right heavy.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>
/// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>.
/// </returns>
[Pure]
private static bool IsRightHeavy(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) >= 2;
}
/// <summary>
/// Determines whether the specified tree is left heavy.
/// </summary>
[Pure]
private static bool IsLeftHeavy(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) <= -2;
}
/// <summary>
/// Balances the specified tree.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>A balanced tree.</returns>
[Pure]
private static SortedInt32KeyNode<TValue> MakeBalanced(SortedInt32KeyNode<TValue> tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (IsRightHeavy(tree))
{
return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree);
}
if (IsLeftHeavy(tree))
{
return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree);
}
return tree;
}
/// <summary>
/// Adds the specified key. Callers are expected to have validated arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private SortedInt32KeyNode<TValue> SetOrAdd(int key, TValue value, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated)
{
// Arg validation skipped in this private method because it's recursive and the tax
// of revalidating arguments on each recursive call is significant.
// All our callers are therefore required to have done input validation.
replacedExistingValue = false;
if (this.IsEmpty)
{
mutated = true;
return new SortedInt32KeyNode<TValue>(key, value, this, this);
}
else
{
SortedInt32KeyNode<TValue> result = this;
if (key > _key)
{
var newRight = _right.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
else if (key < _key)
{
var newLeft = _left.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
if (valueComparer.Equals(_value, value))
{
mutated = false;
return this;
}
else if (overwriteExistingValue)
{
mutated = true;
replacedExistingValue = true;
result = new SortedInt32KeyNode<TValue>(key, value, _left, _right);
}
else
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
}
}
return mutated ? MakeBalanced(result) : result;
}
}
/// <summary>
/// Removes the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private SortedInt32KeyNode<TValue> RemoveRecursive(int key, out bool mutated)
{
if (this.IsEmpty)
{
mutated = false;
return this;
}
else
{
SortedInt32KeyNode<TValue> result = this;
if (key == _key)
{
// We have a match.
mutated = true;
// If this is a leaf, just remove it
// by returning Empty. If we have only one child,
// replace the node with the child.
if (_right.IsEmpty && _left.IsEmpty)
{
result = EmptyNode;
}
else if (_right.IsEmpty && !_left.IsEmpty)
{
result = _left;
}
else if (!_right.IsEmpty && _left.IsEmpty)
{
result = _right;
}
else
{
// We have two children. Remove the next-highest node and replace
// this node with it.
var successor = _right;
while (!successor._left.IsEmpty)
{
successor = successor._left;
}
bool dummyMutated;
var newRight = _right.Remove(successor._key, out dummyMutated);
result = successor.Mutate(left: _left, right: newRight);
}
}
else if (key < _key)
{
var newLeft = _left.Remove(key, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
var newRight = _right.Remove(key, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
return result.IsEmpty ? result : MakeBalanced(result);
}
}
/// <summary>
/// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node
/// with the described changes.
/// </summary>
/// <param name="left">The left branch of the mutated node.</param>
/// <param name="right">The right branch of the mutated node.</param>
/// <returns>The mutated (or created) node.</returns>
private SortedInt32KeyNode<TValue> Mutate(SortedInt32KeyNode<TValue> left = null, SortedInt32KeyNode<TValue> right = null)
{
if (_frozen)
{
return new SortedInt32KeyNode<TValue>(_key, _value, left ?? _left, right ?? _right);
}
else
{
if (left != null)
{
_left = left;
}
if (right != null)
{
_right = right;
}
_height = checked((byte)(1 + Math.Max(_left._height, _right._height)));
return this;
}
}
/// <summary>
/// Searches the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
[Pure]
private SortedInt32KeyNode<TValue> Search(int key)
{
if (this.IsEmpty || key == _key)
{
return this;
}
if (key > _key)
{
return _right.Search(key);
}
return _left.Search(key);
}
/// <summary>
/// Enumerates the contents of a binary tree.
/// </summary>
/// <remarks>
/// This struct can and should be kept in exact sync with the other binary tree enumerators:
/// <see cref="ImmutableList{T}.Enumerator"/>, <see cref="ImmutableSortedDictionary{TKey, TValue}.Enumerator"/>, and <see cref="ImmutableSortedSet{T}.Enumerator"/>.
///
/// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable
/// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool,
/// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk
/// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data
/// corruption and/or exceptions.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public struct Enumerator : IEnumerator<KeyValuePair<int, TValue>>, ISecurePooledObjectUser
{
/// <summary>
/// The resource pool of reusable mutable stacks for purposes of enumeration.
/// </summary>
/// <remarks>
/// We utilize this resource pool to make "allocation free" enumeration achievable.
/// </remarks>
private static readonly SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator> s_enumeratingStacks =
new SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator>();
/// <summary>
/// A unique ID for this instance of this enumerator.
/// Used to protect pooled objects from use after they are recycled.
/// </summary>
private readonly int _poolUserId;
/// <summary>
/// The set being enumerated.
/// </summary>
private SortedInt32KeyNode<TValue> _root;
/// <summary>
/// The stack to use for enumerating the binary tree.
/// </summary>
private SecurePooledObject<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>> _stack;
/// <summary>
/// The node currently selected.
/// </summary>
private SortedInt32KeyNode<TValue> _current;
/// <summary>
/// Initializes an <see cref="Enumerator"/> structure.
/// </summary>
/// <param name="root">The root of the set to be enumerated.</param>
internal Enumerator(SortedInt32KeyNode<TValue> root)
{
Requires.NotNull(root, nameof(root));
_root = root;
_current = null;
_poolUserId = SecureObjectPool.NewId();
_stack = null;
if (!_root.IsEmpty)
{
if (!s_enumeratingStacks.TryTake(this, out _stack))
{
_stack = s_enumeratingStacks.PrepNew(this, new Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>(root.Height));
}
this.PushLeft(_root);
}
}
/// <summary>
/// The current element.
/// </summary>
public KeyValuePair<int, TValue> Current
{
get
{
this.ThrowIfDisposed();
if (_current != null)
{
return _current.Value;
}
throw new InvalidOperationException();
}
}
/// <inheritdoc/>
int ISecurePooledObjectUser.PoolUserId
{
get { return _poolUserId; }
}
/// <summary>
/// The current element.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Disposes of this enumerator and returns the stack reference to the resource pool.
/// </summary>
public void Dispose()
{
_root = null;
_current = null;
Stack<RefAsValueType<SortedInt32KeyNode<TValue>>> stack;
if (_stack != null && _stack.TryUse(ref this, out stack))
{
stack.ClearFastWhenEmpty();
s_enumeratingStacks.TryAdd(this, _stack);
}
_stack = null;
}
/// <summary>
/// Advances enumeration to the next element.
/// </summary>
/// <returns>A value indicating whether there is another element in the enumeration.</returns>
public bool MoveNext()
{
this.ThrowIfDisposed();
if (_stack != null)
{
var stack = _stack.Use(ref this);
if (stack.Count > 0)
{
SortedInt32KeyNode<TValue> n = stack.Pop().Value;
_current = n;
this.PushLeft(n.Right);
return true;
}
}
_current = null;
return false;
}
/// <summary>
/// Restarts enumeration.
/// </summary>
public void Reset()
{
this.ThrowIfDisposed();
_current = null;
if (_stack != null)
{
var stack = _stack.Use(ref this);
stack.ClearFastWhenEmpty();
this.PushLeft(_root);
}
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed.
/// </summary>
internal void ThrowIfDisposed()
{
// Since this is a struct, copies might not have been marked as disposed.
// But the stack we share across those copies would know.
// This trick only works when we have a non-null stack.
// For enumerators of empty collections, there isn't any natural
// way to know when a copy of the struct has been disposed of.
if (_root == null || (_stack != null && !_stack.IsOwned(ref this)))
{
Requires.FailObjectDisposed(this);
}
}
/// <summary>
/// Pushes this node and all its Left descendants onto the stack.
/// </summary>
/// <param name="node">The starting node to push onto the stack.</param>
private void PushLeft(SortedInt32KeyNode<TValue> node)
{
Requires.NotNull(node, nameof(node));
var stack = _stack.Use(ref this);
while (!node.IsEmpty)
{
stack.Push(new RefAsValueType<SortedInt32KeyNode<TValue>>(node));
node = node.Left;
}
}
}
}
}
| |
namespace android.text.method
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.text.method.MetaKeyKeyListener_))]
public abstract partial class MetaKeyKeyListener : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static MetaKeyKeyListener()
{
InitJNI();
}
protected MetaKeyKeyListener(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onKeyDown8091;
public virtual bool onKeyDown(android.view.View arg0, android.text.Editable arg1, int arg2, android.view.KeyEvent arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.method.MetaKeyKeyListener._onKeyDown8091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._onKeyDown8091, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _onKeyUp8092;
public virtual bool onKeyUp(android.view.View arg0, android.text.Editable arg1, int arg2, android.view.KeyEvent arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.method.MetaKeyKeyListener._onKeyUp8092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._onKeyUp8092, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _getMetaState8093;
public static int getMetaState(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._getMetaState8093, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getMetaState8094;
public static int getMetaState(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._getMetaState8094, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getMetaState8095;
public static int getMetaState(long arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._getMetaState8095, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getMetaState8096;
public static int getMetaState(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._getMetaState8096, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _clearMetaKeyState8097;
public virtual long clearMetaKeyState(long arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.text.method.MetaKeyKeyListener._clearMetaKeyState8097, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._clearMetaKeyState8097, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _clearMetaKeyState8098;
public virtual void clearMetaKeyState(android.view.View arg0, android.text.Editable arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.method.MetaKeyKeyListener._clearMetaKeyState8098, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._clearMetaKeyState8098, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _clearMetaKeyState8099;
public static void clearMetaKeyState(android.text.Editable arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._clearMetaKeyState8099, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _resetMetaState8100;
public static void resetMetaState(android.text.Spannable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._resetMetaState8100, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _adjustMetaAfterKeypress8101;
public static long adjustMetaAfterKeypress(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticLongMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._adjustMetaAfterKeypress8101, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _adjustMetaAfterKeypress8102;
public static void adjustMetaAfterKeypress(android.text.Spannable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._adjustMetaAfterKeypress8102, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isMetaTracker8103;
public static bool isMetaTracker(java.lang.CharSequence arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._isMetaTracker8103, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _isSelectingMetaTracker8104;
public static bool isSelectingMetaTracker(java.lang.CharSequence arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._isSelectingMetaTracker8104, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _resetLockedMeta8105;
protected static void resetLockedMeta(android.text.Spannable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._resetLockedMeta8105, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _resetLockedMeta8106;
public static long resetLockedMeta(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticLongMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._resetLockedMeta8106, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _handleKeyDown8107;
public static long handleKeyDown(long arg0, int arg1, android.view.KeyEvent arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticLongMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._handleKeyDown8107, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _handleKeyUp8108;
public static long handleKeyUp(long arg0, int arg1, android.view.KeyEvent arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticLongMethod(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._handleKeyUp8108, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _MetaKeyKeyListener8109;
public MetaKeyKeyListener() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.method.MetaKeyKeyListener.staticClass, global::android.text.method.MetaKeyKeyListener._MetaKeyKeyListener8109);
Init(@__env, handle);
}
public static int META_SHIFT_ON
{
get
{
return 1;
}
}
public static int META_ALT_ON
{
get
{
return 2;
}
}
public static int META_SYM_ON
{
get
{
return 4;
}
}
public static int META_CAP_LOCKED
{
get
{
return 256;
}
}
public static int META_ALT_LOCKED
{
get
{
return 512;
}
}
public static int META_SYM_LOCKED
{
get
{
return 1024;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.method.MetaKeyKeyListener.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/method/MetaKeyKeyListener"));
global::android.text.method.MetaKeyKeyListener._onKeyDown8091 = @__env.GetMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "onKeyDown", "(Landroid/view/View;Landroid/text/Editable;ILandroid/view/KeyEvent;)Z");
global::android.text.method.MetaKeyKeyListener._onKeyUp8092 = @__env.GetMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "onKeyUp", "(Landroid/view/View;Landroid/text/Editable;ILandroid/view/KeyEvent;)Z");
global::android.text.method.MetaKeyKeyListener._getMetaState8093 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "getMetaState", "(Ljava/lang/CharSequence;)I");
global::android.text.method.MetaKeyKeyListener._getMetaState8094 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "getMetaState", "(Ljava/lang/CharSequence;I)I");
global::android.text.method.MetaKeyKeyListener._getMetaState8095 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "getMetaState", "(JI)I");
global::android.text.method.MetaKeyKeyListener._getMetaState8096 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "getMetaState", "(J)I");
global::android.text.method.MetaKeyKeyListener._clearMetaKeyState8097 = @__env.GetMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "clearMetaKeyState", "(JI)J");
global::android.text.method.MetaKeyKeyListener._clearMetaKeyState8098 = @__env.GetMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "clearMetaKeyState", "(Landroid/view/View;Landroid/text/Editable;I)V");
global::android.text.method.MetaKeyKeyListener._clearMetaKeyState8099 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "clearMetaKeyState", "(Landroid/text/Editable;I)V");
global::android.text.method.MetaKeyKeyListener._resetMetaState8100 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "resetMetaState", "(Landroid/text/Spannable;)V");
global::android.text.method.MetaKeyKeyListener._adjustMetaAfterKeypress8101 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "adjustMetaAfterKeypress", "(J)J");
global::android.text.method.MetaKeyKeyListener._adjustMetaAfterKeypress8102 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "adjustMetaAfterKeypress", "(Landroid/text/Spannable;)V");
global::android.text.method.MetaKeyKeyListener._isMetaTracker8103 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "isMetaTracker", "(Ljava/lang/CharSequence;Ljava/lang/Object;)Z");
global::android.text.method.MetaKeyKeyListener._isSelectingMetaTracker8104 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "isSelectingMetaTracker", "(Ljava/lang/CharSequence;Ljava/lang/Object;)Z");
global::android.text.method.MetaKeyKeyListener._resetLockedMeta8105 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "resetLockedMeta", "(Landroid/text/Spannable;)V");
global::android.text.method.MetaKeyKeyListener._resetLockedMeta8106 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "resetLockedMeta", "(J)J");
global::android.text.method.MetaKeyKeyListener._handleKeyDown8107 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "handleKeyDown", "(JILandroid/view/KeyEvent;)J");
global::android.text.method.MetaKeyKeyListener._handleKeyUp8108 = @__env.GetStaticMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "handleKeyUp", "(JILandroid/view/KeyEvent;)J");
global::android.text.method.MetaKeyKeyListener._MetaKeyKeyListener8109 = @__env.GetMethodIDNoThrow(global::android.text.method.MetaKeyKeyListener.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.text.method.MetaKeyKeyListener))]
public sealed partial class MetaKeyKeyListener_ : android.text.method.MetaKeyKeyListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static MetaKeyKeyListener_()
{
InitJNI();
}
internal MetaKeyKeyListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.method.MetaKeyKeyListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/method/MetaKeyKeyListener"));
}
}
}
| |
#region
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
#endregion
namespace Highway.Data.Rest.ExampleAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable
/// public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int" />, <see cref="string" />, <see cref="Enum" />, <see cref="DateTime" />,
/// <see cref="Uri" />, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}" />.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}" />
/// Tuples: <see cref="Tuple{T1}" />, <see cref="Tuple{T1,T2}" />, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}" /> or anything deriving from
/// <see cref="IDictionary{TKey,TValue}" />.
/// Collections: <see cref="IList{T}" />, <see cref="IEnumerable{T}" />, <see cref="ICollection{T}" />,
/// <see cref="IList" />, <see cref="IEnumerable" />, <see cref="ICollection" /> or anything deriving from
/// <see cref="ICollection{T}" /> or <see cref="IList" />.
/// Queryables: <see cref="IQueryable" />, <see cref="IQueryable{T}" />.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof (IDictionary))
{
return GenerateDictionary(typeof (Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof (IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof (IList) ||
type == typeof (IEnumerable) ||
type == typeof (ICollection))
{
return GenerateCollection(typeof (ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof (IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof (IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize,
Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof (Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof (KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof (IList<>) ||
genericTypeDefinition == typeof (IEnumerable<>) ||
genericTypeDefinition == typeof (ICollection<>))
{
Type collectionType = typeof (List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof (IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof (ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof (IDictionary<,>))
{
Type dictionaryType = typeof (Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof (IDictionary<,>).MakeGenericType(genericArguments[0],
genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof (Tuple<>) ||
genericTypeDefinition == typeof (Tuple<,>) ||
genericTypeDefinition == typeof (Tuple<,,>) ||
genericTypeDefinition == typeof (Tuple<,,,>) ||
genericTypeDefinition == typeof (Tuple<,,,,>) ||
genericTypeDefinition == typeof (Tuple<,,,,,>) ||
genericTypeDefinition == typeof (Tuple<,,,,,,>) ||
genericTypeDefinition == typeof (Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType,
Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size,
Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof (object);
Type typeV = typeof (object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool) containsMethod.Invoke(result, new[] {newKey});
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new[] {newKey, newValue});
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size,
Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof (List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof (object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof (IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof (Queryable).GetMethod("AsQueryable", new[] {argumentType});
return asQueryableMethod.Invoke(null, new[] {list});
}
return ((IEnumerable) list).AsQueryable();
}
private static object GenerateCollection(Type collectionType, int size,
Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType
? collectionType.GetGenericArguments()[0]
: typeof (object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new[] {element});
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
private long _index;
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity",
Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{typeof (Boolean), index => true},
{typeof (Byte), index => (Byte) 64},
{typeof (Char), index => (Char) 65},
{typeof (DateTime), index => DateTime.Now},
{typeof (DateTimeOffset), index => new DateTimeOffset(DateTime.Now)},
{typeof (DBNull), index => DBNull.Value},
{typeof (Decimal), index => (Decimal) index},
{typeof (Double), index => index + 0.1},
{typeof (Guid), index => Guid.NewGuid()},
{typeof (Int16), index => (Int16) (index%Int16.MaxValue)},
{typeof (Int32), index => (Int32) (index%Int32.MaxValue)},
{typeof (Int64), index => index},
{typeof (Object), index => new object()},
{typeof (SByte), index => (SByte) 64},
{typeof (Single), index => (Single) (index + 0.1)},
{
typeof (String),
index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); }
},
{
typeof (TimeSpan), index => { return TimeSpan.FromTicks(1234567); }
},
{typeof (UInt16), index => (UInt16) (index%UInt16.MaxValue)},
{typeof (UInt32), index => (UInt32) (index%UInt32.MaxValue)},
{typeof (UInt64), index => (UInt64) index},
{
typeof (Uri),
index =>
{
return
new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
#region Using directives
using SimpleFramework.Xml.Stream;
using SimpleFramework.Xml;
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Util {
public class ExampleConverters {
public static class CowConverter : Converter<Cow> {
public Cow Read(InputNode node) {
String name = node.getAttribute("name").Value;
String age = node.getAttribute("age").Value;
return new Cow(name, Integer.parseInt(age));
}
public void Write(OutputNode node, Cow cow) {
node.setAttribute("name", cow.Name);
node.setAttribute("age", String.valueOf(cow.Age));
node.setAttribute("legs", String.valueOf(cow.Legs));
}
}
public static class ChickenConverter : Converter<Chicken> {
public Chicken Read(InputNode node) {
String name = node.getAttribute("name").Value;
String age = node.getAttribute("age").Value;
return new Chicken(name, Integer.parseInt(age));
}
public void Write(OutputNode node, Chicken chicken) {
node.setAttribute("name", chicken.Name);
node.setAttribute("age", String.valueOf(chicken.Age));
node.setAttribute("legs", String.valueOf(chicken.Legs));
}
}
public static class Animal {
private readonly String name;
private readonly int age;
private readonly int legs;
public Animal(String name, int age, int legs) {
this.name = name;
this.legs = legs;
this.age = age;
}
public String Name {
get {
return name;
}
}
//public String GetName() {
// return name;
//}
return age;
}
public int Legs {
get {
return legs;
}
}
//public int GetLegs() {
// return legs;
//}
public static class Chicken : Animal {
public Chicken(String name, int age) {
super(name, age, 2);
}
}
public static class Cow : Animal {
public Cow(String name, int age) {
super(name, age, 4);
}
}
[Root]
[Convert(EntryConverter.class)]
public static class Entry {
private readonly String name;
private readonly String value;
public Entry(String name, String value) {
this.name = name;
this.value = value;
}
public String Name {
get {
return name;
}
}
//public String GetName() {
// return name;
//}
return value;
}
public bool Equals(Object value) {
if(value instanceof Entry) {
return Equals((Entry)value);
}
return false;
}
public bool Equals(Entry entry) {
return entry.name.Equals(name) &&
entry.value.Equals(value);
}
}
[Convert(ExtendedEntryConverter.class)]
public static class ExtendedEntry : Entry {
private readonly int code;
public ExtendedEntry(String name, String value, int code) {
super(name, value);
this.code = code;
}
public int Code {
get {
return code;
}
}
//public int GetCode() {
// return code;
//}
public static class ExtendedEntryConverter : Converter<ExtendedEntry> {
public ExtendedEntry Read(InputNode node) {
String name = node.getAttribute("name").Value;
String value = node.getAttribute("value").Value;
String code = node.getAttribute("code").Value;
return new ExtendedEntry(name, value, Integer.parseInt(code));
}
public void Write(OutputNode node, ExtendedEntry entry) {
node.setAttribute("name", entry.Name);
node.setAttribute("value", entry.Value);
node.setAttribute("code", String.valueOf(entry.Code));
}
}
public static class OtherEntryConverter : Converter<Entry> {
public Entry Read(InputNode node) {
String name = node.getAttribute("name").Value;
String value = node.getAttribute("value").Value;
return new Entry(name, value);
}
public void Write(OutputNode node, Entry entry) {
node.setAttribute("name", entry.Name);
node.setAttribute("value", entry.Value);
}
}
public static class EntryConverter : Converter<Entry> {
public Entry Read(InputNode node) {
String name = node.getNext("name").Value;
String value = node.getNext("value").Value;
return new Entry(name, value);
}
public void Write(OutputNode node, Entry entry) {
node.getChild("name").setValue(entry.Name);
node.getChild("value").setValue(entry.Value);
}
}
public static class EntryListConverter : Converter<List<Entry>> {
private OtherEntryConverter converter = new OtherEntryConverter();
public List<Entry> Read(InputNode node) {
List<Entry> entryList = new ArrayList<Entry>();
while(true) {
InputNode item = node.getNext("entry");
if(item == null) {
break;
}
entryList.add(converter.Read(item));
}
return entryList;
}
public void Write(OutputNode node, List<Entry> entryList) {
for(Entry entry : entryList) {
OutputNode item = node.getChild("entry");
converter.Write(item, entry);
}
}
}
public static class Pet : SimpleFramework.Xml.Util.Entry{
private readonly String name;
private readonly int age;
public Pet(String name, int age){
this.name = name;
this.age = age;
}
public String Name {
get {
return name;
}
}
//public String GetName() {
// return name;
//}
return age;
}
public bool Equals(Object value) {
if(value instanceof Pet) {
return Equals((Pet)value);
}
return false;
}
public bool Equals(Pet pet) {
return pet.name.Equals(name) &&
pet.age == age;
}
}
public static class Cat : Pet{
public Cat(String name, int age) {
super(name, age);
}
}
public static class Dog : Pet{
public Dog(String name, int age) {
super(name, age);
}
}
public static class CatConverter : Converter<Cat>{
private const String ELEMENT_NAME = "name";
private const String ELEMENT_AGE = "age";
public Cat Read(InputNode source) {
int age = 0;
String name = null;
while(true) {
InputNode node = source.getNext();
if(node == null) {
break;
}else if(node.Name.Equals(ELEMENT_NAME)) {
name = node.Value;
}else if(node.Name.Equals(ELEMENT_AGE)){
age = Integer.parseInt(node.Value.trim());
}
}
return new Cat(name, age);
}
public void Write(OutputNode node, Cat cat) {
OutputNode name = node.getChild(ELEMENT_NAME);
name.setValue(cat.Name);
OutputNode age = node.getChild(ELEMENT_AGE);
age.setValue(String.valueOf(cat.Age));
}
}
public static class DogConverter : Converter<Dog>{
private const String ELEMENT_NAME = "name";
private const String ELEMENT_AGE = "age";
public Dog Read(InputNode node) {
String name = node.getAttribute(ELEMENT_NAME).Value;
String age = node.getAttribute(ELEMENT_AGE).Value;
return new Dog(name, Integer.parseInt(age));
}
public void Write(OutputNode node, Dog dog) {
node.setAttribute(ELEMENT_NAME, dog.Name);
node.setAttribute(ELEMENT_AGE, String.valueOf(dog.Age));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Editors;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Mail;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Media;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Email;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure;
using Umbraco.Cms.Infrastructure.Persistence;
using Umbraco.Cms.Web.BackOffice.ActionResults;
using Umbraco.Cms.Web.BackOffice.Extensions;
using Umbraco.Cms.Web.BackOffice.Filters;
using Umbraco.Cms.Web.BackOffice.ModelBinders;
using Umbraco.Cms.Web.BackOffice.Security;
using Umbraco.Cms.Web.Common.ActionsResults;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Cms.Web.Common.DependencyInjection;
using Umbraco.Cms.Web.Common.Security;
using Umbraco.Extensions;
using Constants = Umbraco.Cms.Core.Constants;
namespace Umbraco.Cms.Web.BackOffice.Controllers
{
[PluginController(Constants.Web.Mvc.BackOfficeApiArea)]
[Authorize(Policy = AuthorizationPolicies.SectionAccessUsers)]
[PrefixlessBodyModelValidator]
[IsCurrentUserModelFilter]
public class UsersController : BackOfficeNotificationsController
{
private readonly MediaFileManager _mediaFileManager;
private readonly ContentSettings _contentSettings;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ISqlContext _sqlContext;
private readonly IImageUrlGenerator _imageUrlGenerator;
private readonly SecuritySettings _securitySettings;
private readonly IEmailSender _emailSender;
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly AppCaches _appCaches;
private readonly IShortStringHelper _shortStringHelper;
private readonly IUserService _userService;
private readonly ILocalizedTextService _localizedTextService;
private readonly IUmbracoMapper _umbracoMapper;
private readonly GlobalSettings _globalSettings;
private readonly IBackOfficeUserManager _userManager;
private readonly ILoggerFactory _loggerFactory;
private readonly LinkGenerator _linkGenerator;
private readonly IBackOfficeExternalLoginProviders _externalLogins;
private readonly UserEditorAuthorizationHelper _userEditorAuthorizationHelper;
private readonly IPasswordChanger<BackOfficeIdentityUser> _passwordChanger;
private readonly ILogger<UsersController> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly WebRoutingSettings _webRoutingSettings;
[ActivatorUtilitiesConstructor]
public UsersController(
MediaFileManager mediaFileManager,
IOptions<ContentSettings> contentSettings,
IHostingEnvironment hostingEnvironment,
ISqlContext sqlContext,
IImageUrlGenerator imageUrlGenerator,
IOptions<SecuritySettings> securitySettings,
IEmailSender emailSender,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
AppCaches appCaches,
IShortStringHelper shortStringHelper,
IUserService userService,
ILocalizedTextService localizedTextService,
IUmbracoMapper umbracoMapper,
IOptions<GlobalSettings> globalSettings,
IBackOfficeUserManager backOfficeUserManager,
ILoggerFactory loggerFactory,
LinkGenerator linkGenerator,
IBackOfficeExternalLoginProviders externalLogins,
UserEditorAuthorizationHelper userEditorAuthorizationHelper,
IPasswordChanger<BackOfficeIdentityUser> passwordChanger,
IHttpContextAccessor httpContextAccessor,
IOptions<WebRoutingSettings> webRoutingSettings)
{
_mediaFileManager = mediaFileManager;
_contentSettings = contentSettings.Value;
_hostingEnvironment = hostingEnvironment;
_sqlContext = sqlContext;
_imageUrlGenerator = imageUrlGenerator;
_securitySettings = securitySettings.Value;
_emailSender = emailSender;
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_appCaches = appCaches;
_shortStringHelper = shortStringHelper;
_userService = userService;
_localizedTextService = localizedTextService;
_umbracoMapper = umbracoMapper;
_globalSettings = globalSettings.Value;
_userManager = backOfficeUserManager;
_loggerFactory = loggerFactory;
_linkGenerator = linkGenerator;
_externalLogins = externalLogins;
_userEditorAuthorizationHelper = userEditorAuthorizationHelper;
_passwordChanger = passwordChanger;
_logger = _loggerFactory.CreateLogger<UsersController>();
_httpContextAccessor = httpContextAccessor;
_webRoutingSettings = webRoutingSettings.Value;
}
[Obsolete("Use constructor that also takes IHttpAccessor and IOptions<WebRoutingSettings>, scheduled for removal in V11")]
public UsersController(
MediaFileManager mediaFileManager,
IOptions<ContentSettings> contentSettings,
IHostingEnvironment hostingEnvironment,
ISqlContext sqlContext,
IImageUrlGenerator imageUrlGenerator,
IOptions<SecuritySettings> securitySettings,
IEmailSender emailSender,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
AppCaches appCaches,
IShortStringHelper shortStringHelper,
IUserService userService,
ILocalizedTextService localizedTextService,
IUmbracoMapper umbracoMapper,
IOptions<GlobalSettings> globalSettings,
IBackOfficeUserManager backOfficeUserManager,
ILoggerFactory loggerFactory,
LinkGenerator linkGenerator,
IBackOfficeExternalLoginProviders externalLogins,
UserEditorAuthorizationHelper userEditorAuthorizationHelper,
IPasswordChanger<BackOfficeIdentityUser> passwordChanger)
: this(mediaFileManager,
contentSettings,
hostingEnvironment,
sqlContext,
imageUrlGenerator,
securitySettings,
emailSender,
backofficeSecurityAccessor,
appCaches,
shortStringHelper,
userService,
localizedTextService,
umbracoMapper,
globalSettings,
backOfficeUserManager,
loggerFactory,
linkGenerator,
externalLogins,
userEditorAuthorizationHelper,
passwordChanger,
StaticServiceProvider.Instance.GetRequiredService<IHttpContextAccessor>(),
StaticServiceProvider.Instance.GetRequiredService<IOptions<WebRoutingSettings>>())
{
}
/// <summary>
/// Returns a list of the sizes of gravatar URLs for the user or null if the gravatar server cannot be reached
/// </summary>
/// <returns></returns>
public ActionResult<string[]> GetCurrentUserAvatarUrls()
{
var urls = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetUserAvatarUrls(_appCaches.RuntimeCache, _mediaFileManager, _imageUrlGenerator);
if (urls == null)
return ValidationProblem("Could not access Gravatar endpoint");
return urls;
}
[AppendUserModifiedHeader("id")]
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostSetAvatar(int id, IList<IFormFile> file)
{
return PostSetAvatarInternal(file, _userService, _appCaches.RuntimeCache, _mediaFileManager, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, id);
}
internal static IActionResult PostSetAvatarInternal(IList<IFormFile> files, IUserService userService, IAppCache cache, MediaFileManager mediaFileManager, IShortStringHelper shortStringHelper, ContentSettings contentSettings, IHostingEnvironment hostingEnvironment, IImageUrlGenerator imageUrlGenerator, int id)
{
if (files is null)
{
return new UnsupportedMediaTypeResult();
}
var root = hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads);
//ensure it exists
Directory.CreateDirectory(root);
//must have a file
if (files.Count == 0)
{
return new NotFoundResult();
}
var user = userService.GetUserById(id);
if (user == null)
return new NotFoundResult();
if (files.Count > 1)
return new ValidationErrorResult("The request was not formatted correctly, only one file can be attached to the request");
//get the file info
var file = files.First();
var fileName = file.FileName.Trim(new[] { '\"' }).TrimEnd();
var safeFileName = fileName.ToSafeFileName(shortStringHelper);
var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower();
if (contentSettings.DisallowedUploadFiles.Contains(ext) == false)
{
//generate a path of known data, we don't want this path to be guessable
user.Avatar = "UserAvatars/" + (user.Id + safeFileName).GenerateHash<SHA1>() + "." + ext;
using (var fs = file.OpenReadStream())
{
mediaFileManager.FileSystem.AddFile(user.Avatar, fs, true);
}
userService.Save(user);
}
return new OkObjectResult(user.GetUserAvatarUrls(cache, mediaFileManager, imageUrlGenerator));
}
[AppendUserModifiedHeader("id")]
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public ActionResult<string[]> PostClearAvatar(int id)
{
var found = _userService.GetUserById(id);
if (found == null)
return NotFound();
var filePath = found.Avatar;
//if the filePath is already null it will mean that the user doesn't have a custom avatar and their gravatar is currently
//being used (if they have one). This means they want to remove their gravatar too which we can do by setting a special value
//for the avatar.
if (filePath.IsNullOrWhiteSpace() == false)
{
found.Avatar = null;
}
else
{
//set a special value to indicate to not have any avatar
found.Avatar = "none";
}
_userService.Save(found);
if (filePath.IsNullOrWhiteSpace() == false)
{
if (_mediaFileManager.FileSystem.FileExists(filePath))
_mediaFileManager.FileSystem.DeleteFile(filePath);
}
return found.GetUserAvatarUrls(_appCaches.RuntimeCache, _mediaFileManager, _imageUrlGenerator);
}
/// <summary>
/// Gets a user by Id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public ActionResult<UserDisplay> GetById(int id)
{
var user = _userService.GetUserById(id);
if (user == null)
{
return NotFound();
}
var result = _umbracoMapper.Map<IUser, UserDisplay>(user);
return result;
}
/// <summary>
/// Get users by integer ids
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public ActionResult<IEnumerable<UserDisplay>> GetByIds([FromJsonPath]int[] ids)
{
if (ids == null)
{
return NotFound();
}
if (ids.Length == 0)
return Enumerable.Empty<UserDisplay>().ToList();
var users = _userService.GetUsersById(ids);
if (users == null)
{
return NotFound();
}
var result = _umbracoMapper.MapEnumerable<IUser, UserDisplay>(users);
return result;
}
/// <summary>
/// Returns a paged users collection
/// </summary>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="userGroups"></param>
/// <param name="userStates"></param>
/// <param name="filter"></param>
/// <returns></returns>
public PagedUserResult GetPagedUsers(
int pageNumber = 1,
int pageSize = 10,
string orderBy = "username",
Direction orderDirection = Direction.Ascending,
[FromQuery]string[] userGroups = null,
[FromQuery]UserState[] userStates = null,
string filter = "")
{
//following the same principle we had in previous versions, we would only show admins to admins, see
// https://github.com/umbraco/Umbraco-CMS/blob/dev-v7/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadUsers.cs#L91
// so to do that here, we'll need to check if this current user is an admin and if not we should exclude all user who are
// also admins
var hideDisabledUsers = _securitySettings.HideDisabledUsersInBackOffice;
var excludeUserGroups = new string[0];
var isAdmin = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin();
if (isAdmin == false)
{
//this user is not an admin so in that case we need to exclude all admin users
excludeUserGroups = new[] {Constants.Security.AdminGroupAlias};
}
var filterQuery = _sqlContext.Query<IUser>();
if (!_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsSuper())
{
// only super can see super - but don't use IsSuper, cannot be mapped to SQL
//filterQuery.Where(x => !x.IsSuper());
filterQuery.Where(x => x.Id != Constants.Security.SuperUserId);
}
if (filter.IsNullOrWhiteSpace() == false)
{
filterQuery.Where(x => x.Name.Contains(filter) || x.Username.Contains(filter));
}
if (hideDisabledUsers)
{
if (userStates == null || userStates.Any() == false)
{
userStates = new[] { UserState.Active, UserState.Invited, UserState.LockedOut, UserState.Inactive };
}
}
long pageIndex = pageNumber - 1;
long total;
var result = _userService.GetAll(pageIndex, pageSize, out total, orderBy, orderDirection, userStates, userGroups, excludeUserGroups, filterQuery);
var paged = new PagedUserResult(total, pageNumber, pageSize)
{
Items = _umbracoMapper.MapEnumerable<IUser, UserBasic>(result),
UserStates = _userService.GetUserStates()
};
return paged;
}
/// <summary>
/// Creates a new user
/// </summary>
/// <param name="userSave"></param>
/// <returns></returns>
public async Task<ActionResult<UserDisplay>> PostCreateUser(UserInvite userSave)
{
if (userSave == null) throw new ArgumentNullException("userSave");
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
if (_securitySettings.UsernameIsEmail)
{
//ensure they are the same if we're using it
userSave.Username = userSave.Email;
}
else
{
//first validate the username if were showing it
CheckUniqueUsername(userSave.Username, null);
}
CheckUniqueEmail(userSave.Email, null);
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
//Perform authorization here to see if the current user can actually save this user with the info being requested
var canSaveUser = _userEditorAuthorizationHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, null, null, null, userSave.UserGroups);
if (canSaveUser == false)
{
return Unauthorized(canSaveUser.Result);
}
//we want to create the user with the UserManager, this ensures the 'empty' (special) password
//format is applied without us having to duplicate that logic
var identityUser = BackOfficeIdentityUser.CreateNew(_globalSettings, userSave.Username, userSave.Email, _globalSettings.DefaultUILanguage);
identityUser.Name = userSave.Name;
var created = await _userManager.CreateAsync(identityUser);
if (created.Succeeded == false)
{
return ValidationProblem(created.Errors.ToErrorMessage());
}
string resetPassword;
var password = _userManager.GeneratePassword();
var result = await _userManager.AddPasswordAsync(identityUser, password);
if (result.Succeeded == false)
{
return ValidationProblem(created.Errors.ToErrorMessage());
}
resetPassword = password;
//now re-look the user back up which will now exist
var user = _userService.GetByEmail(userSave.Email);
//map the save info over onto the user
user = _umbracoMapper.Map(userSave, user);
//since the back office user is creating this user, they will be set to approved
user.IsApproved = true;
_userService.Save(user);
var display = _umbracoMapper.Map<UserDisplay>(user);
display.ResetPasswordValue = resetPassword;
return display;
}
/// <summary>
/// Invites a user
/// </summary>
/// <param name="userSave"></param>
/// <returns></returns>
/// <remarks>
/// This will email the user an invite and generate a token that will be validated in the email
/// </remarks>
public async Task<ActionResult<UserDisplay>> PostInviteUser(UserInvite userSave)
{
if (userSave == null)
{
throw new ArgumentNullException(nameof(userSave));
}
if (userSave.Message.IsNullOrWhiteSpace())
{
ModelState.AddModelError("Message", "Message cannot be empty");
}
if (_securitySettings.UsernameIsEmail)
{
// ensure it's the same
userSave.Username = userSave.Email;
}
else
{
// first validate the username if we're showing it
ActionResult<IUser> userResult = CheckUniqueUsername(userSave.Username, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue);
if (userResult.Result is not null)
{
return userResult.Result;
}
}
IUser user = CheckUniqueEmail(userSave.Email, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue);
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
if (!_emailSender.CanSendRequiredEmail())
{
return ValidationProblem("No Email server is configured");
}
// Perform authorization here to see if the current user can actually save this user with the info being requested
var canSaveUser = _userEditorAuthorizationHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, user, null, null, userSave.UserGroups);
if (canSaveUser == false)
{
return ValidationProblem(canSaveUser.Result, StatusCodes.Status401Unauthorized);
}
if (user == null)
{
// we want to create the user with the UserManager, this ensures the 'empty' (special) password
// format is applied without us having to duplicate that logic
var identityUser = BackOfficeIdentityUser.CreateNew(_globalSettings, userSave.Username, userSave.Email, _globalSettings.DefaultUILanguage);
identityUser.Name = userSave.Name;
var created = await _userManager.CreateAsync(identityUser);
if (created.Succeeded == false)
{
return ValidationProblem(created.Errors.ToErrorMessage());
}
// now re-look the user back up
user = _userService.GetByEmail(userSave.Email);
}
// map the save info over onto the user
user = _umbracoMapper.Map(userSave, user);
// ensure the invited date is set
user.InvitedDate = DateTime.Now;
// Save the updated user (which will process the user groups too)
_userService.Save(user);
var display = _umbracoMapper.Map<UserDisplay>(user);
// send the email
await SendUserInviteEmailAsync(display, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Email, user, userSave.Message);
display.AddSuccessNotification(_localizedTextService.Localize("speechBubbles","resendInviteHeader"), _localizedTextService.Localize("speechBubbles","resendInviteSuccess", new[] { user.Name }));
return display;
}
private IUser CheckUniqueEmail(string email, Func<IUser, bool> extraCheck)
{
var user = _userService.GetByEmail(email);
if (user != null && (extraCheck == null || extraCheck(user)))
{
ModelState.AddModelError("Email", "A user with the email already exists");
}
return user;
}
private ActionResult<IUser> CheckUniqueUsername(string username, Func<IUser, bool> extraCheck)
{
var user = _userService.GetByUsername(username);
if (user != null && (extraCheck == null || extraCheck(user)))
{
ModelState.AddModelError(
_securitySettings.UsernameIsEmail ? "Email" : "Username",
"A user with the username already exists");
return ValidationProblem(ModelState);
}
return new ActionResult<IUser>(user);
}
private async Task SendUserInviteEmailAsync(UserBasic userDisplay, string from, string fromEmail, IUser to, string message)
{
var user = await _userManager.FindByIdAsync(((int) userDisplay.Id).ToString());
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
// Use info from SMTP Settings if configured, otherwise set fromEmail as fallback
var senderEmail = !string.IsNullOrEmpty(_globalSettings.Smtp?.From) ? _globalSettings.Smtp.From : fromEmail;
var inviteToken = string.Format("{0}{1}{2}",
(int)userDisplay.Id,
WebUtility.UrlEncode("|"),
token.ToUrlBase64());
// Get an mvc helper to get the URL
var action = _linkGenerator.GetPathByAction(
nameof(BackOfficeController.VerifyInvite),
ControllerExtensions.GetControllerName<BackOfficeController>(),
new
{
area = Constants.Web.Mvc.BackOfficeArea,
invite = inviteToken
});
// Construct full URL using configured application URL (which will fall back to request)
Uri applicationUri = _httpContextAccessor.GetRequiredHttpContext().Request.GetApplicationUri(_webRoutingSettings);
var inviteUri = new Uri(applicationUri, action);
var emailSubject = _localizedTextService.Localize("user","inviteEmailCopySubject",
// Ensure the culture of the found user is used for the email!
UmbracoUserExtensions.GetUserCulture(to.Language, _localizedTextService, _globalSettings));
var emailBody = _localizedTextService.Localize("user","inviteEmailCopyFormat",
// Ensure the culture of the found user is used for the email!
UmbracoUserExtensions.GetUserCulture(to.Language, _localizedTextService, _globalSettings),
new[] { userDisplay.Name, from, message, inviteUri.ToString(), senderEmail });
// This needs to be in the correct mailto format including the name, else
// the name cannot be captured in the email sending notification.
// i.e. "Some Person" <hello@example.com>
var toMailBoxAddress = new MailboxAddress(to.Name, to.Email);
var mailMessage = new EmailMessage(senderEmail, toMailBoxAddress.ToString(), emailSubject, emailBody, true);
await _emailSender.SendAsync(mailMessage, Constants.Web.EmailTypes.UserInvite, true);
}
/// <summary>
/// Saves a user
/// </summary>
/// <param name="userSave"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
public ActionResult<UserDisplay> PostSaveUser(UserSave userSave)
{
if (userSave == null) throw new ArgumentNullException(nameof(userSave));
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
var found = _userService.GetUserById(userSave.Id);
if (found == null)
return NotFound();
//Perform authorization here to see if the current user can actually save this user with the info being requested
var canSaveUser = _userEditorAuthorizationHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, found, userSave.StartContentIds, userSave.StartMediaIds, userSave.UserGroups);
if (canSaveUser == false)
{
return Unauthorized(canSaveUser.Result);
}
var hasErrors = false;
// we need to check if there's any Deny Local login providers present, if so we need to ensure that the user's email address cannot be changed
var hasDenyLocalLogin = _externalLogins.HasDenyLocalLogin();
if (hasDenyLocalLogin)
{
userSave.Email = found.Email; // it cannot change, this would only happen if people are mucking around with the request
}
var existing = _userService.GetByEmail(userSave.Email);
if (existing != null && existing.Id != userSave.Id)
{
ModelState.AddModelError("Email", "A user with the email already exists");
hasErrors = true;
}
existing = _userService.GetByUsername(userSave.Username);
if (existing != null && existing.Id != userSave.Id)
{
ModelState.AddModelError("Username", "A user with the username already exists");
hasErrors = true;
}
// going forward we prefer to align usernames with email, so we should cross-check to make sure
// the email or username isn't somehow being used by anyone.
existing = _userService.GetByEmail(userSave.Username);
if (existing != null && existing.Id != userSave.Id)
{
ModelState.AddModelError("Username", "A user using this as their email already exists");
hasErrors = true;
}
existing = _userService.GetByUsername(userSave.Email);
if (existing != null && existing.Id != userSave.Id)
{
ModelState.AddModelError("Email", "A user using this as their username already exists");
hasErrors = true;
}
// if the found user has their email for username, we want to keep this synced when changing the email.
// we have already cross-checked above that the email isn't colliding with anything, so we can safely assign it here.
if (_securitySettings.UsernameIsEmail && found.Username == found.Email && userSave.Username != userSave.Email)
{
userSave.Username = userSave.Email;
}
if (hasErrors)
return ValidationProblem(ModelState);
//merge the save data onto the user
var user = _umbracoMapper.Map(userSave, found);
_userService.Save(user);
var display = _umbracoMapper.Map<UserDisplay>(user);
// determine if the user has changed their own language;
var currentUser = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser;
var userHasChangedOwnLanguage =
user.Id == currentUser.Id && currentUser.Language != user.Language;
var textToLocalise = userHasChangedOwnLanguage ? "operationSavedHeaderReloadUser" : "operationSavedHeader";
var culture = userHasChangedOwnLanguage
? CultureInfo.GetCultureInfo(user.Language)
: Thread.CurrentThread.CurrentUICulture;
display.AddSuccessNotification(_localizedTextService.Localize("speechBubbles", textToLocalise, culture), _localizedTextService.Localize("speechBubbles","editUserSaved", culture));
return display;
}
/// <summary>
///
/// </summary>
/// <param name="changingPasswordModel"></param>
/// <returns></returns>
public async Task<ActionResult<ModelWithNotifications<string>>> PostChangePassword(ChangingPasswordModel changingPasswordModel)
{
changingPasswordModel = changingPasswordModel ?? throw new ArgumentNullException(nameof(changingPasswordModel));
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
IUser found = _userService.GetUserById(changingPasswordModel.Id);
if (found == null)
{
return NotFound();
}
IUser currentUser = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser;
// if it's the current user, the current user cannot reset their own password without providing their old password
if (currentUser.Username == found.Username && string.IsNullOrEmpty(changingPasswordModel.OldPassword))
{
return ValidationProblem("Password reset is not allowed without providing old password");
}
if (!currentUser.IsAdmin() && found.IsAdmin())
{
return ValidationProblem("The current user cannot change the password for the specified user");
}
Attempt<PasswordChangedModel> passwordChangeResult = await _passwordChanger.ChangePasswordWithIdentityAsync(changingPasswordModel, _userManager);
if (passwordChangeResult.Success)
{
var result = new ModelWithNotifications<string>(passwordChangeResult.Result.ResetPassword);
result.AddSuccessNotification(_localizedTextService.Localize("general","success"), _localizedTextService.Localize("user","passwordChangedGeneric"));
return result;
}
foreach (string memberName in passwordChangeResult.Result.ChangeError.MemberNames)
{
ModelState.AddModelError(memberName, passwordChangeResult.Result.ChangeError.ErrorMessage);
}
return ValidationProblem(ModelState);
}
/// <summary>
/// Disables the users with the given user ids
/// </summary>
/// <param name="userIds"></param>
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostDisableUsers([FromQuery]int[] userIds)
{
var tryGetCurrentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId();
if (tryGetCurrentUserId && userIds.Contains(tryGetCurrentUserId.Result))
{
return ValidationProblem("The current user cannot disable itself");
}
var users = _userService.GetUsersById(userIds).ToArray();
foreach (var u in users)
{
u.IsApproved = false;
u.InvitedDate = null;
}
_userService.Save(users);
if (users.Length > 1)
{
return Ok(_localizedTextService.Localize("speechBubbles","disableUsersSuccess", new[] {userIds.Length.ToString()}));
}
return Ok(_localizedTextService.Localize("speechBubbles","disableUserSuccess", new[] { users[0].Name }));
}
/// <summary>
/// Enables the users with the given user ids
/// </summary>
/// <param name="userIds"></param>
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostEnableUsers([FromQuery]int[] userIds)
{
var users = _userService.GetUsersById(userIds).ToArray();
foreach (var u in users)
{
u.IsApproved = true;
}
_userService.Save(users);
if (users.Length > 1)
{
return Ok(
_localizedTextService.Localize("speechBubbles","enableUsersSuccess", new[] { userIds.Length.ToString() }));
}
return Ok(
_localizedTextService.Localize("speechBubbles","enableUserSuccess", new[] { users[0].Name }));
}
/// <summary>
/// Unlocks the users with the given user ids
/// </summary>
/// <param name="userIds"></param>
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public async Task<IActionResult> PostUnlockUsers([FromQuery]int[] userIds)
{
if (userIds.Length <= 0) return Ok();
var notFound = new List<int>();
foreach (var u in userIds)
{
var user = await _userManager.FindByIdAsync(u.ToString());
if (user == null)
{
notFound.Add(u);
continue;
}
var unlockResult = await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.Now.AddMinutes(-1));
if (unlockResult.Succeeded == false)
{
return ValidationProblem(
$"Could not unlock for user {u} - error {unlockResult.Errors.ToErrorMessage()}");
}
if (userIds.Length == 1)
{
return Ok(
_localizedTextService.Localize("speechBubbles","unlockUserSuccess", new[] {user.Name}));
}
}
return Ok(
_localizedTextService.Localize("speechBubbles","unlockUsersSuccess", new[] {(userIds.Length - notFound.Count).ToString()}));
}
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostSetUserGroupsOnUsers([FromQuery]string[] userGroupAliases, [FromQuery]int[] userIds)
{
var users = _userService.GetUsersById(userIds).ToArray();
var userGroups = _userService.GetUserGroupsByAlias(userGroupAliases).Select(x => x.ToReadOnlyGroup()).ToArray();
foreach (var u in users)
{
u.ClearGroups();
foreach (var userGroup in userGroups)
{
u.AddGroup(userGroup);
}
}
_userService.Save(users);
return Ok(
_localizedTextService.Localize("speechBubbles","setUserGroupOnUsersSuccess"));
}
/// <summary>
/// Deletes the non-logged in user provided id
/// </summary>
/// <param name="id">User Id</param>
/// <remarks>
/// Limited to users that haven't logged in to avoid issues with related records constrained
/// with a foreign key on the user Id
/// </remarks>
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostDeleteNonLoggedInUser(int id)
{
var user = _userService.GetUserById(id);
if (user == null)
{
return NotFound();
}
// Check user hasn't logged in. If they have they may have made content changes which will mean
// the Id is associated with audit trails, versions etc. and can't be removed.
if (user.LastLoginDate != default(DateTime))
{
return BadRequest();
}
var userName = user.Name;
_userService.Delete(user, true);
return Ok(
_localizedTextService.Localize("speechBubbles","deleteUserSuccess", new[] { userName }));
}
public class PagedUserResult : PagedResult<UserBasic>
{
public PagedUserResult(long totalItems, long pageNumber, long pageSize) : base(totalItems, pageNumber, pageSize)
{
UserStates = new Dictionary<UserState, int>();
}
/// <summary>
/// This is basically facets of UserStates key = state, value = count
/// </summary>
[DataMember(Name = "userStates")]
public IDictionary<UserState, int> UserStates { get; set; }
}
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using GroupDocs.Viewer.Converter.Options;
using GroupDocs.Viewer.Domain;
namespace MvcSample.Helpers
{
/// <summary>
/// Class FileDataJsonSerializer.
/// </summary>
public class FileDataJsonSerializer
{
/// <summary>
/// The _file data
/// </summary>
private readonly FileData _fileData;
/// <summary>
/// The _options
/// </summary>
private readonly FileDataOptions _options;
/// <summary>
/// The _default culture
/// </summary>
private readonly CultureInfo _defaultCulture = CultureInfo.InvariantCulture;
/// <summary>
/// Initializes a new instance of the <see cref="FileDataJsonSerializer"/> class.
/// </summary>
/// <param name="fileData">The file data.</param>
/// <param name="options">The options.</param>
public FileDataJsonSerializer(FileData fileData, FileDataOptions options)
{
_fileData = fileData;
_options = options;
}
/// <summary>
/// Serializes this instance.
/// </summary>
/// <returns>System.String.</returns>
public string Serialize(bool isDefault)
{
WordsFileData wordsFileData = _fileData as WordsFileData;
if (wordsFileData != null)
return SerializeWords(wordsFileData);
var isCellsFileData = _fileData.Pages.Any(_ => !string.IsNullOrEmpty(_.Name));
if (isCellsFileData && !isDefault)
return SerializeCells();
return SerializeDefault();
}
/// <summary>
/// Serializes the default.
/// </summary>
/// <returns>System.String.</returns>
private string SerializeDefault()
{
StringBuilder json = new StringBuilder();
json.Append(string.Format("{{\"maxPageHeight\":{0},\"widthForMaxHeight\":{1}",
_fileData.MaxHeight, _fileData.MaxHeight));
json.Append(",\"pages\":[");
int pageCount = _fileData.Pages.Count;
for (int i = 0; i < pageCount; i++)
{
PageData pageData = _fileData.Pages[i];
bool needSeparator = i > 0;
if (needSeparator)
json.Append(",");
AppendPage(pageData, json);
bool includeRows = _options.UsePdf && pageData.Rows.Count > 0;
if (includeRows)
{
json.Append(",\"rows\":[");
for (int j = 0; j < pageData.Rows.Count; j++)
{
bool appendRowSeaparator = j != 0;
if (appendRowSeaparator)
json.Append(",");
AppendRow(pageData.Rows[j], json);
}
json.Append("]"); // rows
}
json.Append("}"); // page
}
json.Append("]"); // pages
json.Append("}"); // document
return json.ToString();
}
/// <summary>
/// Serializes cells.
/// </summary>
/// <returns>System.String.</returns>
private string SerializeCells()
{
StringBuilder json = new StringBuilder();
json.Append("{\"sheets\":[");
int pageCount = _fileData.Pages.Count;
for (int i = 0; i < pageCount; i++)
{
PageData pageData = _fileData.Pages[i];
bool needSeparator = pageData.Number > 1;
if (needSeparator)
json.Append(",");
json.Append(string.Format("{{\"name\":\"{0}\"}}", pageData.Name));
}
json.Append("]"); // pages
json.Append("}"); // document
return json.ToString();
}
/// <summary>
/// Serializes the specified words file data.
/// </summary>
/// <param name="wordsFileData">The words file data.</param>
/// <returns>System.String.</returns>
private string SerializeWords(WordsFileData wordsFileData)
{
StringBuilder json = new StringBuilder();
json.Append(string.Format("{{\"maxPageHeight\":{0},\"widthForMaxHeight\":{1}",
_fileData.MaxHeight, _fileData.MaxHeight));
json.Append(",\"pages\":[");
int pageCount = wordsFileData.Pages.Count;
for (int i = 0; i < pageCount; i++)
{
PageData pageData = wordsFileData.Pages[i];
bool needSeparator = pageData.Number >= 1;
if (needSeparator)
json.Append(",");
AppendPage(pageData, json);
json.Append("}"); // page
}
json.Append("]"); // pages
bool includeContentControls = _options.UsePdf && wordsFileData.ContentControls.Count > 0;
if (includeContentControls)
{
json.Append(", \"contentControls\":[");
bool needSeparator = false;
foreach (ContentControl contentControl in wordsFileData.ContentControls)
{
if (needSeparator)
json.Append(',');
AppendContentControl(contentControl, json);
needSeparator = true;
}
json.Append("]"); //contentControls
}
json.Append("}"); //document
return json.ToString();
}
/// <summary>
/// Appends the page.
/// </summary>
/// <param name="pageData">The page data.</param>
/// <param name="json">The json.</param>
private void AppendPage(PageData pageData, StringBuilder json)
{
json.Append(string.Format("{{\"w\":{0},\"h\":{1},\"number\":{2},\"rotation\":{3}",
pageData.Width.ToString(_defaultCulture),
pageData.Height.ToString(_defaultCulture),
(pageData.Number).ToString(_defaultCulture),
pageData.Angle));
}
/// <summary>
/// Appends the row.
/// </summary>
/// <param name="rowData">The row data.</param>
/// <param name="json">The json.</param>
private void AppendRow(RowData rowData, StringBuilder json)
{
string[] textCoordinates = new string[rowData.TextCoordinates.Count];
for (int i = 0; i < rowData.TextCoordinates.Count; i++)
textCoordinates[i] = rowData.TextCoordinates[i].ToString(_defaultCulture);
string[] characterCoordinates = new string[rowData.CharacterCoordinates.Count];
for (int i = 0; i < rowData.CharacterCoordinates.Count; i++)
characterCoordinates[i] = rowData.CharacterCoordinates[i].ToString(_defaultCulture);
json.Append(String.Format("{{\"l\":{0},\"t\":{1},\"w\":{2},\"h\":{3},\"c\":[{4}],\"s\":\"{5}\",\"ch\":[{6}]}}",
rowData.LineLeft.ToString(_defaultCulture),
rowData.LineTop.ToString(_defaultCulture),
rowData.LineWidth.ToString(_defaultCulture),
rowData.LineHeight.ToString(_defaultCulture),
string.Join(",", textCoordinates),
JsonEncode(rowData.Text),
string.Join(",", characterCoordinates)));
}
/// <summary>
/// Appends the content control.
/// </summary>
/// <param name="contentControl">The content control.</param>
/// <param name="json">The json.</param>
private void AppendContentControl(ContentControl contentControl, StringBuilder json)
{
json.Append(string.Format("{{\"title\":\"{0}\", \"startPage\":{1}, \"endPage\":{2}}}",
JsonEncode(contentControl.Title),
contentControl.StartPageNumber.ToString(_defaultCulture),
contentControl.EndPageNumber.ToString(_defaultCulture)));
}
/// <summary>
/// Jsons the encode.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>System.String.</returns>
private string JsonEncode(string text)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
int i;
int length = text.Length;
StringBuilder stringBuilder = new StringBuilder(length + 4);
for (i = 0; i < length; i += 1)
{
char c = text[i];
switch (c)
{
case '\\':
case '"':
case '/':
stringBuilder.Append('\\');
stringBuilder.Append(c);
break;
case '\b':
stringBuilder.Append("\\b");
break;
case '\t':
stringBuilder.Append("\\t");
break;
case '\n':
stringBuilder.Append("\\n");
break;
case '\f':
stringBuilder.Append("\\f");
break;
case '\r':
stringBuilder.Append("\\r");
break;
default:
if (c < ' ')
{
string t = "000" + Convert.ToByte(c).ToString("X");
stringBuilder.Append("\\u" + t.Substring(t.Length - 4));
}
else
{
stringBuilder.Append(c);
}
break;
}
}
return stringBuilder.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Mercurial.Hooks
{
/// <summary>
/// This class is used by <see cref="MercurialPreCommandHook"/> and <see cref="MercurialPostCommandHook"/> to
/// hold the options to the Mercurial command.
/// </summary>
public sealed class MercurialCommandHookDictionary : MercurialCommandHookDataStructureBase, IDictionary<string, object>
{
/// <summary>
/// This is the backing field for this <see cref="MercurialCommandHookDictionary"/>.
/// </summary>
private readonly Dictionary<string, object> _Collection = new Dictionary<string, object>();
/// <summary>
/// Initializes a new instance of the <see cref="MercurialCommandHookDictionary"/> class.
/// </summary>
/// <param name="dictionaryValue">
/// The current value of the dictionary, as a string.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>The <paramref name="dictionaryValue"/> is <c>null</c> or an empty string.</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>The <paramref name="dictionaryValue"/> is <c>null</c> or an empty string.</para>
/// <para>- or -</para>
/// <para>The <paramref name="dictionaryValue"/> must start with an opening curly brace.</para>
/// <para>- or -</para>
/// <para>The <paramref name="dictionaryValue"/> must end with a closing curly brace.</para>
/// <para>- or -</para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// <para>Unsupported syntax in the <paramref name="dictionaryValue"/>.</para>
/// </exception>
public MercurialCommandHookDictionary(string dictionaryValue)
{
if (dictionaryValue == null)
throw new ArgumentNullException("dictionaryValue");
if (!dictionaryValue.StartsWith("{", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("dictionaryValue must start with an opening curly brace", "dictionaryValue");
if (!dictionaryValue.EndsWith("}", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("dictionaryValue must end with a closing curly brace", "dictionaryValue");
int index = 1;
while (index < dictionaryValue.Length && dictionaryValue[index] != '}')
{
int prevIndex = index;
// Grab name of key/value pair
var key = ParseValue(dictionaryValue, ref index) as string;
if (prevIndex == index)
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unsupported syntax in options combined at position #{0} (0-based), did not understand value at location", index));
if (key == null)
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unsupported syntax in options combined at position #{0} (0-based), expected name as string", prevIndex));
// Skip colon
if (dictionaryValue[index] != ':')
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unsupported syntax in options combined at position #{0} (0-based), expected colon (:)", prevIndex));
index++;
// Skip space
if (dictionaryValue[index] != ' ')
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unsupported syntax in options combined at position #{0} (0-based), expected space after colon", prevIndex));
index++;
// Grab value
prevIndex = index;
object value = ParseValue(dictionaryValue, ref index);
if (prevIndex == index)
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Unsupported syntax in options combined at position #{0} (0-based), did not understand value at location", index));
// Store
_Collection[key] = value;
// Skip comma and space, if present
if (dictionaryValue[index] == ',')
{
index++;
if (dictionaryValue[index] == ' ')
index++;
}
}
}
/// <summary>
/// Always throws <see cref="NotSupportedException"/> since this <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </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="MercurialCommandHookDictionary"/>.
/// </exception>
/// <exception cref="NotSupportedException">
/// The <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </exception>
public void Add(string key, object value)
{
throw new NotSupportedException("This dictionary is read-only");
}
/// <summary>
/// Determines whether the <see cref="MercurialCommandHookDictionary"/> contains an element with the specified key.
/// </summary>
/// <returns>
/// true if the <see cref="MercurialCommandHookDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
/// <param name="key">
/// The key to locate in the <see cref="MercurialCommandHookDictionary"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
public bool ContainsKey(string key)
{
return _Collection.ContainsKey(key);
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="MercurialCommandHookDictionary"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of this <see cref="MercurialCommandHookDictionary"/>.
/// </returns>
public ICollection<string> Keys
{
get
{
return _Collection.Keys;
}
}
/// <summary>
/// Always throws <see cref="NotSupportedException"/> since this <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </summary>
/// <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="MercurialCommandHookDictionary"/>.
/// </returns>
/// <param name="key">
/// The key of the element to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
/// <exception cref="NotSupportedException">
/// The <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </exception>
public bool Remove(string key)
{
throw new NotSupportedException("This dictionary is read-only");
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <returns>
/// true if this <see cref="MercurialCommandHookDictionary"/> contains an element with the specified key; otherwise, false.
/// </returns>
/// <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 for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
public bool TryGetValue(string key, out object value)
{
return _Collection.TryGetValue(key, out value);
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="MercurialCommandHookDictionary"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="MercurialCommandHookDictionary"/>.
/// </returns>
public ICollection<object> Values
{
get
{
return _Collection.Values;
}
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>
/// The element with the specified key.
/// </returns>
/// <param name="key">
/// The key of the element to get or set.
/// </param>
/// <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="MercurialCommandHookDictionary"/> is read-only.
/// </exception>
public object this[string key]
{
get
{
return _Collection[key];
}
set
{
throw new NotSupportedException("This dictionary is read-only");
}
}
/// <summary>
/// Always throws <see cref="NotSupportedException"/> since this <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </summary>
/// <param name="item">
/// The object to add to the <see cref="MercurialCommandHookDictionary"/>.
/// </param>
/// <exception cref="NotSupportedException">
/// The <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </exception>
public void Add(KeyValuePair<string, object> item)
{
throw new NotSupportedException("This dictionary is read-only");
}
/// <summary>
/// Always throws <see cref="NotSupportedException"/> since this <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </summary>
/// <exception cref="NotSupportedException">
/// The <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </exception>
public void Clear()
{
throw new NotSupportedException("This dictionary is read-only");
}
/// <summary>
/// Determines whether the <see cref="MercurialCommandHookDictionary"/> contains a specific value.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="MercurialCommandHookDictionary"/>; otherwise, false.
/// </returns>
/// <param name="item">
/// The object to locate in the <see cref="MercurialCommandHookDictionary"/>.
/// </param>
public bool Contains(KeyValuePair<string, object> item)
{
return _Collection.Contains(item);
}
/// <summary>
/// Copies the elements of the <see cref="MercurialCommandHookDictionary"/> 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="MercurialCommandHookDictionary"/>.
/// 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>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is null.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.
/// </exception>
/// <exception cref="ArgumentException">
/// <para><paramref name="array"/> is multidimensional.</para>
/// <para>- or -</para>
/// <para><paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>.</para>
/// <para>- or -</para>
/// <para>The number of elements in the source <see cref="MercurialCommandHookDictionary"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.</para>
/// <para>- or -</para>
/// <para>Value cannot be cast automatically to the type of the destination <paramref name="array"/>.</para>
/// </exception>
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<string, object>>)_Collection).CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets the number of elements contained in the <see cref="MercurialCommandHookDictionary"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="MercurialCommandHookDictionary"/>.
/// </returns>
public int Count
{
get
{
return _Collection.Count;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </summary>
/// <returns>
/// Always true since the <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </returns>
public bool IsReadOnly
{
get
{
return true;
}
}
/// <summary>
/// Always throws <see cref="NotSupportedException"/> since this <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="MercurialCommandHookDictionary"/>; otherwise, false.
/// This method also returns false if <paramref name="item"/> is not found in the original <see cref="MercurialCommandHookDictionary"/>.
/// </returns>
/// <param name="item">
/// The object to remove from the <see cref="MercurialCommandHookDictionary"/>.
/// </param>
/// <exception cref="NotSupportedException">
/// The <see cref="MercurialCommandHookDictionary"/> is read-only.
/// </exception>
public bool Remove(KeyValuePair<string, object> item)
{
throw new NotSupportedException("This dictionary is read-only");
}
/// <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 IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return _Collection.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
using Codex.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Codex.Uno.Shared
{
using static ViewBuilder;
using static MainController;
public class LeftPaneView
{
public static FrameworkElement Create(LeftPaneViewModel viewModel)
{
return new DockPanel().WithChildren(
Top(
new Border()
{
Height = 38,
Background = B(C(0xFFFFE0)),
BorderBrush = B(C(0xF0E68C)),
BorderThickness = new Thickness(1),
Margin = new Thickness(8),
VerticalAlignment = VerticalAlignment.Top,
Padding = new Thickness(8, 0, 8, 0),
}
.HideIfNull(viewModel.SearchInfoBinding)
.WithChild(
new TextBlock()
{
Foreground = B(Colors.Black),
VerticalAlignment = VerticalAlignment.Center,
FontSize = 16,
}
.Bind(viewModel.SearchInfoBinding, (t, value) => t.Text = value)
)
),
new ContentControl()
{
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch
}
.HideIfNull(viewModel.ContentBinding)
.Bind(viewModel.ContentBinding, (control, value) => control.Content = value?.CreateView())
);
}
internal static UIElement Create(CategorizedSearchResultsViewModel viewModel)
{
return new ItemsControl().Add(viewModel.Categories.Select(Create));
}
internal static UIElement Create(CategoryGroupSearchResultsViewModel viewModel)
{
return new HeaderedContentControl()
//return new Expander()
{
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
Background = B(0x7988BD),
//IsExpanded = true,
Header = new TextBlock()
{
Text = viewModel.Header,
Margin = new Thickness(4, 6, 4, 6),
Foreground = B(Colors.White),
FontSize = 16
},
Content = new ContentControl()
{
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
Content = Create(viewModel.ProjectResults)
}
};
}
internal static UIElement Create(TextSpanSearchResultViewModel viewModel)
{
return new NavigateButton()
{
NavigateUri = viewModel.NavigateAddress.ToUrl(),
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
Content = new StackPanel()
{
Orientation = Orientation.Horizontal,
Margin = new Thickness(8, 1, 0, 1),
Children =
{
new TextBlock()
{
FontFamily = Consolas,
FontSize = 13,
TextWrapping = TextWrapping.NoWrap,
Text = viewModel.LineNumber.ToString(),
Foreground = B(0x1791AF),
}
.WithMargin(new Thickness(0, 0, 16, 0)),
new TextBlock()
{
FontFamily = Consolas,
FontSize = 13,
TextWrapping = TextWrapping.NoWrap,
Text = viewModel.PrefixText,
Foreground = B(Colors.Black),
},
new Border()
{
Background = B(Colors.Yellow),
Padding = new Thickness(0),
Margin = new Thickness(0),
Child =new TextBlock()
{
FontFamily = Consolas,
FontSize = 13,
TextWrapping = TextWrapping.NoWrap,
Text = viewModel.ContentText,
Foreground = B(Colors.Black),
}
},
new TextBlock()
{
FontFamily = Consolas,
FontSize = 13,
TextWrapping = TextWrapping.NoWrap,
Text = viewModel.SuffixText,
Foreground = B(Colors.Black),
}
}
}
}
.OnExecute(() => viewModel.OnExecuted());
}
internal static UIElement Create(ProjectGroupResultsViewModel viewModel)
{
return new HeaderedContentControl()
//return new Expander()
{
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
Margin = new Thickness(0, 0, 0, 16),
//IsExpanded = true,
Header = new TextBlock()
{
Text = viewModel.ProjectName,
Margin = new Thickness(5),
Foreground = B(Colors.Black),
Background = B(Colors.AliceBlue),
FontSize = 18,
FontWeight = FontWeights.Bold
},
Content = new ItemsControl().Add(viewModel.Items.Select(i => i.CreateView()))
};
}
internal static UIElement Create(FileResultsViewModel viewModel)
{
return new HeaderedContentControl
{
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
Header = new Border()
{
Background = B(0xf6f6f6),
Padding = new Thickness(12, 4, 4, 4),
Child = new TextBlock()
{
Text = viewModel.Path,
Foreground = B(Colors.Gray),
FontSize = 16
}
},
Content = new ItemsControl().Add(viewModel.Items.Select(i => i.CreateView()))
};
}
internal static UIElement Create(ProjectResultsViewModel viewModel)
{
return new ItemsControl().Add(viewModel.ProjectGroups.Select(Create));
}
internal static UIElement Create(SymbolResultViewModel viewModel)
{
return new NavigateButton()
{
NavigateUri = viewModel.NavigateAddress.ToUrl(),
HorizontalContentAlignment = HorizontalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Stretch,
Content = new StackPanel()
{
Orientation = Orientation.Vertical,
Margin = new Thickness(24, 4, 4, 4),
Children =
{
new StackPanel()
{
Orientation = Orientation.Horizontal,
Children =
{
new TextBlock()
{
Text = viewModel.SymbolKind,
Foreground = B(Colors.Blue),
Margin = new Thickness(0, 0, 5, 0),
FontSize = 16
},
new TextBlock()
{
Text = viewModel.ShortName,
Foreground = B(Colors.Black),
FontSize = 16
}
}
},
new TextBlock()
{
Text = viewModel.DisplayName,
Foreground = B(Colors.Silver),
FontSize = 14
}
}
}
}
.OnExecute(() => viewModel.NavigateAddress.Navigate(App, infer: false));
}
}
}
| |
/* Copyright (c) 2006 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.Xml;
using System.IO;
using System.Collections;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.Location;
#if WindowsCE || PocketPC
#else
using System.ComponentModel;
#endif
namespace Google.GData.Photos
{
//////////////////////////////////////////////////////////////////////
/// <summary>
/// Entry API customization class for defining entries in an Event feed.
/// </summary>
//////////////////////////////////////////////////////////////////////
public class AlbumEntry : PicasaEntry
{
/// <summary>
/// Constructs a new EventEntry instance with the appropriate category
/// to indicate that it is an event.
/// </summary>
public AlbumEntry()
: base()
{
Categories.Add(ALBUM_CATEGORY);
}
}
/// <summary>
/// accessor for an AlbumEntry
/// </summary>
[Obsolete("Use Google.Picasa.Album instead. This code will be removed soon")]
public class AlbumAccessor
{
private PicasaEntry entry;
/// <summary>
/// constructs a photo accessor for the passed in entry
/// </summary>
/// <param name="entry"></param>
public AlbumAccessor(PicasaEntry entry)
{
this.entry = entry;
if (entry.IsAlbum == false)
{
throw new ArgumentException("Entry is not a album", "entry");
}
}
/// <summary>
/// The album's access level. In this document, access level is also
/// referred to as "visibility." Valid values are public or private.
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Meta Album Data"),
Description("Specifies the access for the album.")]
#endif
public string Access
{
get
{
return this.entry.GetPhotoExtensionValue(GPhotoNameTable.Access);
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.Access, value);
}
}
/// <summary>
/// The nickname of the author
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Base Album Data"),
Description("Specifies the author's nickname")]
#endif
public string AlbumAuthorNickname
{
get
{
return this.entry.GetPhotoExtensionValue(GPhotoNameTable.Nickname);
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.Nickname, value);
}
}
/// <summary>
/// The author's name
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Base Album Data"),
Description("Specifies the author's name")]
#endif
public string AlbumAuthor
{
get
{
AtomPersonCollection authors = this.entry.Authors;
if (authors != null && authors.Count >0)
{
AtomPerson person = authors[0];
return person.Name;
}
return "No Author given";
}
set
{
AtomPersonCollection authors = this.entry.Authors;
if (authors != null)
{
AtomPerson person = null;
if (authors.Count > 0)
{
person = authors[0];
}
else
{
person = new AtomPerson(AtomPersonType.Author);
this.entry.Authors.Add(person);
}
person.Name = value;
}
}
}
/// <summary>
/// The title of the album
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Base Album Data"),
Description("Specifies the name of the album.")]
#endif
public string AlbumTitle
{
get
{
return this.entry.Title.Text;
}
set
{
this.entry.Title.Text = value;
}
}
/// <summary>
/// The summary of the album
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Base Album Data"),
Description("Specifies the summary of the album.")]
#endif
public string AlbumSummary
{
get
{
return this.entry.Summary.Text;
}
set
{
this.entry.Summary.Text = value;
}
}
/// <summary>
/// The number of bytes of storage that this album uses.
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Meta Album Data"),
Description("Specifies the bytes used for the album.")]
#endif
[CLSCompliant(false)]
public uint BytesUsed
{
get
{
return Convert.ToUInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.BytesUsed));
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.BytesUsed, Convert.ToString(value));
}
}
/// <summary>
/// The user-specified location associated with the album
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Location Data"),
Description("Specifies the location for the album.")]
#endif
public string Location
{
get
{
return this.entry.GetPhotoExtensionValue(GPhotoNameTable.Location);
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.Location, value);
}
}
/// <summary>
/// the Longitude of the photo
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Location Data"),
Description("The longitude of the photo.")]
#endif
public double Longitude
{
get
{
GeoRssWhere where = this.entry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (where != null)
{
return where.Longitude;
}
return -1;
}
set
{
GeoRssWhere where = this.entry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (where == null)
{
where = entry.CreateExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
this.entry.ExtensionElements.Add(where);
}
where.Longitude = value;
}
}
/// <summary>
/// the Longitude of the photo
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Location Data"),
Description("The Latitude of the photo.")]
#endif
public double Latitude
{
get
{
GeoRssWhere where = this.entry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (where != null)
{
return where.Latitude;
}
return -1;
}
set
{
GeoRssWhere where = this.entry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (where == null)
{
where = entry.CreateExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
this.entry.ExtensionElements.Add(where);
}
where.Latitude = value;
}
}
/// <summary>
/// The number of photos in the album.
/// </summary>
///
#if WindowsCE || PocketPC
#else
[Category("Meta Album Data"),
Description("Specifies the number of photos in the album.")]
#endif
[CLSCompliant(false)]
public uint NumPhotos
{
get
{
return Convert.ToUInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.NumPhotos));
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.NumPhotos, Convert.ToString(value));
}
}
/// <summary>
/// The number of remaining photo uploads allowed in this album.
/// This is equivalent to the user's maximum number of photos per
/// album (gphoto:maxPhotosPerAlbum) minus the number of photos
/// currently in the album (gphoto:numphotos).
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Meta Album Data"),
Description("Specifies the number of remaining photo uploads for the album.")]
#endif
[CLSCompliant(false)]
public uint NumPhotosRemaining
{
get
{
return Convert.ToUInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.NumPhotosRemaining));
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.NumPhotosRemaining, Convert.ToString(value));
}
}
/// <summary>
/// the number of comments on an album
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Commenting"),
Description("Specifies the number of comments for the album.")]
#endif
[CLSCompliant(false)]
public uint CommentCount
{
get
{
return Convert.ToUInt32(this.entry.GetPhotoExtensionValue(GPhotoNameTable.CommentCount));
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.CommentCount, Convert.ToString(value));
}
}
/// <summary>
/// is commenting enabled on an album
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Commenting"),
Description("Comments enabled?")]
#endif
public bool CommentingEnabled
{
get
{
return Convert.ToBoolean(this.entry.GetPhotoExtensionValue(GPhotoNameTable.CommentingEnabled));
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.CommentingEnabled, Utilities.ConvertBooleanToXSDString(value));
}
}
/// <summary>
/// the id of the album
/// </summary>
#if WindowsCE || PocketPC
#else
[Category("Base Album Data"),
Description("Specifies the id for the album.")]
#endif
public string Id
{
get
{
return this.entry.GetPhotoExtensionValue(GPhotoNameTable.Id);
}
set
{
this.entry.SetPhotoExtensionValue(GPhotoNameTable.Id, value);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.