context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.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_CSharp() { 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_CSharp() { await new VerifyCS.Test { TestCode = @" public class DoesNotMatter { } ", SolutionTransforms = { (solution, projectId) => solution.WithProjectAssemblyName(projectId, "AssemblyNameHasNoUnderScore") } }.RunAsync(); } [Fact] public async Task CA1707_ForNamespace_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" namespace OuterNamespace { namespace HasUnderScore_ { public class DoesNotMatter { } } } namespace HasNoUnderScore { public class DoesNotMatter { } }", GetCA1707CSharpResultAt(line: 4, column: 15, symbolKind: SymbolKind.Namespace, identifierNames: "OuterNamespace.HasUnderScore_")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForTypes_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class OuterType { public class UnderScoreInName_ { } private class UnderScoreInNameButPrivate_ { } internal class UnderScoreInNameButInternal_ { } } internal class OuterType2 { public class UnderScoreInNameButNotExternallyVisible_ { } } ", GetCA1707CSharpResultAt(line: 4, column: 18, symbolKind: SymbolKind.NamedType, identifierNames: "OuterType.UnderScoreInName_")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForFields_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" 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, _ } public class C { internal class C2 { public const int ConstField_ = 5; } } ", GetCA1707CSharpResultAt(line: 4, column: 26, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ConstField_"), GetCA1707CSharpResultAt(line: 5, column: 36, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.StaticReadOnlyField_"), GetCA1707CSharpResultAt(line: 16, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._EnumWithUnderscore"), GetCA1707CSharpResultAt(line: 17, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForMethods_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" 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 } }", GetCA1707CSharpResultAt(line: 4, column: 17, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicM1_()"), GetCA1707CSharpResultAt(line: 7, column: 20, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedM4_()"), GetCA1707CSharpResultAt(line: 12, column: 10, symbolKind: SymbolKind.Member, identifierNames: "I1.M_()"), GetCA1707CSharpResultAt(line: 18, column: 25, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.M2_()")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForProperties_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" 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 } }", GetCA1707CSharpResultAt(line: 4, column: 16, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicP1_"), GetCA1707CSharpResultAt(line: 7, column: 19, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedP4_"), GetCA1707CSharpResultAt(line: 12, column: 9, symbolKind: SymbolKind.Member, identifierNames: "I1.P_"), GetCA1707CSharpResultAt(line: 18, column: 24, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.P2_")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForEvents_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" 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 } }", GetCA1707CSharpResultAt(line: 6, column: 31, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicE1_"), GetCA1707CSharpResultAt(line: 9, column: 34, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedE4_"), GetCA1707CSharpResultAt(line: 14, column: 24, symbolKind: SymbolKind.Member, identifierNames: "I1.E_"), GetCA1707CSharpResultAt(line: 20, column: 39, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.E2_")); } [Fact] public async Task CA1707_ForDelegates_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" 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_); ", GetCA1707CSharpResultAt(2, 31, SymbolKind.DelegateParameter, "Dele", "intPublic_"), GetCA1707CSharpResultAt(2, 50, SymbolKind.DelegateParameter, "Dele", "stringPublic_"), GetCA1707CSharpResultAt(4, 30, SymbolKind.DelegateParameter, "Del<T>", "t_")); } [Fact] public async Task CA1707_ForMemberparameters_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" 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_) { } } 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_) { throw new System.NotImplementedException(); } public override void M1(int int_) { base.M1(int_); } }", GetCA1707CSharpResultAt(4, 30, SymbolKind.MemberParameter, "DoesNotMatter.PublicM1(int)", "int_"), GetCA1707CSharpResultAt(7, 36, SymbolKind.MemberParameter, "DoesNotMatter.ProtectedM4(int)", "int_"), GetCA1707CSharpResultAt(12, 16, SymbolKind.MemberParameter, "I.M(int)", "int_"), GetCA1707CSharpResultAt(24, 32, SymbolKind.MemberParameter, "Base.M1(int)", "int_"), GetCA1707CSharpResultAt(28, 33, SymbolKind.MemberParameter, "Base.M2(int)", "int_")); } [Fact] public async Task CA1707_ForTypeTypeParameters_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class DoesNotMatter<T_> { } class NoDiag<U_> { }", GetCA1707CSharpResultAt(2, 28, SymbolKind.TypeTypeParameter, "DoesNotMatter<T_>", "T_")); } [Fact] public async Task CA1707_ForMemberTypeParameters_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" 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_>() { throw new System.NotImplementedException(); } public override void M1<T_>() { base.M1<T_>(); } }", GetCA1707CSharpResultAt(4, 26, SymbolKind.MethodTypeParameter, "DoesNotMatter22.PublicM1<T1_>()", "T1_"), GetCA1707CSharpResultAt(7, 32, SymbolKind.MethodTypeParameter, "DoesNotMatter22.ProtectedM4<D_>()", "D_"), GetCA1707CSharpResultAt(12, 12, SymbolKind.MethodTypeParameter, "I.M<T_>()", "T_"), GetCA1707CSharpResultAt(25, 28, SymbolKind.MethodTypeParameter, "Base.M1<T_>()", "T_"), GetCA1707CSharpResultAt(29, 29, SymbolKind.MethodTypeParameter, "Base.M2<U_>()", "U_")); } [Fact, WorkItem(947, "https://github.com/dotnet/roslyn-analyzers/issues/947")] public async Task CA1707_ForOperators_CSharp() { 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_CSharp() { 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_NoDiagnostic() { 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_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public class SomeClass { public SomeClass() { var (_, d) = GetSomething(); } private static (string, double) GetSomething() => ("""", 0); }"); } [Fact] public async Task CA1707_CSharp_DiscardSymbolPatternMatching_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public class SomeClass { public SomeClass(object o) { switch (o) { case object _: break; } } }"); } [Fact] public async Task CA1707_CSharp_StandaloneDiscardSymbol_NoDiagnostic() { 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_GlobalAsaxSpecialMethods() { await VerifyCS.VerifyAnalyzerAsync(@" 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 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) {} }", GetCA1707CSharpResultAt(24, 20, SymbolKind.Member, "InvalidContext.Application_AuthenticateRequest(object, System.EventArgs)"), GetCA1707CSharpResultAt(25, 20, SymbolKind.Member, "InvalidContext.Application_BeginRequest(object, System.EventArgs)"), GetCA1707CSharpResultAt(26, 20, SymbolKind.Member, "InvalidContext.Application_End(object, System.EventArgs)"), GetCA1707CSharpResultAt(27, 20, SymbolKind.Member, "InvalidContext.Application_EndRequest(object, System.EventArgs)"), GetCA1707CSharpResultAt(28, 20, SymbolKind.Member, "InvalidContext.Application_Error(object, System.EventArgs)"), GetCA1707CSharpResultAt(29, 20, SymbolKind.Member, "InvalidContext.Application_Init(object, System.EventArgs)"), GetCA1707CSharpResultAt(30, 20, SymbolKind.Member, "InvalidContext.Application_Start(object, System.EventArgs)"), GetCA1707CSharpResultAt(31, 20, SymbolKind.Member, "InvalidContext.Session_End(object, System.EventArgs)"), GetCA1707CSharpResultAt(32, 20, SymbolKind.Member, "InvalidContext.Session_Start(object, System.EventArgs)")); } #endregion #region Visual Basic Tests [Fact] public async Task CA1707_ForAssembly_VisualBasic() { 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_VisualBasic() { await new VerifyVB.Test { TestCode = @" Public Class DoesNotMatter End Class ", SolutionTransforms = { (solution, projectId) => solution.WithProjectAssemblyName(projectId, "AssemblyNameHasNoUnderScore") } }.RunAsync(); } [Fact] public async Task CA1707_ForNamespace_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Namespace OuterNamespace Namespace HasUnderScore_ Public Class DoesNotMatter End Class End Namespace End Namespace Namespace HasNoUnderScore Public Class DoesNotMatter End Class End Namespace", GetCA1707BasicResultAt(line: 3, column: 15, symbolKind: SymbolKind.Namespace, identifierNames: "OuterNamespace.HasUnderScore_")); } [Fact] public async Task CA1707_ForTypes_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class OuterType Public Class UnderScoreInName_ End Class Private Class UnderScoreInNameButPrivate_ End Class End Class", GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.NamedType, identifierNames: "OuterType.UnderScoreInName_")); } [Fact] public async Task CA1707_ForFields_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" 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", GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ConstField_"), GetCA1707BasicResultAt(line: 4, column: 28, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.SharedReadOnlyField_"), GetCA1707BasicResultAt(line: 14, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._EnumWithUnderscore")); } [Fact] public async Task CA1707_ForMethods_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" 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", GetCA1707BasicResultAt(line: 3, column: 16, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicM1_()"), GetCA1707BasicResultAt(line: 11, column: 19, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedM4_()"), GetCA1707BasicResultAt(line: 16, column: 9, symbolKind: SymbolKind.Member, identifierNames: "I1.M_()"), GetCA1707BasicResultAt(line: 24, column: 28, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.M2_()")); } [Fact] public async Task CA1707_ForProperties_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" 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", GetCA1707BasicResultAt(line: 3, column: 21, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicP1_"), GetCA1707BasicResultAt(line: 26, column: 24, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedP4_"), GetCA1707BasicResultAt(line: 36, column: 14, symbolKind: SymbolKind.Member, identifierNames: "I1.P_"), GetCA1707BasicResultAt(line: 49, column: 33, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.P2_")); } [Fact] public async Task CA1707_ForEvents_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" 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 ' No diagnostic Public Shadows Event E2_ As System.EventHandler End Class", GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicE1_"), GetCA1707BasicResultAt(line: 8, column: 21, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedE4_"), GetCA1707BasicResultAt(line: 12, column: 11, symbolKind: SymbolKind.Member, identifierNames: "I1.E_"), GetCA1707BasicResultAt(line: 19, column: 18, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.E2_"), GetCA1707BasicResultAt(line: 25, column: 26, symbolKind: SymbolKind.Member, identifierNames: "Derives.E2_")); } [Fact] public async Task CA1707_ForDelegates_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" 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 ", GetCA1707BasicResultAt(2, 26, SymbolKind.DelegateParameter, "Dele", "intPublic_"), GetCA1707BasicResultAt(2, 49, SymbolKind.DelegateParameter, "Dele", "stringPublic_"), GetCA1707BasicResultAt(5, 36, SymbolKind.DelegateParameter, "Del(Of T)", "t_")); } [Fact] public async Task CA1707_ForMemberparameters_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@"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", GetCA1707BasicResultAt(2, 25, SymbolKind.MemberParameter, "DoesNotMatter.PublicM1(Integer)", "int_"), GetCA1707BasicResultAt(10, 31, SymbolKind.MemberParameter, "DoesNotMatter.ProtectedM4(Integer)", "int_"), GetCA1707BasicResultAt(15, 11, SymbolKind.MemberParameter, "I.M(Integer)", "int_"), GetCA1707BasicResultAt(25, 31, SymbolKind.MemberParameter, "Base.M1(Integer)", "int_"), GetCA1707BasicResultAt(28, 32, SymbolKind.MemberParameter, "Base.M2(Integer)", "int_")); } [Fact] public async Task CA1707_ForTypeTypeParameters_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class DoesNotMatter(Of T_) End Class Class NoDiag(Of U_) End Class", GetCA1707BasicResultAt(2, 31, SymbolKind.TypeTypeParameter, "DoesNotMatter(Of T_)", "T_")); } [Fact] public async Task CA1707_ForMemberTypeParameters_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" 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", GetCA1707BasicResultAt(3, 28, SymbolKind.MethodTypeParameter, "DoesNotMatter22.PublicM1(Of T1_)()", "T1_"), GetCA1707BasicResultAt(9, 34, SymbolKind.MethodTypeParameter, "DoesNotMatter22.ProtectedM4(Of D_)()", "D_"), GetCA1707BasicResultAt(14, 14, SymbolKind.MethodTypeParameter, "I.M(Of T_)()", "T_"), GetCA1707BasicResultAt(25, 34, SymbolKind.MethodTypeParameter, "Base.M1(Of T_)()", "T_"), GetCA1707BasicResultAt(28, 35, SymbolKind.MethodTypeParameter, "Base.M2(Of U_)()", "U_")); } [Fact, WorkItem(947, "https://github.com/dotnet/roslyn-analyzers/issues/947")] public async Task CA1707_ForOperators_VisualBasic() { 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_VisualBasic() { 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_GlobalAsaxSpecialMethods() { await VerifyVB.VerifyAnalyzerAsync(@" 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 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", GetCA1707BasicResultAt(41, 19, SymbolKind.Member, "InvalidContext.Application_AuthenticateRequest(Object, System.EventArgs)"), GetCA1707BasicResultAt(44, 19, SymbolKind.Member, "InvalidContext.Application_BeginRequest(Object, System.EventArgs)"), GetCA1707BasicResultAt(47, 19, SymbolKind.Member, "InvalidContext.Application_End(Object, System.EventArgs)"), GetCA1707BasicResultAt(50, 19, SymbolKind.Member, "InvalidContext.Application_EndRequest(Object, System.EventArgs)"), GetCA1707BasicResultAt(53, 19, SymbolKind.Member, "InvalidContext.Application_Error(Object, System.EventArgs)"), GetCA1707BasicResultAt(56, 19, SymbolKind.Member, "InvalidContext.Application_Init(Object, System.EventArgs)"), GetCA1707BasicResultAt(59, 19, SymbolKind.Member, "InvalidContext.Application_Start(Object, System.EventArgs)"), GetCA1707BasicResultAt(62, 19, SymbolKind.Member, "InvalidContext.Session_End(Object, System.EventArgs)"), GetCA1707BasicResultAt(65, 19, SymbolKind.Member, "InvalidContext.Session_Start(Object, System.EventArgs)")); } #endregion #region Helpers private static DiagnosticResult GetCA1707CSharpResultAt(int line, int column, SymbolKind symbolKind, params string[] identifierNames) => VerifyCS.Diagnostic(GetApproriateRule(symbolKind)) .WithLocation(line, column) .WithArguments(identifierNames); private static DiagnosticResult GetCA1707BasicResultAt(int line, int column, SymbolKind symbolKind, params string[] identifierNames) => VerifyVB.Diagnostic(GetApproriateRule(symbolKind)) .WithLocation(line, column) .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 System.Exception("Unknown Symbol Kind"), }; } private enum SymbolKind { Assembly, Namespace, NamedType, Member, DelegateParameter, MemberParameter, TypeTypeParameter, MethodTypeParameter } #endregion } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Model=UnityEngine.AssetGraph.DataModel.Version2; namespace UnityEngine.AssetGraph { public class FileUtility { public static void RemakeDirectory (string localFolderPath) { if (Directory.Exists(localFolderPath)) { FileUtility.DeleteDirectory(localFolderPath, true); } Directory.CreateDirectory(localFolderPath); } public static void CopyFile (string sourceFilePath, string targetFilePath) { var parentDirectoryPath = Path.GetDirectoryName(targetFilePath); Directory.CreateDirectory(parentDirectoryPath); File.Copy(sourceFilePath, targetFilePath, true); } public static void CopyTemplateFile (string sourceFilePath, string targetFilePath, string srcName, string dstName) { var parentDirectoryPath = Path.GetDirectoryName(targetFilePath); Directory.CreateDirectory(parentDirectoryPath); StreamReader r = File.OpenText(sourceFilePath); string contents = r.ReadToEnd(); contents = contents.Replace(srcName, dstName); File.WriteAllText(targetFilePath, contents); } public static void DeleteFileThenDeleteFolderIfEmpty (string localTargetFilePath) { File.Delete(localTargetFilePath); File.Delete(localTargetFilePath + Model.Settings.UNITY_METAFILE_EXTENSION); var directoryPath = Directory.GetParent(localTargetFilePath).FullName; var restFiles = GetFilePathsInFolder(directoryPath); if (!restFiles.Any()) { FileUtility.DeleteDirectory(directoryPath, true); File.Delete(directoryPath + Model.Settings.UNITY_METAFILE_EXTENSION); } } // Get all files under given path, including files in child folders public static List<string> GetAllFilePathsInFolder (string localFolderPath, bool includeHidden=false, bool includeMeta=!Model.Settings.IGNORE_META) { var filePaths = new List<string>(); if (string.IsNullOrEmpty(localFolderPath)) { return filePaths; } if (!Directory.Exists(localFolderPath)) { return filePaths; } GetFilePathsRecursively(localFolderPath, filePaths, includeHidden, includeMeta); return filePaths; } // Get files under given path public static List<string> GetFilePathsInFolder (string folderPath, bool includeHidden=false, bool includeMeta=!Model.Settings.IGNORE_META) { var filePaths = Directory.GetFiles(folderPath).Select(p=>p); if(!includeHidden) { filePaths = filePaths.Where(path => !(Path.GetFileName(path).StartsWith(Model.Settings.DOTSTART_HIDDEN_FILE_HEADSTRING))); } if (!includeMeta) { filePaths = filePaths.Where(path => !FileUtility.IsMetaFile(path)); } // Directory.GetFiles() returns platform dependent delimiter, so make sure replace with "/" if( Path.DirectorySeparatorChar != Model.Settings.UNITY_FOLDER_SEPARATOR ) { filePaths = filePaths.Select(filePath => filePath.Replace(Path.DirectorySeparatorChar.ToString(), Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())); } return filePaths.ToList(); } private static void GetFilePathsRecursively (string localFolderPath, List<string> filePaths, bool includeHidden=false, bool includeMeta=!Model.Settings.IGNORE_META) { var folders = Directory.GetDirectories(localFolderPath); foreach (var folder in folders) { GetFilePathsRecursively(folder, filePaths, includeHidden, includeMeta); } var files = GetFilePathsInFolder(localFolderPath, includeHidden, includeMeta); filePaths.AddRange(files); } /** create combination of path. delimiter is always '/'. */ public static string PathCombine (params string[] paths) { if (paths.Length < 2) { throw new ArgumentException("Argument must contain at least 2 strings to combine."); } var combinedPath = _PathCombine(paths[0], paths[1]); var restPaths = new string[paths.Length-2]; Array.Copy(paths, 2, restPaths, 0, restPaths.Length); foreach (var path in restPaths) combinedPath = _PathCombine(combinedPath, path); return combinedPath; } private static string _PathCombine (string head, string tail) { if (!head.EndsWith(Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())) { head = head + Model.Settings.UNITY_FOLDER_SEPARATOR; } if (string.IsNullOrEmpty(tail)) { return head; } if (tail.StartsWith(Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())) { tail = tail.Substring(1); } return Path.Combine(head, tail); } public static string GetPathWithProjectPath (string pathUnderProjectFolder) { var assetPath = Application.dataPath; var projectPath = Directory.GetParent(assetPath).ToString(); return FileUtility.PathCombine(projectPath, pathUnderProjectFolder); } public static string GetPathWithAssetsPath (string pathUnderAssetsFolder) { var assetPath = Application.dataPath; return FileUtility.PathCombine(assetPath, pathUnderAssetsFolder); } public static string ProjectPathWithSlash () { var assetPath = Application.dataPath; return Directory.GetParent(assetPath).ToString() + Model.Settings.UNITY_FOLDER_SEPARATOR; } public static bool IsMetaFile (string filePath) { if (filePath.EndsWith(Model.Settings.UNITY_METAFILE_EXTENSION)) return true; return false; } public static bool ContainsHiddenFiles (string filePath) { var pathComponents = filePath.Split(Model.Settings.UNITY_FOLDER_SEPARATOR); foreach (var path in pathComponents) { if (path.StartsWith(Model.Settings.DOTSTART_HIDDEN_FILE_HEADSTRING)) return true; } return false; } public static string EnsureCacheDirExists(BuildTarget t, Model.NodeData node, string name) { var cacheDir = FileUtility.PathCombine(AssetGraph.AssetGraphBasePath.CachePath, name, node.Id, SystemDataUtility.GetPathSafeTargetName(t)); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } if (!cacheDir.EndsWith(Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())) { cacheDir = cacheDir + Model.Settings.UNITY_FOLDER_SEPARATOR.ToString(); } return cacheDir; } public static string EnsureAssetBundleCacheDirExists(BuildTarget t, Model.NodeData node, bool remake = false) { var cacheDir = FileUtility.PathCombine(Model.Settings.Path.BundleBuilderCachePath, node.Id, BuildTargetUtility.TargetToAssetBundlePlatformName(t)); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } else { if(remake) { RemakeDirectory(cacheDir); } } return cacheDir; } public static void DeleteDirectory(string dirPath, bool isRecursive, bool forceDelete = true) { if (forceDelete) { RemoveFileAttributes (dirPath, isRecursive); } Directory.Delete(dirPath, isRecursive); } public static void RemoveFileAttributes(string dirPath, bool isRecursive) { foreach (var file in Directory.GetFiles (dirPath)) { File.SetAttributes (file, FileAttributes.Normal); } if(isRecursive) { foreach (var dir in Directory.GetDirectories (dirPath)) { RemoveFileAttributes (dir, isRecursive); } } } } }
// 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 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.AppEngine.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAuthorizedCertificatesClientTest { [xunit::FactAttribute] public void GetAuthorizedCertificateRequestObject() { moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient> mockGrpcClient = new moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient>(moq::MockBehavior.Strict); GetAuthorizedCertificateRequest request = new GetAuthorizedCertificateRequest { Name = "name1c9368b0", View = AuthorizedCertificateView.FullCertificate, }; AuthorizedCertificate expectedResponse = new AuthorizedCertificate { Name = "name1c9368b0", Id = "id74b70bb8", DisplayName = "display_name137f65c2", DomainNames = { "domain_names58aa2a78", }, ExpireTime = new wkt::Timestamp(), CertificateRawData = new CertificateRawData(), ManagedCertificate = new ManagedCertificate(), VisibleDomainMappings = { "visible_domain_mappings231706d8", }, DomainMappingsCount = 1489673528, }; mockGrpcClient.Setup(x => x.GetAuthorizedCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AuthorizedCertificatesClient client = new AuthorizedCertificatesClientImpl(mockGrpcClient.Object, null); AuthorizedCertificate response = client.GetAuthorizedCertificate(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAuthorizedCertificateRequestObjectAsync() { moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient> mockGrpcClient = new moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient>(moq::MockBehavior.Strict); GetAuthorizedCertificateRequest request = new GetAuthorizedCertificateRequest { Name = "name1c9368b0", View = AuthorizedCertificateView.FullCertificate, }; AuthorizedCertificate expectedResponse = new AuthorizedCertificate { Name = "name1c9368b0", Id = "id74b70bb8", DisplayName = "display_name137f65c2", DomainNames = { "domain_names58aa2a78", }, ExpireTime = new wkt::Timestamp(), CertificateRawData = new CertificateRawData(), ManagedCertificate = new ManagedCertificate(), VisibleDomainMappings = { "visible_domain_mappings231706d8", }, DomainMappingsCount = 1489673528, }; mockGrpcClient.Setup(x => x.GetAuthorizedCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizedCertificate>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AuthorizedCertificatesClient client = new AuthorizedCertificatesClientImpl(mockGrpcClient.Object, null); AuthorizedCertificate responseCallSettings = await client.GetAuthorizedCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizedCertificate responseCancellationToken = await client.GetAuthorizedCertificateAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateAuthorizedCertificateRequestObject() { moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient> mockGrpcClient = new moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient>(moq::MockBehavior.Strict); CreateAuthorizedCertificateRequest request = new CreateAuthorizedCertificateRequest { Parent = "parent7858e4d0", Certificate = new AuthorizedCertificate(), }; AuthorizedCertificate expectedResponse = new AuthorizedCertificate { Name = "name1c9368b0", Id = "id74b70bb8", DisplayName = "display_name137f65c2", DomainNames = { "domain_names58aa2a78", }, ExpireTime = new wkt::Timestamp(), CertificateRawData = new CertificateRawData(), ManagedCertificate = new ManagedCertificate(), VisibleDomainMappings = { "visible_domain_mappings231706d8", }, DomainMappingsCount = 1489673528, }; mockGrpcClient.Setup(x => x.CreateAuthorizedCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AuthorizedCertificatesClient client = new AuthorizedCertificatesClientImpl(mockGrpcClient.Object, null); AuthorizedCertificate response = client.CreateAuthorizedCertificate(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateAuthorizedCertificateRequestObjectAsync() { moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient> mockGrpcClient = new moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient>(moq::MockBehavior.Strict); CreateAuthorizedCertificateRequest request = new CreateAuthorizedCertificateRequest { Parent = "parent7858e4d0", Certificate = new AuthorizedCertificate(), }; AuthorizedCertificate expectedResponse = new AuthorizedCertificate { Name = "name1c9368b0", Id = "id74b70bb8", DisplayName = "display_name137f65c2", DomainNames = { "domain_names58aa2a78", }, ExpireTime = new wkt::Timestamp(), CertificateRawData = new CertificateRawData(), ManagedCertificate = new ManagedCertificate(), VisibleDomainMappings = { "visible_domain_mappings231706d8", }, DomainMappingsCount = 1489673528, }; mockGrpcClient.Setup(x => x.CreateAuthorizedCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizedCertificate>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AuthorizedCertificatesClient client = new AuthorizedCertificatesClientImpl(mockGrpcClient.Object, null); AuthorizedCertificate responseCallSettings = await client.CreateAuthorizedCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizedCertificate responseCancellationToken = await client.CreateAuthorizedCertificateAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateAuthorizedCertificateRequestObject() { moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient> mockGrpcClient = new moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient>(moq::MockBehavior.Strict); UpdateAuthorizedCertificateRequest request = new UpdateAuthorizedCertificateRequest { Name = "name1c9368b0", Certificate = new AuthorizedCertificate(), UpdateMask = new wkt::FieldMask(), }; AuthorizedCertificate expectedResponse = new AuthorizedCertificate { Name = "name1c9368b0", Id = "id74b70bb8", DisplayName = "display_name137f65c2", DomainNames = { "domain_names58aa2a78", }, ExpireTime = new wkt::Timestamp(), CertificateRawData = new CertificateRawData(), ManagedCertificate = new ManagedCertificate(), VisibleDomainMappings = { "visible_domain_mappings231706d8", }, DomainMappingsCount = 1489673528, }; mockGrpcClient.Setup(x => x.UpdateAuthorizedCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AuthorizedCertificatesClient client = new AuthorizedCertificatesClientImpl(mockGrpcClient.Object, null); AuthorizedCertificate response = client.UpdateAuthorizedCertificate(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateAuthorizedCertificateRequestObjectAsync() { moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient> mockGrpcClient = new moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient>(moq::MockBehavior.Strict); UpdateAuthorizedCertificateRequest request = new UpdateAuthorizedCertificateRequest { Name = "name1c9368b0", Certificate = new AuthorizedCertificate(), UpdateMask = new wkt::FieldMask(), }; AuthorizedCertificate expectedResponse = new AuthorizedCertificate { Name = "name1c9368b0", Id = "id74b70bb8", DisplayName = "display_name137f65c2", DomainNames = { "domain_names58aa2a78", }, ExpireTime = new wkt::Timestamp(), CertificateRawData = new CertificateRawData(), ManagedCertificate = new ManagedCertificate(), VisibleDomainMappings = { "visible_domain_mappings231706d8", }, DomainMappingsCount = 1489673528, }; mockGrpcClient.Setup(x => x.UpdateAuthorizedCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizedCertificate>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AuthorizedCertificatesClient client = new AuthorizedCertificatesClientImpl(mockGrpcClient.Object, null); AuthorizedCertificate responseCallSettings = await client.UpdateAuthorizedCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizedCertificate responseCancellationToken = await client.UpdateAuthorizedCertificateAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAuthorizedCertificateRequestObject() { moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient> mockGrpcClient = new moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient>(moq::MockBehavior.Strict); DeleteAuthorizedCertificateRequest request = new DeleteAuthorizedCertificateRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAuthorizedCertificate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AuthorizedCertificatesClient client = new AuthorizedCertificatesClientImpl(mockGrpcClient.Object, null); client.DeleteAuthorizedCertificate(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAuthorizedCertificateRequestObjectAsync() { moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient> mockGrpcClient = new moq::Mock<AuthorizedCertificates.AuthorizedCertificatesClient>(moq::MockBehavior.Strict); DeleteAuthorizedCertificateRequest request = new DeleteAuthorizedCertificateRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAuthorizedCertificateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AuthorizedCertificatesClient client = new AuthorizedCertificatesClientImpl(mockGrpcClient.Object, null); await client.DeleteAuthorizedCertificateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAuthorizedCertificateAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using Orleans.Providers; namespace Orleans.Runtime.Configuration { /// <summary> /// Orleans client configuration parameters. /// </summary> public class ClientConfiguration : MessagingConfiguration, ITraceConfiguration, IStatisticsConfiguration { /// <summary> /// Specifies the type of the gateway provider. /// </summary> public enum GatewayProviderType { None, // AzureTable, // use Azure, requires SystemStore element SqlServer, // use SQL, requires SystemStore element ZooKeeper, // use ZooKeeper, requires SystemStore element Config, // use Config based static list, requires Config element(s) Custom // use provider from third-party assembly } /// <summary> /// The name of this client. /// </summary> public static string ClientName = "Client"; private string traceFilePattern; private readonly DateTime creationTimestamp; public string SourceFile { get; private set; } /// <summary> /// The list fo the gateways to use. /// Each GatewayNode element specifies an outside grain client gateway node. /// If outside (non-Orleans) clients are to connect to the Orleans system, then at least one gateway node must be specified. /// Additional gateway nodes may be specified if desired, and will add some failure resilience and scalability. /// If multiple gateways are specified, then each client will select one from the list at random. /// </summary> public IList<IPEndPoint> Gateways { get; set; } /// <summary> /// </summary> public int PreferedGatewayIndex { get; set; } /// <summary> /// </summary> public GatewayProviderType GatewayProvider { get; set; } /// <summary> /// Specifies a unique identifier of this deployment. /// If the silos are deployed on Azure (run as workers roles), deployment id is set automatically by Azure runtime, /// accessible to the role via RoleEnvironment.DeploymentId static variable and is passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set by a deployment script in the OrleansConfiguration.xml file. /// </summary> public string DeploymentId { get; set; } /// <summary> /// Specifies the connection string for the gateway provider. /// If the silos are deployed on Azure (run as workers roles), DataConnectionString may be specified via RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"); /// In such a case it is taken from there and passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles and this config is specified via RoleEnvironment, /// this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set in the OrleansConfiguration.xml file. /// If not set at all, DevelopmentStorageAccount will be used. /// </summary> public string DataConnectionString { get; set; } /// <summary> /// When using ADO, identifies the underlying data provider for the gateway provider. This three-part naming syntax is also used when creating a new factory /// and for identifying the provider in an application configuration file so that the provider name, along with its associated /// connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx /// </summary> public string AdoInvariant { get; set; } public string CustomGatewayProviderAssemblyName { get; set; } public Severity DefaultTraceLevel { get; set; } public IList<Tuple<string, Severity>> TraceLevelOverrides { get; private set; } public bool TraceToConsole { get; set; } public int LargeMessageWarningThreshold { get; set; } public bool PropagateActivityId { get; set; } public int BulkMessageLimit { get; set; } /// <summary> /// </summary> public AddressFamily PreferredFamily { get; set; } /// <summary> /// The Interface attribute specifies the name of the network interface to use to work out an IP address for this machine. /// </summary> public string NetInterface { get; private set; } /// <summary> /// The Port attribute specifies the specific listen port for this client machine. /// If value is zero, then a random machine-assigned port number will be used. /// </summary> public int Port { get; private set; } /// <summary> /// </summary> public string DNSHostName { get; private set; } // This is a true host name, no IP address. It is NOT settable, equals Dns.GetHostName(). /// <summary> /// </summary> public TimeSpan GatewayListRefreshPeriod { get; set; } public string StatisticsProviderName { get; set; } public TimeSpan StatisticsMetricsTableWriteInterval { get; set; } public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } public TimeSpan StatisticsLogWriteInterval { get; set; } public bool StatisticsWriteLogStatisticsToTable { get; set; } public StatisticsLevel StatisticsCollectionLevel { get; set; } public LimitManager LimitManager { get; private set; } private static readonly TimeSpan DEFAULT_GATEWAY_LIST_REFRESH_PERIOD = TimeSpan.FromMinutes(1); private static readonly TimeSpan DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = Constants.INFINITE_TIMESPAN; private static readonly TimeSpan DEFAULT_STATS_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5); /// <summary> /// </summary> public bool UseAzureSystemStore { get { return GatewayProvider == GatewayProviderType.AzureTable && !String.IsNullOrWhiteSpace(DeploymentId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } /// <summary> /// </summary> public bool UseSqlSystemStore { get { return GatewayProvider == GatewayProviderType.SqlServer && !String.IsNullOrWhiteSpace(DeploymentId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } private bool HasStaticGateways { get { return Gateways != null && Gateways.Count > 0; } } /// <summary> /// </summary> public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; } public string TraceFilePattern { get { return traceFilePattern; } set { traceFilePattern = value; ConfigUtilities.SetTraceFileName(this, ClientName, this.creationTimestamp); } } public string TraceFileName { get; set; } /// <summary> /// </summary> public ClientConfiguration() : base(false) { creationTimestamp = DateTime.UtcNow; SourceFile = null; PreferedGatewayIndex = -1; Gateways = new List<IPEndPoint>(); GatewayProvider = GatewayProviderType.None; PreferredFamily = AddressFamily.InterNetwork; NetInterface = null; Port = 0; DNSHostName = Dns.GetHostName(); DeploymentId = Environment.UserName; DataConnectionString = ""; // Assume the ado invariant is for sql server storage if not explicitly specified AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER; DefaultTraceLevel = Severity.Info; TraceLevelOverrides = new List<Tuple<string, Severity>>(); TraceToConsole = true; TraceFilePattern = "{0}-{1}.log"; LargeMessageWarningThreshold = Constants.LARGE_OBJECT_HEAP_THRESHOLD; PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; BulkMessageLimit = Constants.DEFAULT_LOGGER_BULK_MESSAGE_LIMIT; GatewayListRefreshPeriod = DEFAULT_GATEWAY_LIST_REFRESH_PERIOD; StatisticsProviderName = null; StatisticsMetricsTableWriteInterval = DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD; StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD; StatisticsLogWriteInterval = DEFAULT_STATS_LOG_WRITE_PERIOD; StatisticsWriteLogStatisticsToTable = true; StatisticsCollectionLevel = NodeConfiguration.DEFAULT_STATS_COLLECTION_LEVEL; LimitManager = new LimitManager(); ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>(); } public void Load(TextReader input) { var xml = new XmlDocument(); var xmlReader = XmlReader.Create(input); xml.Load(xmlReader); XmlElement root = xml.DocumentElement; LoadFromXml(root); } internal void LoadFromXml(XmlElement root) { foreach (XmlNode node in root.ChildNodes) { var child = node as XmlElement; if (child != null) { switch (child.LocalName) { case "Gateway": Gateways.Add(ConfigUtilities.ParseIPEndPoint(child).GetResult()); if (GatewayProvider == GatewayProviderType.None) { GatewayProvider = GatewayProviderType.Config; } break; case "Azure": // Throw exception with explicit deprecation error message throw new OrleansException( "The Azure element has been deprecated -- use SystemStore element instead."); case "SystemStore": if (child.HasAttribute("SystemStoreType")) { var sst = child.GetAttribute("SystemStoreType"); GatewayProvider = (GatewayProviderType)Enum.Parse(typeof(GatewayProviderType), sst); } if (child.HasAttribute("CustomGatewayProviderAssemblyName")) { CustomGatewayProviderAssemblyName = child.GetAttribute("CustomGatewayProviderAssemblyName"); if (CustomGatewayProviderAssemblyName.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"CustomGatewayProviderAssemblyName\""); if (GatewayProvider != GatewayProviderType.Custom) throw new FormatException("SystemStoreType should be \"Custom\" when CustomGatewayProviderAssemblyName is specified"); } if (child.HasAttribute("DeploymentId")) { DeploymentId = child.GetAttribute("DeploymentId"); } if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME)) { DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionString)) { throw new FormatException("SystemStore.DataConnectionString cannot be blank"); } if (GatewayProvider == GatewayProviderType.None) { // Assume the connection string is for Azure storage if not explicitly specified GatewayProvider = GatewayProviderType.AzureTable; } } if (child.HasAttribute(Constants.ADO_INVARIANT_NAME)) { AdoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME); if (String.IsNullOrWhiteSpace(AdoInvariant)) { throw new FormatException("SystemStore.AdoInvariant cannot be blank"); } } break; case "Tracing": ConfigUtilities.ParseTracing(this, child, ClientName); break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, ClientName); break; case "Limits": ConfigUtilities.ParseLimitValues(LimitManager, child, ClientName); break; case "Debug": break; case "Messaging": base.Load(child); break; case "LocalAddress": if (child.HasAttribute("PreferredFamily")) { PreferredFamily = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid address family for the PreferredFamily attribute on the LocalAddress element"); } else { throw new FormatException("Missing PreferredFamily attribute on the LocalAddress element"); } if (child.HasAttribute("Interface")) { NetInterface = child.GetAttribute("Interface"); } if (child.HasAttribute("Port")) { Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Invalid integer value for the Port attribute on the LocalAddress element"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child); break; default: if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal)) { var providerCategory = ProviderCategoryConfiguration.Load(child); if (ProviderConfigurations.ContainsKey(providerCategory.Name)) { var existingCategory = ProviderConfigurations[providerCategory.Name]; existingCategory.Merge(providerCategory); } else { ProviderConfigurations.Add(providerCategory.Name, providerCategory); } } break; } } } } /// <summary> /// </summary> public static ClientConfiguration LoadFromFile(string fileName) { if (fileName == null) { return null; } using (TextReader input = File.OpenText(fileName)) { var config = new ClientConfiguration(); config.Load(input); config.SourceFile = fileName; return config; } } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="Orleans.Streams.IStreamProvider"/> stream</typeparam> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to stream provider upon initialization</param> public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider { TypeInfo providerTypeInfo = typeof(T).GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(typeof(T))) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given stream provider. /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to the stream provider upon initialization </param> public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Retrieves an existing provider configuration /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="config">The provider configuration, if exists</param> /// <returns>True if a configuration for this provider already exists, false otherwise.</returns> public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config) { return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config); } /// <summary> /// Retrieves an enumeration of all currently configured provider configurations. /// </summary> /// <returns>An enumeration of all currently configured provider configurations.</returns> public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations() { return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations); } /// <summary> /// Loads the configuration from the standard paths, looking up the directory hierarchy /// </summary> /// <returns>Client configuration data if a configuration file was found.</returns> /// <exception cref="FileNotFoundException">Thrown if no configuration file could be found in any of the standard locations</exception> public static ClientConfiguration StandardLoad() { var fileName = ConfigUtilities.FindConfigFile(false); // Throws FileNotFoundException return LoadFromFile(fileName); } public override string ToString() { var sb = new StringBuilder(); sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo()); sb.Append(" Host: ").AppendLine(Dns.GetHostName()); sb.Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.AppendLine("Client Configuration:"); sb.Append(" Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile)); sb.Append(" Start time: ").AppendLine(LogFormatter.PrintDate(DateTime.UtcNow)); sb.Append(" Gateway Provider: ").Append(GatewayProvider); if (GatewayProvider == GatewayProviderType.None) { sb.Append(". Gateway Provider that will be used instead: ").Append(GatewayProviderToUse); } sb.AppendLine(); if (Gateways != null && Gateways.Count > 0 ) { sb.AppendFormat(" Gateways[{0}]:", Gateways.Count).AppendLine(); foreach (var endpoint in Gateways) { sb.Append(" ").AppendLine(endpoint.ToString()); } } else { sb.Append(" Gateways: ").AppendLine("Unspecified"); } sb.Append(" Preferred Gateway Index: ").AppendLine(PreferedGatewayIndex.ToString()); if (Gateways != null && PreferedGatewayIndex >= 0 && PreferedGatewayIndex < Gateways.Count) { sb.Append(" Preferred Gateway Address: ").AppendLine(Gateways[PreferedGatewayIndex].ToString()); } sb.Append(" GatewayListRefreshPeriod: ").Append(GatewayListRefreshPeriod).AppendLine(); if (!String.IsNullOrEmpty(DeploymentId) || !String.IsNullOrEmpty(DataConnectionString)) { sb.Append(" Azure:").AppendLine(); sb.Append(" DeploymentId: ").Append(DeploymentId).AppendLine(); string dataConnectionInfo = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); // Don't print Azure account keys in log files sb.Append(" DataConnectionString: ").Append(dataConnectionInfo).AppendLine(); } if (!string.IsNullOrWhiteSpace(NetInterface)) { sb.Append(" Network Interface: ").AppendLine(NetInterface); } if (Port != 0) { sb.Append(" Network Port: ").Append(Port).AppendLine(); } sb.Append(" Preferred Address Family: ").AppendLine(PreferredFamily.ToString()); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Client Name: ").AppendLine(ClientName); sb.Append(ConfigUtilities.TraceConfigurationToString(this)); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); sb.AppendFormat(base.ToString()); sb.Append(" .NET: ").AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return sb.ToString(); } internal GatewayProviderType GatewayProviderToUse { get { // order is important here for establishing defaults. if (GatewayProvider != GatewayProviderType.None) return GatewayProvider; if (UseAzureSystemStore) return GatewayProviderType.AzureTable; return HasStaticGateways ? GatewayProviderType.Config : GatewayProviderType.None; } } internal void CheckGatewayProviderSettings() { switch (GatewayProvider) { case GatewayProviderType.AzureTable: if (!UseAzureSystemStore) throw new ArgumentException("Config specifies Azure based GatewayProviderType, but Azure element is not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.Config: if (!HasStaticGateways) throw new ArgumentException("Config specifies Config based GatewayProviderType, but Gateway element(s) is/are not specified.", "GatewayProvider"); break; case GatewayProviderType.Custom: if (String.IsNullOrEmpty(CustomGatewayProviderAssemblyName)) throw new ArgumentException("Config specifies Custom GatewayProviderType, but CustomGatewayProviderAssemblyName attribute is not specified", "GatewayProvider"); break; case GatewayProviderType.None: if (!UseAzureSystemStore && !HasStaticGateways) throw new ArgumentException("Config does not specify GatewayProviderType, and also does not have the adequate defaults: no Azure and or Gateway element(s) are specified.","GatewayProvider"); break; case GatewayProviderType.SqlServer: if (!UseSqlSystemStore) throw new ArgumentException("Config specifies SqlServer based GatewayProviderType, but DeploymentId or DataConnectionString are not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.ZooKeeper: break; } } /// <summary> /// Retuurns a ClientConfiguration object for connecting to a local silo (for testing). /// </summary> /// <param name="gatewayPort">Client gateway TCP port</param> /// <returns>ClientConfiguration object that can be passed to GrainClient class for initialization</returns> public static ClientConfiguration LocalhostSilo(int gatewayPort = 40000) { var config = new ClientConfiguration {GatewayProvider = GatewayProviderType.Config}; config.Gateways.Add(new IPEndPoint(IPAddress.Loopback, gatewayPort)); return config; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Cryptography { [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class AesCryptoServiceProvider : System.Security.Cryptography.Aes { public AesCryptoServiceProvider() { } public override int FeedbackSize { get { throw null; } set { } } public override int BlockSize { get { throw null; } set { } } public override byte[] IV { get { throw null; } set { } } public override byte[] Key { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } } public sealed partial class CspKeyContainerInfo { public CspKeyContainerInfo(System.Security.Cryptography.CspParameters parameters) { } public bool Accessible { get { throw null; } } public bool Exportable { get { throw null; } } public bool HardwareDevice { get { throw null; } } public string KeyContainerName { get { throw null; } } public System.Security.Cryptography.KeyNumber KeyNumber { get { throw null; } } public bool MachineKeyStore { get { throw null; } } public bool Protected { get { throw null; } } public string ProviderName { get { throw null; } } public int ProviderType { get { throw null; } } public bool RandomlyGenerated { get { throw null; } } public bool Removable { get { throw null; } } public string UniqueKeyContainerName { get { throw null; } } } public sealed partial class CspParameters { public string KeyContainerName; public int KeyNumber; public string ProviderName; public int ProviderType; public CspParameters() { } public CspParameters(int dwTypeIn) { } public CspParameters(int dwTypeIn, string strProviderNameIn) { } public CspParameters(int dwTypeIn, string strProviderNameIn, string strContainerNameIn) { } public System.Security.Cryptography.CspProviderFlags Flags { get { throw null; } set { } } [System.CLSCompliantAttribute(false)] public System.Security.SecureString KeyPassword { get { throw null; } set { } } public System.IntPtr ParentWindowHandle { get { throw null; } set { } } } [System.FlagsAttribute] public enum CspProviderFlags { CreateEphemeralKey = 128, NoFlags = 0, NoPrompt = 64, UseArchivableKey = 16, UseDefaultKeyContainer = 2, UseExistingKey = 8, UseMachineKeyStore = 1, UseNonExportableKey = 4, UseUserProtectedKey = 32, } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class DESCryptoServiceProvider : System.Security.Cryptography.DES { public DESCryptoServiceProvider() { } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override void GenerateIV() { } public override void GenerateKey() { } } public sealed partial class DSACryptoServiceProvider : System.Security.Cryptography.DSA, System.Security.Cryptography.ICspAsymmetricAlgorithm { public DSACryptoServiceProvider() { } public DSACryptoServiceProvider(int dwKeySize) { } public DSACryptoServiceProvider(int dwKeySize, System.Security.Cryptography.CspParameters parameters) { } public DSACryptoServiceProvider(System.Security.Cryptography.CspParameters parameters) { } public System.Security.Cryptography.CspKeyContainerInfo CspKeyContainerInfo { get { throw null; } } public override string KeyExchangeAlgorithm { get { throw null; } } public override int KeySize { get { throw null; } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public bool PersistKeyInCsp { get { throw null; } set { } } public bool PublicOnly { get { throw null; } } public override string SignatureAlgorithm { get { throw null; } } public static bool UseMachineKeyStore { get { throw null; } set { } } public override byte[] CreateSignature(byte[] rgbHash) { throw null; } protected override void Dispose(bool disposing) { } public byte[] ExportCspBlob(bool includePrivateParameters) { throw null; } public override System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters) { throw null; } protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public void ImportCspBlob(byte[] keyBlob) { } public override void ImportParameters(System.Security.Cryptography.DSAParameters parameters) { } public byte[] SignData(byte[] buffer) { throw null; } public byte[] SignData(byte[] buffer, int offset, int count) { throw null; } public byte[] SignData(System.IO.Stream inputStream) { throw null; } public byte[] SignHash(byte[] rgbHash, string str) { throw null; } public bool VerifyData(byte[] rgbData, byte[] rgbSignature) { throw null; } public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { throw null; } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; } } public partial interface ICspAsymmetricAlgorithm { System.Security.Cryptography.CspKeyContainerInfo CspKeyContainerInfo { get; } byte[] ExportCspBlob(bool includePrivateParameters); void ImportCspBlob(byte[] rawData); } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class MD5CryptoServiceProvider : System.Security.Cryptography.MD5 { public MD5CryptoServiceProvider() { } protected sealed override void Dispose(bool disposing) { } protected override void HashCore(byte[] array, int ibStart, int cbSize) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } } public enum KeyNumber { Exchange = 1, Signature = 2, } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public partial class PasswordDeriveBytes : System.Security.Cryptography.DeriveBytes { public PasswordDeriveBytes(byte[] password, byte[] salt) { } public PasswordDeriveBytes(byte[] password, byte[] salt, System.Security.Cryptography.CspParameters cspParams) { } public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations) { } public PasswordDeriveBytes(byte[] password, byte[] salt, string hashName, int iterations, System.Security.Cryptography.CspParameters cspParams) { } public PasswordDeriveBytes(string strPassword, byte[] rgbSalt) { } public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, System.Security.Cryptography.CspParameters cspParams) { } public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations) { } public PasswordDeriveBytes(string strPassword, byte[] rgbSalt, string strHashName, int iterations, System.Security.Cryptography.CspParameters cspParams) { } public string HashName { get { throw null; } set { } } public int IterationCount { get { throw null; } set { } } public byte[] Salt { get { throw null; } set { } } public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } [System.ObsoleteAttribute("Rfc2898DeriveBytes replaces PasswordDeriveBytes for deriving key material from a password and is preferred in new applications.")] #pragma warning disable 0809 public override byte[] GetBytes(int cb) { throw null; } #pragma warning restore 0809 public override void Reset() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class RC2CryptoServiceProvider : System.Security.Cryptography.RC2 { public RC2CryptoServiceProvider() { } public override int EffectiveKeySize { get { throw null; } set { } } public bool UseSalt { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override void GenerateIV() { } public override void GenerateKey() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class RNGCryptoServiceProvider : System.Security.Cryptography.RandomNumberGenerator { public RNGCryptoServiceProvider() { } public RNGCryptoServiceProvider(byte[] rgb) { } public RNGCryptoServiceProvider(System.Security.Cryptography.CspParameters cspParams) { } public RNGCryptoServiceProvider(string str) { } protected override void Dispose(bool disposing) { } public override void GetBytes(byte[] data) { } public override void GetNonZeroBytes(byte[] data) { } } public sealed partial class RSACryptoServiceProvider : System.Security.Cryptography.RSA, System.Security.Cryptography.ICspAsymmetricAlgorithm { public RSACryptoServiceProvider() { } public RSACryptoServiceProvider(int dwKeySize) { } public RSACryptoServiceProvider(int dwKeySize, System.Security.Cryptography.CspParameters parameters) { } public RSACryptoServiceProvider(System.Security.Cryptography.CspParameters parameters) { } public System.Security.Cryptography.CspKeyContainerInfo CspKeyContainerInfo { get { throw null; } } public override string KeyExchangeAlgorithm { get { throw null; } } public override int KeySize { get { throw null; } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public bool PersistKeyInCsp { get { throw null; } set { } } public bool PublicOnly { get { throw null; } } public override string SignatureAlgorithm { get { throw null; } } public static bool UseMachineKeyStore { get { throw null; } set { } } public byte[] Decrypt(byte[] rgb, bool fOAEP) { throw null; } public override byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; } public override byte[] DecryptValue(byte[] rgb) { throw null; } protected override void Dispose(bool disposing) { } public byte[] Encrypt(byte[] rgb, bool fOAEP) { throw null; } public override byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; } public override byte[] EncryptValue(byte[] rgb) { throw null; } public byte[] ExportCspBlob(bool includePrivateParameters) { throw null; } public override System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters) { throw null; } protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public void ImportCspBlob(byte[] keyBlob) { } public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters) { } public byte[] SignData(byte[] buffer, int offset, int count, object halg) { throw null; } public byte[] SignData(byte[] buffer, object halg) { throw null; } public byte[] SignData(System.IO.Stream inputStream, object halg) { throw null; } public override byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public byte[] SignHash(byte[] rgbHash, string str) { throw null; } public bool VerifyData(byte[] buffer, object halg, byte[] signature) { throw null; } public override bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA1CryptoServiceProvider : System.Security.Cryptography.SHA1 { public SHA1CryptoServiceProvider() { } protected sealed override void Dispose(bool disposing) { } protected override void HashCore(byte[] array, int ibStart, int cbSize) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA256CryptoServiceProvider : System.Security.Cryptography.SHA256 { public SHA256CryptoServiceProvider() { } protected sealed override void Dispose(bool disposing) { } protected override void HashCore(byte[] array, int ibStart, int cbSize) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA384CryptoServiceProvider : System.Security.Cryptography.SHA384 { public SHA384CryptoServiceProvider() { } protected sealed override void Dispose(bool disposing) { } protected override void HashCore(byte[] array, int ibStart, int cbSize) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA512CryptoServiceProvider : System.Security.Cryptography.SHA512 { public SHA512CryptoServiceProvider() { } protected sealed override void Dispose(bool disposing) { } protected override void HashCore(byte[] array, int ibStart, int cbSize) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class TripleDESCryptoServiceProvider : System.Security.Cryptography.TripleDES { public TripleDESCryptoServiceProvider() { } public override int FeedbackSize { get { throw null; } set { } } public override int BlockSize { get { throw null; } set { } } public override byte[] IV { get { throw null; } set { } } public override byte[] Key { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } } }
using System; using System.Diagnostics; using System.Text; namespace Community.CsharpSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { /* ** 2005 February 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that used to generate VDBE code ** that implements the ALTER TABLE command. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" /* ** The code in this file only exists if we are not omitting the ** ALTER TABLE logic from the build. */ #if !SQLITE_OMIT_ALTERTABLE /* ** This function is used by SQL generated to implement the ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or ** CREATE INDEX command. The second is a table name. The table name in ** the CREATE TABLE or CREATE INDEX statement is replaced with the third ** argument and the result returned. Examples: ** ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') ** . 'CREATE TABLE def(a, b, c)' ** ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') ** . 'CREATE INDEX i ON def(a, b, c)' */ static void renameTableFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { string bResult = sqlite3_value_text( argv[0] ); string zSql = bResult == null ? "" : bResult; string zTableName = sqlite3_value_text( argv[1] ); int token = 0; Token tname = new Token(); int zCsr = 0; int zLoc = 0; int len = 0; string zRet; sqlite3 db = sqlite3_context_db_handle( context ); UNUSED_PARAMETER( NotUsed ); /* The principle used to locate the table name in the CREATE TABLE ** statement is that the table name is the first non-space token that ** is immediately followed by a TK_LP or TK_USING token. */ if ( zSql != "" ) { do { if ( zCsr == zSql.Length ) { /* Ran out of input before finding an opening bracket. Return NULL. */ return; } /* Store the token that zCsr points to in tname. */ zLoc = zCsr; tname.z = zSql.Substring( zCsr );//(char*)zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token ); } while ( token == TK_SPACE ); Debug.Assert( len > 0 ); } while ( token != TK_LP && token != TK_USING ); zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ), zTableName, zSql.Substring( zLoc + tname.n ) ); sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC ); } } /* ** This C function implements an SQL user function that is used by SQL code ** generated by the ALTER TABLE ... RENAME command to modify the definition ** of any foreign key constraints that use the table being renamed as the ** parent table. It is passed three arguments: ** ** 1) The complete text of the CREATE TABLE statement being modified, ** 2) The old name of the table being renamed, and ** 3) The new name of the table being renamed. ** ** It returns the new CREATE TABLE statement. For example: ** ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3') ** -> 'CREATE TABLE t1(a REFERENCES t3)' */ #if !SQLITE_OMIT_FOREIGN_KEY static void renameParentFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { sqlite3 db = sqlite3_context_db_handle( context ); string zOutput = ""; string zResult; string zInput = sqlite3_value_text( argv[0] ); string zOld = sqlite3_value_text( argv[1] ); string zNew = sqlite3_value_text( argv[2] ); int zIdx; /* Pointer to token */ int zLeft = 0; /* Pointer to remainder of String */ int n = 0; /* Length of token z */ int token = 0; /* Type of token */ UNUSED_PARAMETER( NotUsed ); for ( zIdx = 0; zIdx < zInput.Length; zIdx += n )//z=zInput; *z; z=z+n) { n = sqlite3GetToken( zInput, zIdx, ref token ); if ( token == TK_REFERENCES ) { string zParent; do { zIdx += n; n = sqlite3GetToken( zInput, zIdx, ref token ); } while ( token == TK_SPACE ); zParent = zIdx + n < zInput.Length ? zInput.Substring( zIdx, n ) : "";//sqlite3DbStrNDup(db, zIdx, n); if ( String.IsNullOrEmpty( zParent ) ) break; sqlite3Dequote( ref zParent ); if ( zOld.Equals( zParent, StringComparison.OrdinalIgnoreCase) ) { string zOut = sqlite3MPrintf( db, "%s%.*s\"%w\"", zOutput, zIdx - zLeft, zInput.Substring( zLeft ), zNew ); sqlite3DbFree( db, ref zOutput ); zOutput = zOut; zIdx += n;// zInput = &z[n]; zLeft = zIdx; } sqlite3DbFree( db, ref zParent ); } } zResult = sqlite3MPrintf( db, "%s%s", zOutput, zInput.Substring( zLeft ) ); sqlite3_result_text( context, zResult, -1, SQLITE_DYNAMIC ); sqlite3DbFree( db, ref zOutput ); } #endif #if !SQLITE_OMIT_TRIGGER /* This function is used by SQL generated to implement the ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER ** statement. The second is a table name. The table name in the CREATE ** TRIGGER statement is replaced with the third argument and the result ** returned. This is analagous to renameTableFunc() above, except for CREATE ** TRIGGER, not CREATE INDEX and CREATE TABLE. */ static void renameTriggerFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { string zSql = sqlite3_value_text( argv[0] ); string zTableName = sqlite3_value_text( argv[1] ); int token = 0; Token tname = new Token(); int dist = 3; int zCsr = 0; int zLoc = 0; int len = 1; string zRet; sqlite3 db = sqlite3_context_db_handle( context ); UNUSED_PARAMETER( NotUsed ); /* The principle used to locate the table name in the CREATE TRIGGER ** statement is that the table name is the first token that is immediatedly ** preceded by either TK_ON or TK_DOT and immediatedly followed by one ** of TK_WHEN, TK_BEGIN or TK_FOR. */ if ( zSql != null ) { do { if ( zCsr == zSql.Length ) { /* Ran out of input before finding the table name. Return NULL. */ return; } /* Store the token that zCsr points to in tname. */ zLoc = zCsr; tname.z = zSql.Substring( zCsr, len );//(char*)zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token ); } while ( token == TK_SPACE ); Debug.Assert( len > 0 ); /* Variable 'dist' stores the number of tokens read since the most ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN ** token is read and 'dist' equals 2, the condition stated above ** to be met. ** ** Note that ON cannot be a database, table or column name, so ** there is no need to worry about syntax like ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. */ dist++; if ( token == TK_DOT || token == TK_ON ) { dist = 0; } } while ( dist != 2 || ( token != TK_WHEN && token != TK_FOR && token != TK_BEGIN ) ); /* Variable tname now contains the token that is the old table-name ** in the CREATE TRIGGER statement. */ zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ), zTableName, zSql.Substring( zLoc + tname.n ) ); sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC ); } } #endif // * !SQLITE_OMIT_TRIGGER */ /* ** Register built-in functions used to help implement ALTER TABLE */ static FuncDef[] aAlterTableFuncs; static void sqlite3AlterFunctions() { aAlterTableFuncs = new FuncDef[] { FUNCTION("sqlite_rename_table", 2, 0, 0, renameTableFunc), #if !SQLITE_OMIT_TRIGGER FUNCTION("sqlite_rename_trigger", 2, 0, 0, renameTriggerFunc), #endif #if !SQLITE_OMIT_FOREIGN_KEY FUNCTION("sqlite_rename_parent", 3, 0, 0, renameParentFunc), #endif }; int i; #if SQLITE_OMIT_WSD FuncDefHash pHash = GLOBAL(FuncDefHash, sqlite3GlobalFunctions); FuncDef[] aFunc = GLOBAL(FuncDef, aAlterTableFuncs); #else FuncDefHash pHash = sqlite3GlobalFunctions; FuncDef[] aFunc = aAlterTableFuncs; #endif for ( i = 0; i < ArraySize( aAlterTableFuncs ); i++ ) { sqlite3FuncDefInsert( pHash, aFunc[i] ); } } /* ** This function is used to create the text of expressions of the form: ** ** name=<constant1> OR name=<constant2> OR ... ** ** If argument zWhere is NULL, then a pointer string containing the text ** "name=<constant>" is returned, where <constant> is the quoted version ** of the string passed as argument zConstant. The returned buffer is ** allocated using sqlite3DbMalloc(). It is the responsibility of the ** caller to ensure that it is eventually freed. ** ** If argument zWhere is not NULL, then the string returned is ** "<where> OR name=<constant>", where <where> is the contents of zWhere. ** In this case zWhere is passed to sqlite3DbFree() before returning. ** */ static string whereOrName( sqlite3 db, string zWhere, string zConstant ) { string zNew; if ( String.IsNullOrEmpty( zWhere ) ) { zNew = sqlite3MPrintf( db, "name=%Q", zConstant ); } else { zNew = sqlite3MPrintf( db, "%s OR name=%Q", zWhere, zConstant ); sqlite3DbFree( db, ref zWhere ); } return zNew; } #if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER) /* ** Generate the text of a WHERE expression which can be used to select all ** tables that have foreign key constraints that refer to table pTab (i.e. ** constraints for which pTab is the parent table) from the sqlite_master ** table. */ static string whereForeignKeys( Parse pParse, Table pTab ) { FKey p; string zWhere = ""; for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo ) { zWhere = whereOrName( pParse.db, zWhere, p.pFrom.zName ); } return zWhere; } #endif /* ** Generate the text of a WHERE expression which can be used to select all ** temporary triggers on table pTab from the sqlite_temp_master table. If ** table pTab has no temporary triggers, or is itself stored in the ** temporary database, NULL is returned. */ static string whereTempTriggers( Parse pParse, Table pTab ) { Trigger pTrig; string zWhere = ""; Schema pTempSchema = pParse.db.aDb[1].pSchema; /* Temp db schema */ /* If the table is not located in the temp.db (in which case NULL is ** returned, loop through the tables list of triggers. For each trigger ** that is not part of the temp.db schema, add a clause to the WHERE ** expression being built up in zWhere. */ if ( pTab.pSchema != pTempSchema ) { sqlite3 db = pParse.db; for ( pTrig = sqlite3TriggerList( pParse, pTab ); pTrig != null; pTrig = pTrig.pNext ) { if ( pTrig.pSchema == pTempSchema ) { zWhere = whereOrName( db, zWhere, pTrig.zName ); } } } if ( !String.IsNullOrEmpty( zWhere ) ) { zWhere = sqlite3MPrintf( pParse.db, "type='trigger' AND (%s)", zWhere ); //sqlite3DbFree( pParse.db, ref zWhere ); //zWhere = zNew; } return zWhere; } /* ** Generate code to drop and reload the internal representation of table ** pTab from the database, including triggers and temporary triggers. ** Argument zName is the name of the table in the database schema at ** the time the generated code is executed. This can be different from ** pTab.zName if this function is being called to code part of an ** "ALTER TABLE RENAME TO" statement. */ static void reloadTableSchema( Parse pParse, Table pTab, string zName ) { Vdbe v; string zWhere; int iDb; /* Index of database containing pTab */ #if !SQLITE_OMIT_TRIGGER Trigger pTrig; #endif v = sqlite3GetVdbe( pParse ); if ( NEVER( v == null ) ) return; Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); Debug.Assert( iDb >= 0 ); #if !SQLITE_OMIT_TRIGGER /* Drop any table triggers from the internal schema. */ for ( pTrig = sqlite3TriggerList( pParse, pTab ); pTrig != null; pTrig = pTrig.pNext ) { int iTrigDb = sqlite3SchemaToIndex( pParse.db, pTrig.pSchema ); Debug.Assert( iTrigDb == iDb || iTrigDb == 1 ); sqlite3VdbeAddOp4( v, OP_DropTrigger, iTrigDb, 0, 0, pTrig.zName, 0 ); } #endif /* Drop the table and index from the internal schema. */ sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 ); /* Reload the table, index and permanent trigger schemas. */ zWhere = sqlite3MPrintf( pParse.db, "tbl_name=%Q", zName ); if ( zWhere == null ) return; sqlite3VdbeAddParseSchemaOp( v, iDb, zWhere ); #if !SQLITE_OMIT_TRIGGER /* Now, if the table is not stored in the temp database, reload any temp ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. */ if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" ) { sqlite3VdbeAddParseSchemaOp( v, 1, zWhere ); } #endif } /* ** Parameter zName is the name of a table that is about to be altered ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). ** If the table is a system table, this function leaves an error message ** in pParse->zErr (system tables may not be altered) and returns non-zero. ** ** Or, if zName is not a system table, zero is returned. */ static int isSystemTable( Parse pParse, string zName ) { if (zName.StartsWith("sqlite_", System.StringComparison.OrdinalIgnoreCase)) { sqlite3ErrorMsg( pParse, "table %s may not be altered", zName ); return 1; } return 0; } /* ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" ** command. */ static void sqlite3AlterRenameTable( Parse pParse, /* Parser context. */ SrcList pSrc, /* The table to rename. */ Token pName /* The new table name. */ ) { int iDb; /* Database that contains the table */ string zDb; /* Name of database iDb */ Table pTab; /* Table being renamed */ string zName = null; /* NULL-terminated version of pName */ sqlite3 db = pParse.db; /* Database connection */ int nTabName; /* Number of UTF-8 characters in zTabName */ string zTabName; /* Original name of the table */ Vdbe v; #if !SQLITE_OMIT_TRIGGER string zWhere = ""; /* Where clause to locate temp triggers */ #endif VTable pVTab = null; /* Non-zero if this is a v-tab with an xRename() */ int savedDbFlags; /* Saved value of db->flags */ savedDbFlags = db.flags; //if ( NEVER( db.mallocFailed != 0 ) ) goto exit_rename_table; Debug.Assert( pSrc.nSrc == 1 ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase ); if ( pTab == null ) goto exit_rename_table; iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); zDb = db.aDb[iDb].zName; db.flags |= SQLITE_PreferBuiltin; /* Get a NULL terminated version of the new table name. */ zName = sqlite3NameFromToken( db, pName ); if ( zName == null ) goto exit_rename_table; /* Check that a table or index named 'zName' does not already exist ** in database iDb. If so, this is an error. */ if ( sqlite3FindTable( db, zName, zDb ) != null || sqlite3FindIndex( db, zName, zDb ) != null ) { sqlite3ErrorMsg( pParse, "there is already another table or index with this name: %s", zName ); goto exit_rename_table; } /* Make sure it is not a system table being altered, or a reserved name ** that the table is being renamed to. */ if ( SQLITE_OK!=isSystemTable(pParse, pTab.zName) ) { goto exit_rename_table; } if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) ) { goto exit_rename_table; } #if !SQLITE_OMIT_VIEW if ( pTab.pSelect != null ) { sqlite3ErrorMsg( pParse, "view %s may not be altered", pTab.zName ); goto exit_rename_table; } #endif #if !SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0) ){ goto exit_rename_table; } #endif if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 ) { goto exit_rename_table; } #if !SQLITE_OMIT_VIRTUALTABLE if ( IsVirtual( pTab ) ) { pVTab = sqlite3GetVTable( db, pTab ); if ( pVTab.pVtab.pModule.xRename == null ) { pVTab = null; } } #endif /* Begin a transaction and code the VerifyCookie for database iDb. ** Then modify the schema cookie (since the ALTER TABLE modifies the ** schema). Open a statement transaction if the table is a virtual ** table. */ v = sqlite3GetVdbe( pParse ); if ( v == null ) { goto exit_rename_table; } sqlite3BeginWriteOperation( pParse, pVTab != null ? 1 : 0, iDb ); sqlite3ChangeCookie( pParse, iDb ); /* If this is a virtual table, invoke the xRename() function if ** one is defined. The xRename() callback will modify the names ** of any resources used by the v-table implementation (including other ** SQLite tables) that are identified by the name of the virtual table. */ #if !SQLITE_OMIT_VIRTUALTABLE if ( pVTab !=null) { int i = ++pParse.nMem; sqlite3VdbeAddOp4( v, OP_String8, 0, i, 0, zName, 0 ); sqlite3VdbeAddOp4( v, OP_VRename, i, 0, 0, pVTab, P4_VTAB ); sqlite3MayAbort(pParse); } #endif /* figure out how many UTF-8 characters are in zName */ zTabName = pTab.zName; nTabName = sqlite3Utf8CharLen( zTabName, -1 ); #if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER) if ( ( db.flags & SQLITE_ForeignKeys ) != 0 ) { /* If foreign-key support is enabled, rewrite the CREATE TABLE ** statements corresponding to all child tables of foreign key constraints ** for which the renamed table is the parent table. */ if ( ( zWhere = whereForeignKeys( pParse, pTab ) ) != null ) { sqlite3NestedParse( pParse, "UPDATE \"%w\".%s SET " + "sql = sqlite_rename_parent(sql, %Q, %Q) " + "WHERE %s;", zDb, SCHEMA_TABLE( iDb ), zTabName, zName, zWhere ); sqlite3DbFree( db, ref zWhere ); } } #endif /* Modify the sqlite_master table to use the new table name. */ sqlite3NestedParse( pParse, "UPDATE %Q.%s SET " + #if SQLITE_OMIT_TRIGGER "sql = sqlite_rename_table(sql, %Q), " + #else "sql = CASE " + "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" + "ELSE sqlite_rename_table(sql, %Q) END, " + #endif "tbl_name = %Q, " + "name = CASE " + "WHEN type='table' THEN %Q " + "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " + "'sqlite_autoindex_' || %Q || substr(name,%d+18) " + "ELSE name END " + "WHERE tbl_name=%Q AND " + "(type='table' OR type='index' OR type='trigger');", zDb, SCHEMA_TABLE( iDb ), zName, zName, zName, #if !SQLITE_OMIT_TRIGGER zName, #endif zName, nTabName, zTabName ); #if !SQLITE_OMIT_AUTOINCREMENT /* If the sqlite_sequence table exists in this database, then update ** it with the new table name. */ if ( sqlite3FindTable( db, "sqlite_sequence", zDb ) != null ) { sqlite3NestedParse( pParse, "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", zDb, zName, pTab.zName ); } #endif #if !SQLITE_OMIT_TRIGGER /* If there are TEMP triggers on this table, modify the sqlite_temp_master ** table. Don't do this if the table being ALTERed is itself located in ** the temp database. */ if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" ) { sqlite3NestedParse( pParse, "UPDATE sqlite_temp_master SET " + "sql = sqlite_rename_trigger(sql, %Q), " + "tbl_name = %Q " + "WHERE %s;", zName, zName, zWhere ); sqlite3DbFree( db, ref zWhere ); } #endif #if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER) if ( ( db.flags & SQLITE_ForeignKeys ) != 0 ) { FKey p; for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo ) { Table pFrom = p.pFrom; if ( pFrom != pTab ) { reloadTableSchema( pParse, p.pFrom, pFrom.zName ); } } } #endif /* Drop and reload the internal table schema. */ reloadTableSchema( pParse, pTab, zName ); exit_rename_table: sqlite3SrcListDelete( db, ref pSrc ); sqlite3DbFree( db, ref zName ); db.flags = savedDbFlags; } /* ** Generate code to make sure the file format number is at least minFormat. ** The generated code will increase the file format number if necessary. */ static void sqlite3MinimumFileFormat( Parse pParse, int iDb, int minFormat ) { Vdbe v; v = sqlite3GetVdbe( pParse ); /* The VDBE should have been allocated before this routine is called. ** If that allocation failed, we would have quit before reaching this ** point */ if ( ALWAYS( v ) ) { int r1 = sqlite3GetTempReg( pParse ); int r2 = sqlite3GetTempReg( pParse ); int j1; sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT ); sqlite3VdbeUsesBtree( v, iDb ); sqlite3VdbeAddOp2( v, OP_Integer, minFormat, r2 ); j1 = sqlite3VdbeAddOp3( v, OP_Ge, r2, 0, r1 ); sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2 ); sqlite3VdbeJumpHere( v, j1 ); sqlite3ReleaseTempReg( pParse, r1 ); sqlite3ReleaseTempReg( pParse, r2 ); } } /* ** This function is called after an "ALTER TABLE ... ADD" statement ** has been parsed. Argument pColDef contains the text of the new ** column definition. ** ** The Table structure pParse.pNewTable was extended to include ** the new column during parsing. */ static void sqlite3AlterFinishAddColumn( Parse pParse, Token pColDef ) { Table pNew; /* Copy of pParse.pNewTable */ Table pTab; /* Table being altered */ int iDb; /* Database number */ string zDb; /* Database name */ string zTab; /* Table name */ string zCol; /* Null-terminated column definition */ Column pCol; /* The new column */ Expr pDflt; /* Default value for the new column */ sqlite3 db; /* The database connection; */ db = pParse.db; if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) return; pNew = pParse.pNewTable; Debug.Assert( pNew != null ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); iDb = sqlite3SchemaToIndex( db, pNew.pSchema ); zDb = db.aDb[iDb].zName; zTab = pNew.zName.Substring( 16 );// zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ pCol = pNew.aCol[pNew.nCol - 1]; pDflt = pCol.pDflt; pTab = sqlite3FindTable( db, zTab, zDb ); Debug.Assert( pTab != null ); #if !SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0) ){ return; } #endif /* If the default value for the new column was specified with a ** literal NULL, then set pDflt to 0. This simplifies checking ** for an SQL NULL default below. */ if ( pDflt != null && pDflt.op == TK_NULL ) { pDflt = null; } /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. ** If there is a NOT NULL constraint, then the default value for the ** column must not be NULL. */ if ( pCol.isPrimKey != 0 ) { sqlite3ErrorMsg( pParse, "Cannot add a PRIMARY KEY column" ); return; } if ( pNew.pIndex != null ) { sqlite3ErrorMsg( pParse, "Cannot add a UNIQUE column" ); return; } if ( ( db.flags & SQLITE_ForeignKeys ) != 0 && pNew.pFKey != null && pDflt != null ) { sqlite3ErrorMsg( pParse, "Cannot add a REFERENCES column with non-NULL default value" ); return; } if ( pCol.notNull != 0 && pDflt == null ) { sqlite3ErrorMsg( pParse, "Cannot add a NOT NULL column with default value NULL" ); return; } /* Ensure the default expression is something that sqlite3ValueFromExpr() ** can handle (i.e. not CURRENT_TIME etc.) */ if ( pDflt != null ) { sqlite3_value pVal = null; if ( sqlite3ValueFromExpr( db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, ref pVal ) != 0 ) { // db.mallocFailed = 1; return; } if ( pVal == null ) { sqlite3ErrorMsg( pParse, "Cannot add a column with non-constant default" ); return; } sqlite3ValueFree( ref pVal ); } /* Modify the CREATE TABLE statement. */ zCol = pColDef.z.Substring( 0, pColDef.n ).Replace( ";", " " ).Trim();//sqlite3DbStrNDup(db, (char*)pColDef.z, pColDef.n); if ( zCol != null ) { // char zEnd = zCol[pColDef.n-1]; int savedDbFlags = db.flags; // while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ // zEnd-- = '\0'; // } db.flags |= SQLITE_PreferBuiltin; sqlite3NestedParse( pParse, "UPDATE \"%w\".%s SET " + "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " + "WHERE type = 'table' AND name = %Q", zDb, SCHEMA_TABLE( iDb ), pNew.addColOffset, zCol, pNew.addColOffset + 1, zTab ); sqlite3DbFree( db, ref zCol ); db.flags = savedDbFlags; } /* If the default value of the new column is NULL, then set the file ** format to 2. If the default value of the new column is not NULL, ** the file format becomes 3. */ sqlite3MinimumFileFormat( pParse, iDb, pDflt != null ? 3 : 2 ); /* Reload the schema of the modified table. */ reloadTableSchema( pParse, pTab, pTab.zName ); } /* ** This function is called by the parser after the table-name in ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument ** pSrc is the full-name of the table being altered. ** ** This routine makes a (partial) copy of the Table structure ** for the table being altered and sets Parse.pNewTable to point ** to it. Routines called by the parser as the column definition ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to ** the copy. The copy of the Table structure is deleted by tokenize.c ** after parsing is finished. ** ** Routine sqlite3AlterFinishAddColumn() will be called to complete ** coding the "ALTER TABLE ... ADD" statement. */ static void sqlite3AlterBeginAddColumn( Parse pParse, SrcList pSrc ) { Table pNew; Table pTab; Vdbe v; int iDb; int i; int nAlloc; sqlite3 db = pParse.db; /* Look up the table being altered. */ Debug.Assert( pParse.pNewTable == null ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); // if ( db.mallocFailed != 0 ) goto exit_begin_add_column; pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase ); if ( pTab == null ) goto exit_begin_add_column; if ( IsVirtual( pTab ) ) { sqlite3ErrorMsg( pParse, "virtual tables may not be altered" ); goto exit_begin_add_column; } /* Make sure this is not an attempt to ALTER a view. */ if ( pTab.pSelect != null ) { sqlite3ErrorMsg( pParse, "Cannot add a column to a view" ); goto exit_begin_add_column; } if ( SQLITE_OK != isSystemTable( pParse, pTab.zName ) ) { goto exit_begin_add_column; } Debug.Assert( pTab.addColOffset > 0 ); iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); /* Put a copy of the Table struct in Parse.pNewTable for the ** sqlite3AddColumn() function and friends to modify. But modify ** the name by adding an "sqlite_altertab_" prefix. By adding this ** prefix, we insure that the name will not collide with an existing ** table because user table are not allowed to have the "sqlite_" ** prefix on their name. */ pNew = new Table();// (Table*)sqlite3DbMallocZero( db, sizeof(Table)) if ( pNew == null ) goto exit_begin_add_column; pParse.pNewTable = pNew; pNew.nRef = 1; pNew.nCol = pTab.nCol; Debug.Assert( pNew.nCol > 0 ); nAlloc = ( ( ( pNew.nCol - 1 ) / 8 ) * 8 ) + 8; Debug.Assert( nAlloc >= pNew.nCol && nAlloc % 8 == 0 && nAlloc - pNew.nCol < 8 ); pNew.aCol = new Column[nAlloc];// (Column*)sqlite3DbMallocZero( db, sizeof(Column) * nAlloc ); pNew.zName = sqlite3MPrintf( db, "sqlite_altertab_%s", pTab.zName ); if ( pNew.aCol == null || pNew.zName == null ) { // db.mallocFailed = 1; goto exit_begin_add_column; } // memcpy( pNew.aCol, pTab.aCol, sizeof(Column) * pNew.nCol ); for ( i = 0; i < pNew.nCol; i++ ) { Column pCol = pTab.aCol[i].Copy(); // sqlite3DbStrDup( db, pCol.zName ); pCol.zColl = null; pCol.zType = null; pCol.pDflt = null; pCol.zDflt = null; pNew.aCol[i] = pCol; } pNew.pSchema = db.aDb[iDb].pSchema; pNew.addColOffset = pTab.addColOffset; pNew.nRef = 1; /* Begin a transaction and increment the schema cookie. */ sqlite3BeginWriteOperation( pParse, 0, iDb ); v = sqlite3GetVdbe( pParse ); if ( v == null ) goto exit_begin_add_column; sqlite3ChangeCookie( pParse, iDb ); exit_begin_add_column: sqlite3SrcListDelete( db, ref pSrc ); return; } #endif // * SQLITE_ALTER_TABLE */ } }
// $begin{copyright} // // This file is part of WebSharper // // Copyright (c) 2008-2018 IntelliFactory // // 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. // // $end{copyright} using Microsoft.FSharp.Control; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebSharper.Testing; using static WebSharper.JavaScript.Pervasives; namespace WebSharper.CSharp.Tests { delegate int FuncWithOptional(int a = 5); [JavaScript, Test("Delegate tests")] class DelegateTests : TestCategory { [Test] public void Delegates() { Expect(8); A0(() => IsTrue(true, "Action lambda invocation")); A1(x => Equal(x, 122, "Action<T> lambda invocation")); Equal(F1(() => 41), 41, "Func<T> lambda invocation"); Equal(F2(x => x + 41), 42, "Func<T,U> lambda invocation"); A0(a0); A1(a1); Equal(F1(f1), 32, "Func<T> method invocation"); Equal(F2(f2), 5, "Func<T,U> method invocation"); } [Test] public async void AsyncLambda() { var x = 0; Equal(x, 0); var t = new Task(() => { x = 1; }); A0(async () => { await t; }); await FSharpAsync.StartAsTask(FSharpAsync.Sleep(200), null, null); // await Task.Delay(200); Equal(x, 1); } private int F1(Func<int> f) { return f(); } private int F2(Func<int, int> f) { return f(1); } private void A0(Action f) { f(); } private void A1(Action<int> f) { f(122); } private int f1() => 32; private int f1m() => 42; private int f2(int x) => x + 4; private void a0() => IsTrue(true, "Action method invocation"); private void a1(int x) => Equal(x, 122, "Action<T> method invocation"); [Test] public void StaticDelegate() { var d = new Action(DoNothing); d(); Equal(ForTesting, 2); } //public static int ForTesting = 0; public static int ForTesting { get; set; } = 1; public static void DoNothing() { ForTesting++; } [Test] public void Target() { var d = new Func<int>(f1); Equal(d.Target, this); } [Test] public void Equality() { var d1 = new Func<int>(f1); var d2 = new Func<int>(f1); var d3 = new Func<int>(f1m); IsTrue((object)d1 == (object)d2); IsTrue(d1 == d2); IsTrue(d1.Equals(d2)); IsTrue(d1.Equals((object)d2)); IsTrue(d1 != null); IsFalse(d1 == d3); IsFalse((object)d1 == (object)d3); IsTrue(d1 != d3); } [Test] public void DelegateCombine() { var act = new System.Action(() => { }); var res = new[] { 0 }; var a1 = new System.Action<int>(x => res[0] += x); var a2 = new System.Action<int>(x => res[0] += 1); var comb = a1 + a2; comb.Invoke(2); Equal(res[0], 3); Equal(comb.GetInvocationList().Length, 2); } [Test("Delegate with default value, known issue: https://github.com/intellifactory/websharper/issues/788", TestKind.Skip)] public void DelegateWithOptional() { var f = new FuncWithOptional(x => x); Equal(f(3), 3); Equal(f(), 5); } public event Action MyEvent; public int EventTester = 0; public void IncrEventTester() { EventTester++; } public void IncrEventTesterByTwo() { EventTester += 2; } public event Action MyExplicitEvent { add { EventTester++; MyEvent += value; } remove { EventTester--; MyEvent -= value; } } [Test] public void Event() { MyEvent += IncrEventTester; this.MyEvent(); Equal(EventTester, 1, "added IncrEventTester, triggered"); MyEvent += IncrEventTesterByTwo; MyEvent(); Equal(EventTester, 4, "added IncrEventTesterByTwo, triggered"); MyEvent -= IncrEventTester; MyEvent(); Equal(EventTester, 6, "removed IncrEventTester, triggered"); MyEvent += IncrEventTesterByTwo; MyEvent(); Equal(EventTester, 10, "added another IncrEventTesterByTwo, triggered"); MyEvent -= IncrEventTesterByTwo; MyEvent(); Equal(EventTester, 12, "removed one IncrEventTesterByTwo, triggered"); MyEvent = null; MyExplicitEvent += IncrEventTester; Equal(EventTester, 13, "explicit add handler"); MyEvent(); Equal(EventTester, 14, "triggered"); MyExplicitEvent -= IncrEventTester; Equal(EventTester, 13, "explicit remove handler"); Equal(MyEvent, null, "empty event is null"); } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using Common; /// <summary> /// Sends messages over a TCP network connection. /// </summary> internal class TcpNetworkSender : NetworkSender { private readonly Queue<SocketAsyncEventArgs> _pendingRequests = new Queue<SocketAsyncEventArgs>(); private ISocket _socket; private Exception _pendingError; private bool _asyncOperationInProgress; private AsyncContinuation _closeContinuation; private AsyncContinuation _flushContinuation; /// <summary> /// Initializes a new instance of the <see cref="TcpNetworkSender"/> class. /// </summary> /// <param name="url">URL. Must start with tcp://.</param> /// <param name="addressFamily">The address family.</param> public TcpNetworkSender(string url, AddressFamily addressFamily) : base(url) { AddressFamily = addressFamily; } internal AddressFamily AddressFamily { get; set; } internal int MaxQueueSize { get; set; } /// <summary> /// Creates the socket with given parameters. /// </summary> /// <param name="addressFamily">The address family.</param> /// <param name="socketType">Type of the socket.</param> /// <param name="protocolType">Type of the protocol.</param> /// <returns>Instance of <see cref="ISocket" /> which represents the socket.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method")] protected internal virtual ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { return new SocketProxy(addressFamily, socketType, protocolType); } /// <summary> /// Performs sender-specific initialization. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed in the event handler.")] protected override void DoInitialize() { var args = new MySocketAsyncEventArgs(); args.RemoteEndPoint = ParseEndpointAddress(new Uri(Address), AddressFamily); args.Completed += SocketOperationCompleted; args.UserToken = null; _socket = CreateSocket(args.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _asyncOperationInProgress = true; if (!_socket.ConnectAsync(args)) { SocketOperationCompleted(_socket, args); } } /// <summary> /// Closes the socket. /// </summary> /// <param name="continuation">The continuation.</param> protected override void DoClose(AsyncContinuation continuation) { lock (this) { if (_asyncOperationInProgress) { _closeContinuation = continuation; } else { CloseSocket(continuation); } } } /// <summary> /// Performs sender-specific flush. /// </summary> /// <param name="continuation">The continuation.</param> protected override void DoFlush(AsyncContinuation continuation) { lock (this) { if (!_asyncOperationInProgress && _pendingRequests.Count == 0) { continuation(null); } else { _flushContinuation = continuation; } } } /// <summary> /// Sends the specified text over the connected socket. /// </summary> /// <param name="bytes">The bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param> /// <remarks>To be overridden in inheriting classes.</remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Object is disposed in the event handler.")] protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { var args = new MySocketAsyncEventArgs(); args.SetBuffer(bytes, offset, length); args.UserToken = asyncContinuation; args.Completed += SocketOperationCompleted; lock (this) { if (MaxQueueSize != 0 && _pendingRequests.Count >= MaxQueueSize) { var dequeued = _pendingRequests.Dequeue(); if (dequeued != null) { dequeued.Dispose(); } } _pendingRequests.Enqueue(args); } ProcessNextQueuedItem(); } private void CloseSocket(AsyncContinuation continuation) { try { var sock = _socket; _socket = null; if (sock != null) { sock.Close(); } continuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } continuation(exception); } } private void SocketOperationCompleted(object sender, SocketAsyncEventArgs e) { lock (this) { _asyncOperationInProgress = false; var asyncContinuation = e.UserToken as AsyncContinuation; if (e.SocketError != SocketError.Success) { _pendingError = new IOException("Error: " + e.SocketError); } e.Dispose(); if (asyncContinuation != null) { asyncContinuation(_pendingError); } } ProcessNextQueuedItem(); } private void ProcessNextQueuedItem() { SocketAsyncEventArgs args; lock (this) { if (_asyncOperationInProgress) { return; } if (_pendingError != null) { while (_pendingRequests.Count != 0) { args = _pendingRequests.Dequeue(); var asyncContinuation = (AsyncContinuation)args.UserToken; args.Dispose(); asyncContinuation(_pendingError); } } if (_pendingRequests.Count == 0) { var fc = _flushContinuation; if (fc != null) { _flushContinuation = null; fc(_pendingError); } var cc = _closeContinuation; if (cc != null) { _closeContinuation = null; CloseSocket(cc); } return; } args = _pendingRequests.Dequeue(); _asyncOperationInProgress = true; if (!_socket.SendAsync(args)) { SocketOperationCompleted(_socket, args); } } } public override void CheckSocket() { if (_socket == null) { DoInitialize(); } } /// <summary> /// Facilitates mocking of <see cref="SocketAsyncEventArgs"/> class. /// </summary> internal class MySocketAsyncEventArgs : SocketAsyncEventArgs { /// <summary> /// Raises the Completed event. /// </summary> public void RaiseCompleted() { OnCompleted(this); } } } }
namespace Signum.Utilities.Reflection; public static class TupleReflection { public static bool IsTuple(Type type) { return type.IsGenericType && IsTupleDefinition(type.GetGenericTypeDefinition()); } private static bool IsTupleDefinition(Type genericTypeDefinition) { var numParameters = genericTypeDefinition.GetGenericArguments().Length; return numParameters <= 8 && genericTypeDefinition == TupleOf(numParameters); } public static Type TupleOf(int numParameters) { switch (numParameters) { case 1: return typeof(Tuple<>); case 2: return typeof(Tuple<,>); case 3: return typeof(Tuple<,,>); case 4: return typeof(Tuple<,,,>); case 5: return typeof(Tuple<,,,,>); case 6: return typeof(Tuple<,,,,,>); case 7: return typeof(Tuple<,,,,,,>); case 8: return typeof(Tuple<,,,,,,,>); default: throw new UnexpectedValueException(numParameters); } } public static int TupleIndex(PropertyInfo pi) { switch (pi.Name) { case "Item1": return 0; case "Item2": return 1; case "Item3": return 2; case "Item4": return 3; case "Item5": return 4; case "Item6": return 5; case "Item7": return 6; case "Rest": return 7; } throw new ArgumentException("pi should be the property of a Tuple type"); } public static PropertyInfo TupleProperty(Type type, int index) { switch (index) { case 0: return type.GetProperty("Item1")!; case 1: return type.GetProperty("Item2")!; case 2: return type.GetProperty("Item3")!; case 3: return type.GetProperty("Item4")!; case 4: return type.GetProperty("Item5")!; case 5: return type.GetProperty("Item6")!; case 6: return type.GetProperty("Item7")!; case 7: return type.GetProperty("Rest")!; } throw new ArgumentException("Property with index {0} not found on {1}".FormatWith(index, type.GetType())); } public static Type TupleChainType(IEnumerable<Type> tupleElementTypes) { int count = tupleElementTypes.Count(); if (count == 0) throw new InvalidOperationException("typleElementTypes is empty"); if (count >= 8) return TupleOf(8).MakeGenericType(tupleElementTypes.Take(7).And(TupleChainType(tupleElementTypes.Skip(7))).ToArray()); return TupleOf(tupleElementTypes.Count()).MakeGenericType(tupleElementTypes.ToArray()); } public static Expression TupleChainConstructor(IEnumerable<Expression> fieldExpressions) { int count = fieldExpressions.Count(); if (count == 0) return Expression.Constant(new object(), typeof(object)); Type type = TupleChainType(fieldExpressions.Select(e => e.Type)); ConstructorInfo ci = type.GetConstructors().SingleEx(); if (count >= 8) return Expression.New(ci, fieldExpressions.Take(7).And(TupleChainConstructor(fieldExpressions.Skip(7)))); return Expression.New(ci, fieldExpressions); } public static Expression TupleChainProperty(Expression expression, int index) { if (index >= 7) return TupleChainProperty(Expression.Property(expression, TupleProperty(expression.Type, 7)), index - 7); return Expression.Property(expression, TupleProperty(expression.Type, index)); } } public static class ValueTupleReflection { public static bool IsValueTuple(Type type) { return type.IsGenericType && IsValueTupleDefinition(type.GetGenericTypeDefinition()); } private static bool IsValueTupleDefinition(Type genericTypeDefinition) { var numParameters = genericTypeDefinition.GetGenericArguments().Length; return numParameters <= 8 && genericTypeDefinition == ValueTupleOf(numParameters); } public static Type ValueTupleOf(int numParameters) { switch (numParameters) { case 1: return typeof(ValueTuple<>); case 2: return typeof(ValueTuple<,>); case 3: return typeof(ValueTuple<,,>); case 4: return typeof(ValueTuple<,,,>); case 5: return typeof(ValueTuple<,,,,>); case 6: return typeof(ValueTuple<,,,,,>); case 7: return typeof(ValueTuple<,,,,,,>); case 8: return typeof(ValueTuple<,,,,,,,>); default: throw new UnexpectedValueException(numParameters); } } public static int TupleIndex(FieldInfo pi) { switch (pi.Name) { case "Item1": return 0; case "Item2": return 1; case "Item3": return 2; case "Item4": return 3; case "Item5": return 4; case "Item6": return 5; case "Item7": return 6; case "Rest": return 7; } throw new ArgumentException("pi should be the property of a Tuple type"); } public static FieldInfo TupleField(Type type, int index) { switch (index) { case 0: return type.GetField("Item1")!; case 1: return type.GetField("Item2")!; case 2: return type.GetField("Item3")!; case 3: return type.GetField("Item4")!; case 4: return type.GetField("Item5")!; case 5: return type.GetField("Item6")!; case 6: return type.GetField("Item7")!; case 7: return type.GetField("Rest")!; } throw new ArgumentException("Property with index {0} not found on {1}".FormatWith(index, type.GetType())); } public static Type TupleChainType(IEnumerable<Type> tupleElementTypes) { int count = tupleElementTypes.Count(); if (count == 0) throw new InvalidOperationException("typleElementTypes is empty"); if (count >= 8) return ValueTupleOf(8).MakeGenericType(tupleElementTypes.Take(7).And(TupleChainType(tupleElementTypes.Skip(7))).ToArray()); return ValueTupleOf(tupleElementTypes.Count()).MakeGenericType(tupleElementTypes.ToArray()); } public static Expression TupleChainConstructor(IEnumerable<Expression> fieldExpressions) { int count = fieldExpressions.Count(); if (count == 0) return Expression.Constant(new object(), typeof(object)); Type type = TupleChainType(fieldExpressions.Select(e => e.Type)); ConstructorInfo ci = type.GetConstructors().SingleEx(); if (count >= 8) return Expression.New(ci, fieldExpressions.Take(7).And(TupleChainConstructor(fieldExpressions.Skip(7)))); return Expression.New(ci, fieldExpressions); } public static Expression TupleChainProperty(Expression expression, int index) { if (index >= 7) return TupleChainProperty(Expression.Field(expression, TupleField(expression.Type, 7)), index - 7); return Expression.Field(expression, TupleField(expression.Type, index)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; namespace System.Dynamic.Utils { internal static class ExpressionUtils { public static ReadOnlyCollection<T> ReturnReadOnly<T>(ref IList<T> collection) { IList<T> value = collection; // if it's already read-only just return it. ReadOnlyCollection<T> res = value as ReadOnlyCollection<T>; if (res != null) { return res; } // otherwise make sure only readonly collection every gets exposed Interlocked.CompareExchange<IList<T>>( ref collection, value.ToReadOnly(), value ); // and return it return (ReadOnlyCollection<T>)collection; } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is similar to the ReturnReadOnly of T. This version supports nodes which hold /// onto multiple Expressions where one is typed to object. That object field holds either /// an expression or a ReadOnlyCollection of Expressions. When it holds a ReadOnlyCollection /// the IList which backs it is a ListArgumentProvider which uses the Expression which /// implements IArgumentProvider to get 2nd and additional values. The ListArgumentProvider /// continues to hold onto the 1st expression. /// /// This enables users to get the ReadOnlyCollection w/o it consuming more memory than if /// it was just an array. Meanwhile The DLR internally avoids accessing which would force /// the readonly collection to be created resulting in a typical memory savings. /// </summary> public static ReadOnlyCollection<Expression> ReturnReadOnly(IArgumentProvider provider, ref object collection) { Expression tObj = collection as Expression; if (tObj != null) { // otherwise make sure only one readonly collection ever gets exposed Interlocked.CompareExchange( ref collection, new ReadOnlyCollection<Expression>(new ListArgumentProvider(provider, tObj)), tObj ); } // and return what is not guaranteed to be a readonly collection return (ReadOnlyCollection<Expression>)collection; } /// <summary> /// Helper which is used for specialized subtypes which use ReturnReadOnly(ref object, ...). /// This is the reverse version of ReturnReadOnly which takes an IArgumentProvider. /// /// This is used to return the 1st argument. The 1st argument is typed as object and either /// contains a ReadOnlyCollection or the Expression. We check for the Expression and if it's /// present we return that, otherwise we return the 1st element of the ReadOnlyCollection. /// </summary> public static T ReturnObject<T>(object collectionOrT) where T : class { T t = collectionOrT as T; if (t != null) { return t; } return ((ReadOnlyCollection<T>)collectionOrT)[0]; } public static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ref ReadOnlyCollection<Expression> arguments) { Debug.Assert(nodeKind == ExpressionType.Invoke || nodeKind == ExpressionType.Call || nodeKind == ExpressionType.Dynamic || nodeKind == ExpressionType.New); ParameterInfo[] pis = GetParametersForValidation(method, nodeKind); ValidateArgumentCount(method, nodeKind, arguments.Count, pis); Expression[] newArgs = null; for (int i = 0, n = pis.Length; i < n; i++) { Expression arg = arguments[i]; ParameterInfo pi = pis[i]; arg = ValidateOneArgument(method, nodeKind, arg, pi); if (newArgs == null && arg != arguments[i]) { newArgs = new Expression[arguments.Count]; for (int j = 0; j < i; j++) { newArgs[j] = arguments[j]; } } if (newArgs != null) { newArgs[i] = arg; } } if (newArgs != null) { arguments = new TrueReadOnlyCollection<Expression>(newArgs); } } public static void ValidateArgumentCount(MethodBase method, ExpressionType nodeKind, int count, ParameterInfo[] pis) { if (pis.Length != count) { // Throw the right error for the node we were given switch (nodeKind) { case ExpressionType.New: throw Error.IncorrectNumberOfConstructorArguments(); case ExpressionType.Invoke: throw Error.IncorrectNumberOfLambdaArguments(); case ExpressionType.Dynamic: case ExpressionType.Call: throw Error.IncorrectNumberOfMethodCallArguments(method); default: throw ContractUtils.Unreachable; } } } public static Expression ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi) { RequiresCanRead(arg, "arguments"); Type pType = pi.ParameterType; if (pType.IsByRef) { pType = pType.GetElementType(); } TypeUtils.ValidateType(pType); if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) { if (!TryQuote(pType, ref arg)) { // Throw the right error for the node we were given switch (nodeKind) { case ExpressionType.New: throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType); case ExpressionType.Invoke: throw Error.ExpressionTypeDoesNotMatchParameter(arg.Type, pType); case ExpressionType.Dynamic: case ExpressionType.Call: throw Error.ExpressionTypeDoesNotMatchMethodParameter(arg.Type, pType, method); default: throw ContractUtils.Unreachable; } } } return arg; } public static void RequiresCanRead(Expression expression, string paramName) { if (expression == null) { throw new ArgumentNullException(paramName); } // validate that we can read the node switch (expression.NodeType) { case ExpressionType.Index: IndexExpression index = (IndexExpression)expression; if (index.Indexer != null && !index.Indexer.CanRead) { throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName); } break; case ExpressionType.MemberAccess: MemberExpression member = (MemberExpression)expression; PropertyInfo prop = member.Member as PropertyInfo; if (prop != null) { if (!prop.CanRead) { throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName); } } break; } } // Attempts to auto-quote the expression tree. Returns true if it succeeded, false otherwise. public static bool TryQuote(Type parameterType, ref Expression argument) { // We used to allow quoting of any expression, but the behavior of // quote (produce a new tree closed over parameter values), only // works consistently for lambdas Type quoteable = typeof(LambdaExpression); if (TypeUtils.IsSameOrSubclass(quoteable, parameterType) && parameterType.IsAssignableFrom(argument.GetType())) { argument = Expression.Quote(argument); return true; } return false; } internal static ParameterInfo[] GetParametersForValidation(MethodBase method, ExpressionType nodeKind) { ParameterInfo[] pis = method.GetParametersCached(); if (nodeKind == ExpressionType.Dynamic) { pis = pis.RemoveFirst(); // ignore CallSite argument } return pis; } } }
// ============================================================ // RRDSharp: Managed implementation of RRDTool for .NET/Mono // ============================================================ // // Project Info: http://sourceforge.net/projects/rrdsharp/ // Project Lead: Julio David Quintana (david@quintana.org) // // Distributed under terms of the LGPL: // // This library is free software; you can redistribute it and/or modify it under the terms // of the GNU Lesser General Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License along with this // library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, // Boston, MA 02111-1307, USA. using System; using System.Collections; using System.Text; namespace stRrd.Core { /// <summary> /// Class to represent definition of new RRD file. /// </summary> /// <remarks> /// Object of this class is used to create new RRD file from scratch - pass its reference as /// an RrdDb constructor argument (see documentation for RrdDb class). RrdDef object does not /// actually create new RRD file. It just holds all necessary information which will be used /// during the actual creation process /// /// RRD file definition (RrdDef object) consists of the following elements: /// <list type="bullet"> /// <item><description> path to RRD file that will be created</description></item> /// <item><description> starting timestamp</description></item> /// <item><description> step</description></item> /// <item><description> one or more datasource definitions</description></item> /// <item><description> one or more archive definitions </description></item> /// </list> /// RrdDef provides API to set all these elements. /// </remarks> public class RrdDef { /// <summary> /// Default RRD step to be used if not specified in constructor (300 seconds) /// </summary> public static readonly long DEFAULT_STEP = 300L; /// <summary> /// If not specified in constructor, starting timestamp will be set to the current timestamp /// plus DEFAULT_INITIAL_SHIFT seconds (-10) /// </summary> public static readonly long DEFAULT_INITIAL_SHIFT = -10L; private string path; private long startTime = Util.Time + DEFAULT_INITIAL_SHIFT; private long step = DEFAULT_STEP; private ArrayList dsDefs = new ArrayList(); private ArrayList arcDefs = new ArrayList(); /// <summary> /// /// </summary> /// <param name="path"></param> public RrdDef(string path) { if (path == null || path.Length == 0) { throw new RrdException("No filename specified"); } this.path = path; } /// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="step"></param> public RrdDef(string path, long step) : this (path) { if(step <= 0) { throw new RrdException("Invalid RRD step specified: " + step); } this.step = step; } /// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="startTime"></param> /// <param name="step"></param> public RrdDef(string path, long startTime, long step): this (path, step) { if(startTime < 0) { throw new RrdException("Invalid RRD start time specified: " + startTime); } this.startTime = startTime; } /// <summary> /// /// </summary> public string Path { get { return path; } set { this.path = value; } } /// <summary> /// /// </summary> public long StartTime { get { return startTime; } set { this.startTime = value; } } /// <summary> /// /// </summary> /// <param name="date"></param> public void SetStartTime(DateTime date) { this.startTime = Util.TicksToMillis(date.Ticks); } /// <summary> /// /// </summary> public long Step { get { return step; } set { this.step = value; } } /// <summary> /// /// </summary> /// <param name="dsDef"></param> public void AddDatasource(DsDef dsDef) { if(dsDefs.Contains(dsDef)) { throw new RrdException("Datasource already defined: " + dsDef.Dump()); } dsDefs.Add(dsDef); } /// <summary> /// /// </summary> /// <param name="dsName"></param> /// <param name="dsType"></param> /// <param name="heartbeat"></param> /// <param name="minValue"></param> /// <param name="maxValue"></param> public void AddDatasource(string dsName, string dsType, long heartbeat, double minValue, double maxValue) { AddDatasource(new DsDef(dsName, dsType, heartbeat, minValue, maxValue)); } /// <summary> /// /// </summary> /// <param name="dsDefs"></param> public void AddDatasource(DsDef[] dsDefs) { for(int i = 0; i < dsDefs.Length; i++) { AddDatasource(dsDefs[i]); } } /// <summary> /// /// </summary> /// <param name="arcDef"></param> public void AddArchive(ArcDef arcDef) { if(arcDefs.Contains(arcDef)) { throw new RrdException("Archive already defined: " + arcDef.Dump()); } arcDefs.Add(arcDef); } /// <summary> /// /// </summary> /// <param name="arcDefs"></param> public void AddArchive(ArcDef[] arcDefs) { for(int i = 0; i < arcDefs.Length; i++) { AddArchive(arcDefs[i]); } } /// <summary> /// /// </summary> /// <param name="consolFun"></param> /// <param name="xff"></param> /// <param name="steps"></param> /// <param name="rows"></param> public void AddArchive(string consolFun, double xff, int steps, int rows) { AddArchive(new ArcDef(consolFun, xff, steps, rows)); } internal void Validate() { if(dsDefs.Count == 0) { throw new RrdException("No RRD datasource specified. At least one is needed."); } if(arcDefs.Count == 0) { throw new RrdException("No RRD archive specified. At least one is needed."); } } /// <summary> /// /// </summary> public DsDef[] DsDefs { get { return (DsDef[]) dsDefs.ToArray(new DsDef("speed", "COUNTER", 600, Double.NaN, Double.NaN).GetType()); } } /// <summary> /// /// </summary> public ArcDef[] ArcDefs { get { return (ArcDef[]) arcDefs.ToArray(new ArcDef("AVERAGE", 0.5, 1, 24).GetType()); } } /// <summary> /// /// </summary> public int DsCount { get { return dsDefs.Count; } } /// <summary> /// /// </summary> public int ArcCount { get { return arcDefs.Count; } } /// <summary> /// /// </summary> /// <returns></returns> public string Dump() { StringBuilder buffer = new StringBuilder(RrdDb.RRDTOOL); buffer.Append(" create " + path); buffer.Append(" --start " + StartTime); buffer.Append(" --step " + Step + " "); for(int i = 0; i < dsDefs.Count; i++) { DsDef dsDef = (DsDef) dsDefs[i]; buffer.Append(dsDef.Dump() + " "); } for(int i = 0; i < arcDefs.Count; i++) { ArcDef arcDef = (ArcDef) arcDefs[i]; buffer.Append(arcDef.Dump() + " "); } return buffer.ToString().Trim(); } internal string RrdToolCommand { get { return Dump(); } } internal void RemoveDatasource(string dsName) { for(int i = 0; i < dsDefs.Count; i++) { DsDef dsDef = (DsDef) dsDefs[i]; if(dsDef.DsName.Equals(dsName)) { dsDefs.Remove(i); return; } } throw new RrdException("Could not find datasource named '" + dsName + "'"); } internal void RemoveArchive(string consolFun, int steps) { ArcDef arcDef = FindArchive(consolFun, steps); if(!arcDefs.Contains(arcDef)) { throw new RrdException("Could not remove archive " + consolFun + "/" + steps); } arcDefs.Remove(arcDef); } internal ArcDef FindArchive(string consolFun, int steps) { for(int i = 0; i < arcDefs.Count; i++) { ArcDef arcDef = (ArcDef) arcDefs[i]; if(arcDef.ConsolFun.Equals(consolFun) && arcDef.Steps == steps) { return arcDef; } } throw new RrdException("Could not find archive " + consolFun + "/" + steps); } } }
using Amazon; using Amazon.Glacier; using Amazon.Glacier.Model; using Amazon.Glacier.Transfer; using Amazon.Runtime; using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; namespace GlacierTool { public static class GlacierTool { public static void Main(string[] args) { Console.Write("GlacierTool\n(c) 2012 Justin Gottula\n\n"); if (args.Length < 1) Usage(); /* commands */ switch (args[0].ToLower()) { case "listvaults": case "inventory": case "download": Console.Error.Write("Command not implemented yet.\n"); Environment.Exit(1); break; case "upload": CheckArgs(args.Length, 8); Upload(args.Skip(1).ToArray()); break; case "hints": Hints(); break; default: Console.Error.Write(String.Format("Can't understand the " + "command '{0}'.\n", args[0])); Usage(); break; } } public static void Upload(string[] args) { string id = args[0]; string access = args[1]; string secret = args[2]; RegionEndpoint region = ParseRegion(args[3]); string vault = args[4]; string path = args[5]; string desc = args[6]; var info = new FileInfo(path); long size = 0; if (info.Exists) size = info.Length; else { Console.Error.Write("The given path does not exist.\n"); Usage(); } Console.Write("About to perform the following upload:\n\n" + String.Format("{0,-16}{1}\n", "Path:", path) + String.Format("{0,-16}{1:f6} GiB\n", "Size:", (decimal)size / (1024m * 1024m * 1024m)) + String.Format("{0,-16}\"{1}\"\n", "Description:", desc) + String.Format("\n{0,-16}{1}\n", "Region:", region.DisplayName) + String.Format("{0,-16}{1}\n", "Vault:", vault) + String.Format("\n{0,-16}${1:f2}/month\n", "Storage cost:", ((decimal)size / (1024m * 1024m * 1024m) * 0.01m)) + String.Format("{0,-16}${1:f2} (< 90 days)\n", "Deletion fee:", ((decimal)size / (1024m * 1024m * 1024m) * 0.03m)) + String.Format("{0,-16}${1:f2}\n", "Retrieval cost:", ((decimal)size / (1024m * 1024m * 1024m) * 0.12m)) + String.Format("\n{0,-16}{1}\n", "Account ID:", id) + String.Format("{0,-16}{1}\n", "Access key:", access) + String.Format("{0,-16}{1}\n", "Secret key:", secret) + "\nARE YOU SURE YOU WANT TO PROCEED? [y/N] "); bool proceed = false; do { ConsoleKeyInfo key = Console.ReadKey(true); switch (Char.ToLower(key.KeyChar)) { case 'y': Console.WriteLine(key.KeyChar); proceed = true; break; case 'n': Console.Write(key.KeyChar); goto case '\n'; case '\n': Console.WriteLine(); Console.Write("Upload aborted.\n"); Environment.Exit(0); break; } } while (!proceed); Console.Write("\nUpload started at {0:G}.\n", DateTime.Now); Console.CancelKeyPress += CtrlC; var progress = new Progress(); var options = new UploadOptions(); options.AccountId = id; options.StreamTransferProgress += progress.Update; var creds = new BasicAWSCredentials(access, secret); var manager = new ArchiveTransferManager(creds, region); progress.Start(); /* not asynchronous */ UploadResult result = manager.Upload(vault, desc, path, options); Console.Write("\n\nUpload complete.\n" + String.Format("Archive ID: {0}\n", result.ArchiveId)); } public static RegionEndpoint ParseRegion(string str) { RegionEndpoint region = null; foreach (var field in typeof(RegionEndpoint).GetFields()) { object obj = field.GetValue(null); if (obj is RegionEndpoint && field.Name == str) { region = (RegionEndpoint)obj; break; } } if (region == null) { Console.Error.Write("Can't parse the region given.\n"); Usage(); } return region; } public static void CheckArgs(int actual, int correct) { if (actual != correct) { if (actual < correct) Console.Error.Write("Too few arguments were given for " + "that command.\n"); else Console.Error.Write("Too many arguments were given for " + "that command.\n"); Usage(); } } public static void Usage() { Console.Error.Write("\nUsage: [mono] GlacierTool.exe " + "<command> <parameters>\n\n" + String.Format("{0,-12}{1}\n", "Command:", "Parameters & Description:") + String.Format("{0,-12}{1}\n", "listvaults", "account_id acc_key sec_key region") + String.Format("{0,-12} {1}\n", "", "list the vaults located in <region>") + String.Format("{0,-12}{1}\n", "inventory", "account_id acc_key sec_key region vault") + String.Format("{0,-12} {1}\n", "", "get the latest inventory for <vault>") + String.Format("{0,-12}{1}\n", "upload", "account_id acc_key sec_key region vault path " + "description") + String.Format("{0,-12} {1}\n", "", "upload the file located at <path> as an archive to " + "<vault>") + String.Format("{0,-12}{1}\n", "download", "account_id acc_key sec_key region vault arch_id path") + String.Format("{0,-12} {1}\n", "", "download the archive specified by <arch_id> from " + "<vault> to the") + String.Format("{0,-12} {1}\n", "", "file located at <path>") + String.Format("{0,-12}{1}\n", "hints", "") + String.Format("{0,-12} {1}\n", "", "display some helpful hints about potential problems")); Console.Error.Write("\nAvailable regions are listed below.\n" + String.Format("\n{0,-16}{1}\n", "Region:", "Description:")); foreach (var field in typeof(RegionEndpoint).GetFields()) { object obj = field.GetValue(null); if (obj is RegionEndpoint) { RegionEndpoint reg = (RegionEndpoint)obj; Console.Error.WriteLine(String.Format("{0,-16}{1}", field.Name, reg.DisplayName)); } } Environment.Exit(1); } public static void Hints() { /* hint: mono ssl problems need root certs installed * (use the mozilla thing) */ /* hint: where to find acc id, access key, secret key */ Console.Error.Write("No hints yet.\n"); Environment.Exit(1); } public static void CtrlC(object sender, ConsoleCancelEventArgs e) { Console.Write("\n\nOperation canceled.\n"); Environment.Exit(1); } } public class Progress { Stopwatch watch; public Progress() { watch = new Stopwatch(); Console.Write("\n{0}{1,11}{2,13}{3,11}{4,12}\n", "Percent", "Uploaded", "Total Size", "Elapsed", "Remaining"); } public void Start() { watch.Start(); } public void Update(object sender, StreamTransferProgressArgs e) { /* TODO: add bitrate indicator (use timer with interval of 1-10 * seconds, which compares bytes transferred before and after) * also, use this for the ETA calculation (with longer interval) */ float percent; if (e.TotalBytes != 0) percent = 100f * ((float)e.TransferredBytes / (float)e.TotalBytes); else percent = 0f; TimeSpan eta; if (e.TransferredBytes != 0) { long bytesLeft = e.TotalBytes - e.TransferredBytes; float rate = (float)watch.Elapsed.Ticks / (float)e.TransferredBytes; eta = new TimeSpan((long)((float)bytesLeft * rate)); } else eta = new TimeSpan(0); try { /* return to first column */ Console.CursorTop = Console.BufferHeight - 1; Console.CursorLeft = 0; } catch(ArgumentOutOfRangeException) { /* Terminal resize can cause an ArgumentOutOfRangeException * because of Mono bug 874 where the dimenisions of * the console aren't updated until after a write * https://bugzilla.xamarin.com/show_bug.cgi?id=874 */ Console.Write(""); return; } /* BUG: the hack used below will roll over if either time is over * 24 hours, which is likely for large archives * * in the future: use __d __:__:__ (right-aligned space-padded * two-digit days, only displayed if >24 hrs) */ /* Mono can't handle custom TimeSpan formatting, so we convert the * TimeSpans to DateTimes before printing them */ Console.Write(String.Format("{0,6:f1}%{1,7:d} MiB{2,9:d} MiB" + "{3,11:HH:mm:ss}{4,12:HH:mm:ss}", percent, (e.TransferredBytes / 1024 / 1024), (e.TotalBytes / 1024 / 1024), new DateTime(watch.Elapsed.Ticks), new DateTime(eta.Ticks))); } } }
using J2N.Text; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using JCG = J2N.Collections.Generic; 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. */ /// <summary> /// Merges segments of approximately equal size, subject to /// an allowed number of segments per tier. This is similar /// to <see cref="LogByteSizeMergePolicy"/>, except this merge /// policy is able to merge non-adjacent segment, and /// separates how many segments are merged at once (<see cref="MaxMergeAtOnce"/>) /// from how many segments are allowed /// per tier (<see cref="SegmentsPerTier"/>). This merge /// policy also does not over-merge (i.e. cascade merges). /// /// <para/>For normal merging, this policy first computes a /// "budget" of how many segments are allowed to be in the /// index. If the index is over-budget, then the policy /// sorts segments by decreasing size (pro-rating by percent /// deletes), and then finds the least-cost merge. Merge /// cost is measured by a combination of the "skew" of the /// merge (size of largest segment divided by smallest segment), /// total merge size and percent deletes reclaimed, /// so that merges with lower skew, smaller size /// and those reclaiming more deletes, are /// favored. /// /// <para/>If a merge will produce a segment that's larger than /// <see cref="MaxMergedSegmentMB"/>, then the policy will /// merge fewer segments (down to 1 at once, if that one has /// deletions) to keep the segment size under budget. /// /// <para/><b>NOTE</b>: This policy freely merges non-adjacent /// segments; if this is a problem, use <see cref="LogMergePolicy"/>. /// /// <para/><b>NOTE</b>: This policy always merges by byte size /// of the segments, always pro-rates by percent deletes, /// and does not apply any maximum segment size during /// forceMerge (unlike <see cref="LogByteSizeMergePolicy"/>). /// <para/> /// @lucene.experimental /// </summary> // TODO // - we could try to take into account whether a large // merge is already running (under CMS) and then bias // ourselves towards picking smaller merges if so (or, // maybe CMS should do so) public class TieredMergePolicy : MergePolicy { /// <summary> /// Default noCFSRatio. If a merge's size is >= 10% of /// the index, then we disable compound file for it. /// </summary> /// <seealso cref="MergePolicy.NoCFSRatio"/> public new static readonly double DEFAULT_NO_CFS_RATIO = 0.1; private int maxMergeAtOnce = 10; private long maxMergedSegmentBytes = 5 * 1024 * 1024 * 1024L; private int maxMergeAtOnceExplicit = 30; private long floorSegmentBytes = 2 * 1024 * 1024L; private double segsPerTier = 10.0; private double forceMergeDeletesPctAllowed = 10.0; private double reclaimDeletesWeight = 2.0; /// <summary> /// Sole constructor, setting all settings to their /// defaults. /// </summary> public TieredMergePolicy() : base(DEFAULT_NO_CFS_RATIO, MergePolicy.DEFAULT_MAX_CFS_SEGMENT_SIZE) { } /// <summary> /// Gets or sets maximum number of segments to be merged at a time /// during "normal" merging. For explicit merging (eg, /// <see cref="IndexWriter.ForceMerge(int)"/> or /// <see cref="IndexWriter.ForceMergeDeletes()"/> was called), see /// <see cref="MaxMergeAtOnceExplicit"/>. Default is 10. /// </summary> public virtual int MaxMergeAtOnce { get => maxMergeAtOnce; set { if (value < 2) { throw new ArgumentException("maxMergeAtOnce must be > 1 (got " + value + ")"); } maxMergeAtOnce = value; } } // TODO: should addIndexes do explicit merging, too? And, // if user calls IW.maybeMerge "explicitly" /// <summary> /// Gets or sets maximum number of segments to be merged at a time, /// during <see cref="IndexWriter.ForceMerge(int)"/> or /// <see cref="IndexWriter.ForceMergeDeletes()"/>. Default is 30. /// </summary> public virtual int MaxMergeAtOnceExplicit { get => maxMergeAtOnceExplicit; set { if (value < 2) { throw new ArgumentException("maxMergeAtOnceExplicit must be > 1 (got " + value + ")"); } maxMergeAtOnceExplicit = value; } } /// <summary> /// Gets or sets maximum sized segment to produce during /// normal merging. This setting is approximate: the /// estimate of the merged segment size is made by summing /// sizes of to-be-merged segments (compensating for /// percent deleted docs). Default is 5 GB. /// </summary> public virtual double MaxMergedSegmentMB { get => maxMergedSegmentBytes / 1024 / 1024.0; set { if (value < 0.0) { throw new ArgumentException("maxMergedSegmentMB must be >=0 (got " + value.ToString("0.0") + ")"); } value *= 1024 * 1024; maxMergedSegmentBytes = (value > long.MaxValue) ? long.MaxValue : (long)value; } } /// <summary> /// Controls how aggressively merges that reclaim more /// deletions are favored. Higher values will more /// aggressively target merges that reclaim deletions, but /// be careful not to go so high that way too much merging /// takes place; a value of 3.0 is probably nearly too /// high. A value of 0.0 means deletions don't impact /// merge selection. /// </summary> public virtual double ReclaimDeletesWeight { get => reclaimDeletesWeight; set { if (value < 0.0) { throw new ArgumentException("reclaimDeletesWeight must be >= 0.0 (got " + value.ToString("0.0") + ")"); } reclaimDeletesWeight = value; } } /// <summary> /// Segments smaller than this are "rounded up" to this /// size, ie treated as equal (floor) size for merge /// selection. this is to prevent frequent flushing of /// tiny segments from allowing a long tail in the index. /// Default is 2 MB. /// </summary> public virtual double FloorSegmentMB { get => floorSegmentBytes / (1024 * 1024.0); set { if (value <= 0.0) { throw new ArgumentException("floorSegmentMB must be >= 0.0 (got " + value.ToString("0.0") + ")"); } value *= 1024 * 1024; floorSegmentBytes = (value > long.MaxValue) ? long.MaxValue : (long)value; } } /// <summary> /// When forceMergeDeletes is called, we only merge away a /// segment if its delete percentage is over this /// threshold. Default is 10%. /// </summary> public virtual double ForceMergeDeletesPctAllowed { get => forceMergeDeletesPctAllowed; set { if (value < 0.0 || value > 100.0) { throw new ArgumentException("forceMergeDeletesPctAllowed must be between 0.0 and 100.0 inclusive (got " + value.ToString("0.0") + ")"); } forceMergeDeletesPctAllowed = value; } } /// <summary> /// Gets or sets the allowed number of segments per tier. Smaller /// values mean more merging but fewer segments. /// /// <para/><b>NOTE</b>: this value should be >= the /// <see cref="MaxMergeAtOnce"/> otherwise you'll force too much /// merging to occur. /// /// <para/>Default is 10.0. /// </summary> public virtual double SegmentsPerTier { get => segsPerTier; set { if (value < 2.0) { throw new ArgumentException("segmentsPerTier must be >= 2.0 (got " + value.ToString("0.0") + ")"); } segsPerTier = value; } } private class SegmentByteSizeDescending : IComparer<SegmentCommitInfo> { private readonly TieredMergePolicy outerInstance; public SegmentByteSizeDescending(TieredMergePolicy outerInstance) { this.outerInstance = outerInstance; } public virtual int Compare(SegmentCommitInfo o1, SegmentCommitInfo o2) { try { long sz1 = outerInstance.Size(o1); long sz2 = outerInstance.Size(o2); if (sz1 > sz2) { return -1; } else if (sz2 > sz1) { return 1; } else { return o1.Info.Name.CompareToOrdinal(o2.Info.Name); } } catch (IOException ioe) { throw new Exception(ioe.ToString(), ioe); } } } /// <summary> /// Holds score and explanation for a single candidate /// merge. /// </summary> protected abstract class MergeScore { /// <summary> /// Sole constructor. (For invocation by subclass /// constructors, typically implicit.) /// </summary> protected MergeScore() { } /// <summary> /// Returns the score for this merge candidate; lower /// scores are better. /// </summary> public abstract double Score { get; } /// <summary> /// Human readable explanation of how the merge got this /// score. /// </summary> public abstract string Explanation { get; } } public override MergeSpecification FindMerges(MergeTrigger mergeTrigger, SegmentInfos infos) { if (Verbose()) { Message("findMerges: " + infos.Count + " segments"); } if (infos.Count == 0) { return null; } ICollection<SegmentCommitInfo> merging = m_writer.Get().MergingSegments; ICollection<SegmentCommitInfo> toBeMerged = new JCG.HashSet<SegmentCommitInfo>(); List<SegmentCommitInfo> infosSorted = new List<SegmentCommitInfo>(infos.AsList()); infosSorted.Sort(new SegmentByteSizeDescending(this)); // Compute total index bytes & print details about the index long totIndexBytes = 0; long minSegmentBytes = long.MaxValue; foreach (SegmentCommitInfo info in infosSorted) { long segBytes = Size(info); if (Verbose()) { string extra = merging.Contains(info) ? " [merging]" : ""; if (segBytes >= maxMergedSegmentBytes / 2.0) { extra += " [skip: too large]"; } else if (segBytes < floorSegmentBytes) { extra += " [floored]"; } Message(" seg=" + m_writer.Get().SegString(info) + " size=" + string.Format("{0:0.000}", segBytes / 1024 / 1024.0) + " MB" + extra); } minSegmentBytes = Math.Min(segBytes, minSegmentBytes); // Accum total byte size totIndexBytes += segBytes; } // If we have too-large segments, grace them out // of the maxSegmentCount: int tooBigCount = 0; while (tooBigCount < infosSorted.Count && Size(infosSorted[tooBigCount]) >= maxMergedSegmentBytes / 2.0) { totIndexBytes -= Size(infosSorted[tooBigCount]); tooBigCount++; } minSegmentBytes = FloorSize(minSegmentBytes); // Compute max allowed segs in the index long levelSize = minSegmentBytes; long bytesLeft = totIndexBytes; double allowedSegCount = 0; while (true) { double segCountLevel = bytesLeft / (double)levelSize; if (segCountLevel < segsPerTier) { allowedSegCount += Math.Ceiling(segCountLevel); break; } allowedSegCount += segsPerTier; bytesLeft -= (long)(segsPerTier * levelSize); levelSize *= maxMergeAtOnce; } int allowedSegCountInt = (int)allowedSegCount; MergeSpecification spec = null; // Cycle to possibly select more than one merge: while (true) { long mergingBytes = 0; // Gather eligible segments for merging, ie segments // not already being merged and not already picked (by // prior iteration of this loop) for merging: IList<SegmentCommitInfo> eligible = new List<SegmentCommitInfo>(); for (int idx = tooBigCount; idx < infosSorted.Count; idx++) { SegmentCommitInfo info = infosSorted[idx]; if (merging.Contains(info)) { mergingBytes += info.GetSizeInBytes(); } else if (!toBeMerged.Contains(info)) { eligible.Add(info); } } bool maxMergeIsRunning = mergingBytes >= maxMergedSegmentBytes; if (Verbose()) { Message(" allowedSegmentCount=" + allowedSegCountInt + " vs count=" + infosSorted.Count + " (eligible count=" + eligible.Count + ") tooBigCount=" + tooBigCount); } if (eligible.Count == 0) { return spec; } if (eligible.Count >= allowedSegCountInt) { // OK we are over budget -- find best merge! MergeScore bestScore = null; IList<SegmentCommitInfo> best = null; bool bestTooLarge = false; long bestMergeBytes = 0; // Consider all merge starts: for (int startIdx = 0; startIdx <= eligible.Count - maxMergeAtOnce; startIdx++) { long totAfterMergeBytes = 0; IList<SegmentCommitInfo> candidate = new List<SegmentCommitInfo>(); bool hitTooLarge = false; for (int idx = startIdx; idx < eligible.Count && candidate.Count < maxMergeAtOnce; idx++) { SegmentCommitInfo info = eligible[idx]; long segBytes = Size(info); if (totAfterMergeBytes + segBytes > maxMergedSegmentBytes) { hitTooLarge = true; // NOTE: we continue, so that we can try // "packing" smaller segments into this merge // to see if we can get closer to the max // size; this in general is not perfect since // this is really "bin packing" and we'd have // to try different permutations. continue; } candidate.Add(info); totAfterMergeBytes += segBytes; } MergeScore score = Score(candidate, hitTooLarge, mergingBytes); if (Verbose()) { Message(" maybe=" + m_writer.Get().SegString(candidate) + " score=" + score.Score + " " + score.Explanation + " tooLarge=" + hitTooLarge + " size=" + string.Format("{0:0.000} MB", totAfterMergeBytes / 1024.0 / 1024.0)); } // If we are already running a max sized merge // (maxMergeIsRunning), don't allow another max // sized merge to kick off: if ((bestScore == null || score.Score < bestScore.Score) && (!hitTooLarge || !maxMergeIsRunning)) { best = candidate; bestScore = score; bestTooLarge = hitTooLarge; bestMergeBytes = totAfterMergeBytes; } } if (best != null) { if (spec == null) { spec = new MergeSpecification(); } OneMerge merge = new OneMerge(best); spec.Add(merge); foreach (SegmentCommitInfo info in merge.Segments) { toBeMerged.Add(info); } if (Verbose()) { Message(" add merge=" + m_writer.Get().SegString(merge.Segments) + " size=" + string.Format("{0:0.000} MB", bestMergeBytes / 1024.0 / 1024.0) + " score=" + string.Format("{0:0.000}", bestScore.Score) + " " + bestScore.Explanation + (bestTooLarge ? " [max merge]" : "")); } } else { return spec; } } else { return spec; } } } /// <summary> /// Expert: scores one merge; subclasses can override. </summary> protected virtual MergeScore Score(IList<SegmentCommitInfo> candidate, bool hitTooLarge, long mergingBytes) { long totBeforeMergeBytes = 0; long totAfterMergeBytes = 0; long totAfterMergeBytesFloored = 0; foreach (SegmentCommitInfo info in candidate) { long segBytes = Size(info); totAfterMergeBytes += segBytes; totAfterMergeBytesFloored += FloorSize(segBytes); totBeforeMergeBytes += info.GetSizeInBytes(); } // Roughly measure "skew" of the merge, i.e. how // "balanced" the merge is (whether the segments are // about the same size), which can range from // 1.0/numSegsBeingMerged (good) to 1.0 (poor). Heavily // lopsided merges (skew near 1.0) is no good; it means // O(N^2) merge cost over time: double skew; if (hitTooLarge) { // Pretend the merge has perfect skew; skew doesn't // matter in this case because this merge will not // "cascade" and so it cannot lead to N^2 merge cost // over time: skew = 1.0 / maxMergeAtOnce; } else { skew = ((double)FloorSize(Size(candidate[0]))) / totAfterMergeBytesFloored; } // Strongly favor merges with less skew (smaller // mergeScore is better): double mergeScore = skew; // Gently favor smaller merges over bigger ones. We // don't want to make this exponent too large else we // can end up doing poor merges of small segments in // order to avoid the large merges: mergeScore *= Math.Pow(totAfterMergeBytes, 0.05); // Strongly favor merges that reclaim deletes: double nonDelRatio = ((double)totAfterMergeBytes) / totBeforeMergeBytes; mergeScore *= Math.Pow(nonDelRatio, reclaimDeletesWeight); double finalMergeScore = mergeScore; return new MergeScoreAnonymousInnerClassHelper(this, skew, nonDelRatio, finalMergeScore); } private class MergeScoreAnonymousInnerClassHelper : MergeScore { private readonly TieredMergePolicy outerInstance; private double skew; private double nonDelRatio; private double finalMergeScore; public MergeScoreAnonymousInnerClassHelper(TieredMergePolicy outerInstance, double skew, double nonDelRatio, double finalMergeScore) { this.outerInstance = outerInstance; this.skew = skew; this.nonDelRatio = nonDelRatio; this.finalMergeScore = finalMergeScore; } public override double Score => finalMergeScore; public override string Explanation => "skew=" + string.Format(CultureInfo.InvariantCulture, "{0:F3}", skew) + " nonDelRatio=" + string.Format(CultureInfo.InvariantCulture, "{0:F3}", nonDelRatio); } public override MergeSpecification FindForcedMerges(SegmentInfos infos, int maxSegmentCount, IDictionary<SegmentCommitInfo, bool?> segmentsToMerge) { if (Verbose()) { Message("FindForcedMerges maxSegmentCount=" + maxSegmentCount + " infos=" + m_writer.Get().SegString(infos.Segments) + " segmentsToMerge=" + string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", segmentsToMerge)); } List<SegmentCommitInfo> eligible = new List<SegmentCommitInfo>(); bool forceMergeRunning = false; ICollection<SegmentCommitInfo> merging = m_writer.Get().MergingSegments; bool? segmentIsOriginal = false; foreach (SegmentCommitInfo info in infos.Segments) { bool? isOriginal; if (segmentsToMerge.TryGetValue(info, out isOriginal)) { segmentIsOriginal = isOriginal; if (!merging.Contains(info)) { eligible.Add(info); } else { forceMergeRunning = true; } } } if (eligible.Count == 0) { return null; } if ((maxSegmentCount > 1 && eligible.Count <= maxSegmentCount) || (maxSegmentCount == 1 && eligible.Count == 1 && (segmentIsOriginal == false || IsMerged(infos, eligible[0])))) { if (Verbose()) { Message("already merged"); } return null; } eligible.Sort(new SegmentByteSizeDescending(this)); if (Verbose()) { Message("eligible=" + string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", eligible)); Message("forceMergeRunning=" + forceMergeRunning); } int end = eligible.Count; MergeSpecification spec = null; // Do full merges, first, backwards: while (end >= maxMergeAtOnceExplicit + maxSegmentCount - 1) { if (spec == null) { spec = new MergeSpecification(); } OneMerge merge = new OneMerge(eligible.SubList(end - maxMergeAtOnceExplicit, end)); if (Verbose()) { Message("add merge=" + m_writer.Get().SegString(merge.Segments)); } spec.Add(merge); end -= maxMergeAtOnceExplicit; } if (spec == null && !forceMergeRunning) { // Do final merge int numToMerge = end - maxSegmentCount + 1; OneMerge merge = new OneMerge(eligible.SubList(end - numToMerge, end)); if (Verbose()) { Message("add final merge=" + merge.SegString(m_writer.Get().Directory)); } spec = new MergeSpecification(); spec.Add(merge); } return spec; } public override MergeSpecification FindForcedDeletesMerges(SegmentInfos infos) { if (Verbose()) { Message("findForcedDeletesMerges infos=" + m_writer.Get().SegString(infos.Segments) + " forceMergeDeletesPctAllowed=" + forceMergeDeletesPctAllowed); } List<SegmentCommitInfo> eligible = new List<SegmentCommitInfo>(); ICollection<SegmentCommitInfo> merging = m_writer.Get().MergingSegments; foreach (SegmentCommitInfo info in infos.Segments) { double pctDeletes = 100.0 * ((double)m_writer.Get().NumDeletedDocs(info)) / info.Info.DocCount; if (pctDeletes > forceMergeDeletesPctAllowed && !merging.Contains(info)) { eligible.Add(info); } } if (eligible.Count == 0) { return null; } eligible.Sort(new SegmentByteSizeDescending(this)); if (Verbose()) { Message("eligible=" + string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", eligible)); } int start = 0; MergeSpecification spec = null; while (start < eligible.Count) { // Don't enforce max merged size here: app is explicitly // calling forceMergeDeletes, and knows this may take a // long time / produce big segments (like forceMerge): int end = Math.Min(start + maxMergeAtOnceExplicit, eligible.Count); if (spec == null) { spec = new MergeSpecification(); } OneMerge merge = new OneMerge(eligible.SubList(start, end)); if (Verbose()) { Message("add merge=" + m_writer.Get().SegString(merge.Segments)); } spec.Add(merge); start = end; } return spec; } protected override void Dispose(bool disposing) { } private long FloorSize(long bytes) { return Math.Max(floorSegmentBytes, bytes); } private bool Verbose() { IndexWriter w = m_writer.Get(); return w != null && w.infoStream.IsEnabled("TMP"); } private void Message(string message) { m_writer.Get().infoStream.Message("TMP", message); } public override string ToString() { StringBuilder sb = new StringBuilder("[" + this.GetType().Name + ": "); sb.Append("maxMergeAtOnce=").Append(maxMergeAtOnce).Append(", "); sb.Append("maxMergeAtOnceExplicit=").Append(maxMergeAtOnceExplicit).Append(", "); sb.Append("maxMergedSegmentMB=").Append(maxMergedSegmentBytes / 1024 / 1024.0).Append(", "); sb.Append("floorSegmentMB=").Append(floorSegmentBytes / 1024 / 1024.0).Append(", "); sb.Append("forceMergeDeletesPctAllowed=").Append(forceMergeDeletesPctAllowed).Append(", "); sb.Append("segmentsPerTier=").Append(segsPerTier).Append(", "); sb.Append("maxCFSSegmentSizeMB=").Append(MaxCFSSegmentSizeMB).Append(", "); sb.Append("noCFSRatio=").Append(m_noCFSRatio); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; using Orleans; using Orleans.GrainDirectory; using Orleans.Metadata; using Orleans.Runtime; using Orleans.Runtime.GrainDirectory; using TestExtensions; using Xunit; using Xunit.Abstractions; namespace UnitTests.Directory { [TestCategory("BVT"), TestCategory("Directory")] public class CachedGrainLocatorTests { private readonly LoggerFactory loggerFactory; private readonly SiloLifecycleSubject lifecycle; private readonly IGrainDirectory grainDirectory; private readonly GrainDirectoryResolver grainDirectoryResolver; private readonly MockClusterMembershipService mockMembershipService; private readonly CachedGrainLocator grainLocator; public CachedGrainLocatorTests(ITestOutputHelper output) { this.loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(output) }); this.lifecycle = new SiloLifecycleSubject(this.loggerFactory.CreateLogger<SiloLifecycleSubject>()); this.grainDirectory = Substitute.For<IGrainDirectory>(); var services = new ServiceCollection() .AddSingleton(typeof(IKeyedServiceCollection<,>), typeof(KeyedServiceCollection<,>)) .AddSingletonKeyedService(GrainDirectoryAttribute.DEFAULT_GRAIN_DIRECTORY, (sp, name) => this.grainDirectory) .BuildServiceProvider(); this.grainDirectoryResolver = new GrainDirectoryResolver( services, new GrainPropertiesResolver(new NoOpClusterManifestProvider()), Array.Empty<IGrainDirectoryResolver>()); this.mockMembershipService = new MockClusterMembershipService(); this.grainLocator = new CachedGrainLocator( this.grainDirectoryResolver, this.mockMembershipService.Target); this.grainLocator.Participate(this.lifecycle); } // TODO //[Fact] //public void ConvertActivationAddressToGrainAddress() //{ // var expected = GenerateActivationAddress(); // var grainAddress = expected.ToGrainAddress(); // Assert.Equal(expected, grainAddress.ToActivationAddress()); //} [Fact] public async Task RegisterWhenNoOtherEntryExists() { var silo = GenerateSiloAddress(); // Setup membership service this.mockMembershipService.UpdateSiloStatus(silo, SiloStatus.Active, "exp"); await this.lifecycle.OnStart(); await WaitUntilClusterChangePropagated(); var expected = GenerateGrainAddress(silo); this.grainDirectory.Register(expected).Returns(expected); var actual = await this.grainLocator.Register(expected); Assert.Equal(expected, actual); await this.grainDirectory.Received(1).Register(expected); // Now should be in cache Assert.True(this.grainLocator.TryLookupInCache(expected.GrainId, out var result)); Assert.NotNull(result); Assert.Equal(expected, result); } [Fact] public async Task RegisterWhenOtherEntryExists() { var expectedSilo = GenerateSiloAddress(); var otherSilo = GenerateSiloAddress(); // Setup membership service this.mockMembershipService.UpdateSiloStatus(expectedSilo, SiloStatus.Active, "exp"); await this.lifecycle.OnStart(); await WaitUntilClusterChangePropagated(); var expectedAddr = GenerateGrainAddress(expectedSilo); var otherAddr = GenerateGrainAddress(otherSilo); this.grainDirectory.Register(otherAddr).Returns(expectedAddr); var actual = await this.grainLocator.Register(otherAddr); Assert.Equal(expectedAddr, actual); await this.grainDirectory.Received(1).Register(otherAddr); // Now should be in cache Assert.True(this.grainLocator.TryLookupInCache(expectedAddr.GrainId, out var result)); Assert.NotNull(result); Assert.Equal(expectedAddr, result); } [Fact] public async Task RegisterWhenOtherEntryExistsButSiloIsDead() { var expectedSilo = GenerateSiloAddress(); var outdatedSilo = GenerateSiloAddress(); // Setup membership service this.mockMembershipService.UpdateSiloStatus(expectedSilo, SiloStatus.Active, "exp"); this.mockMembershipService.UpdateSiloStatus(outdatedSilo, SiloStatus.Dead, "old"); await this.lifecycle.OnStart(); await WaitUntilClusterChangePropagated(); var expectedAddr = GenerateGrainAddress(expectedSilo); var outdatedAddr = GenerateGrainAddress(outdatedSilo); // First returns the outdated entry, then the new one this.grainDirectory.Register(expectedAddr).Returns(outdatedAddr, expectedAddr); var actual = await this.grainLocator.Register(expectedAddr); Assert.Equal(expectedAddr, actual); await this.grainDirectory.Received(2).Register(expectedAddr); await this.grainDirectory.Received(1).Unregister(outdatedAddr); // Now should be in cache Assert.True(this.grainLocator.TryLookupInCache(expectedAddr.GrainId, out var result)); Assert.NotNull(result); Assert.Equal(expectedAddr, result); await this.lifecycle.OnStop(); } [Fact] public async Task LookupPopulateTheCache() { var expectedSilo = GenerateSiloAddress(); // Setup membership service this.mockMembershipService.UpdateSiloStatus(expectedSilo, SiloStatus.Active, "exp"); await this.lifecycle.OnStart(); await WaitUntilClusterChangePropagated(); var grainAddress = GenerateGrainAddress(expectedSilo); this.grainDirectory.Lookup(grainAddress.GrainId).Returns(grainAddress); // Cache should be empty Assert.False(this.grainLocator.TryLookupInCache(grainAddress.GrainId, out _)); // Do a remote lookup var result = await this.grainLocator.Lookup(grainAddress.GrainId); Assert.NotNull(result); Assert.Equal(grainAddress, result); // Now cache should be populated Assert.True(this.grainLocator.TryLookupInCache(grainAddress.GrainId, out var cachedValue)); Assert.NotNull(cachedValue); Assert.Equal(grainAddress, cachedValue); } [Fact] public async Task LookupWhenEntryExistsButSiloIsDead() { var outdatedSilo = GenerateSiloAddress(); // Setup membership service this.mockMembershipService.UpdateSiloStatus(outdatedSilo, SiloStatus.Dead, "old"); await this.lifecycle.OnStart(); await WaitUntilClusterChangePropagated(); var outdatedAddr = GenerateGrainAddress(outdatedSilo); this.grainDirectory.Lookup(outdatedAddr.GrainId).Returns(outdatedAddr); var actual = await this.grainLocator.Lookup(outdatedAddr.GrainId); Assert.Null(actual); await this.grainDirectory.Received(1).Lookup(outdatedAddr.GrainId); await this.grainDirectory.Received(1).Unregister(outdatedAddr); Assert.False(this.grainLocator.TryLookupInCache(outdatedAddr.GrainId, out _)); await this.lifecycle.OnStop(); } [Fact] public async Task LocalLookupWhenEntryExistsButSiloIsDead() { var outdatedSilo = GenerateSiloAddress(); // Setup membership service this.mockMembershipService.UpdateSiloStatus(outdatedSilo, SiloStatus.Dead, "old"); await this.lifecycle.OnStart(); await WaitUntilClusterChangePropagated(); var outdatedAddr = GenerateGrainAddress(outdatedSilo); this.grainDirectory.Lookup(outdatedAddr.GrainId).Returns(outdatedAddr); Assert.False(this.grainLocator.TryLookupInCache(outdatedAddr.GrainId, out _)); // Local lookup should never call the directory await this.grainDirectory.DidNotReceive().Lookup(outdatedAddr.GrainId); await this.grainDirectory.DidNotReceive().Unregister(outdatedAddr); await this.lifecycle.OnStop(); } [Fact] public async Task CleanupWhenSiloIsDead() { var expectedSilo = GenerateSiloAddress(); var outdatedSilo = GenerateSiloAddress(); // Setup membership service this.mockMembershipService.UpdateSiloStatus(expectedSilo, SiloStatus.Active, "exp"); this.mockMembershipService.UpdateSiloStatus(outdatedSilo, SiloStatus.Active, "old"); await this.lifecycle.OnStart(); await WaitUntilClusterChangePropagated(); var expectedAddr = GenerateGrainAddress(expectedSilo); var outdatedAddr = GenerateGrainAddress(outdatedSilo); // Register two entries this.grainDirectory.Register(expectedAddr).Returns(expectedAddr); this.grainDirectory.Register(outdatedAddr).Returns(outdatedAddr); await this.grainLocator.Register(expectedAddr); await this.grainLocator.Register(outdatedAddr); // Simulate a dead silo this.mockMembershipService.UpdateSiloStatus(outdatedAddr.SiloAddress, SiloStatus.Dead, "old"); // Wait a bit for the update to be processed await WaitUntilClusterChangePropagated(); // Cleanup function from grain directory should have been called await this.grainDirectory .Received(1) .UnregisterSilos(Arg.Is<List<SiloAddress>>(list => list.Count == 1 && list.Contains(outdatedAddr.SiloAddress))); // Cache should have been cleaned Assert.False(this.grainLocator.TryLookupInCache(outdatedAddr.GrainId, out var unused1)); Assert.True(this.grainLocator.TryLookupInCache(expectedAddr.GrainId, out var unused2)); var result = await this.grainLocator.Lookup(expectedAddr.GrainId); Assert.NotNull(result); Assert.Equal(expectedAddr, result); await this.lifecycle.OnStop(); } [Fact] public async Task UnregisterCallDirectoryAndCleanCache() { var expectedSilo = GenerateSiloAddress(); // Setup membership service this.mockMembershipService.UpdateSiloStatus(expectedSilo, SiloStatus.Active, "exp"); await this.lifecycle.OnStart(); await WaitUntilClusterChangePropagated(); var expectedAddr = GenerateGrainAddress(expectedSilo); this.grainDirectory.Register(expectedAddr).Returns(expectedAddr); // Register to populate cache await this.grainLocator.Register(expectedAddr); // Unregister and check if cache was cleaned await this.grainLocator.Unregister(expectedAddr, UnregistrationCause.Force); Assert.False(this.grainLocator.TryLookupInCache(expectedAddr.GrainId, out _)); } private GrainAddress GenerateGrainAddress(SiloAddress siloAddress = null) { return new GrainAddress { GrainId = GrainId.Create(GrainType.Create("test"), GrainIdKeyExtensions.CreateGuidKey(Guid.NewGuid())), ActivationId = ActivationId.NewId(), SiloAddress = siloAddress ?? GenerateSiloAddress(), MembershipVersion = this.mockMembershipService.CurrentVersion, }; } private int generation = 0; private SiloAddress GenerateSiloAddress() => SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 5000), ++generation); private async Task WaitUntilClusterChangePropagated() { await Until(() => this.mockMembershipService.CurrentVersion == ((CachedGrainLocator.ITestAccessor)this.grainLocator).LastMembershipVersion); } private static async Task Until(Func<bool> condition) { var maxTimeout = 40_000; while (!condition() && (maxTimeout -= 10) > 0) await Task.Delay(10); Assert.True(maxTimeout > 0); } private class NoOpClusterManifestProvider : IClusterManifestProvider { public ClusterManifest Current => new ClusterManifest( MajorMinorVersion.Zero, ImmutableDictionary<SiloAddress, GrainManifest>.Empty, ImmutableArray.Create(new GrainManifest(ImmutableDictionary<GrainType, GrainProperties>.Empty, ImmutableDictionary<GrainInterfaceType, GrainInterfaceProperties>.Empty))); public IAsyncEnumerable<ClusterManifest> Updates => this.GetUpdates(); public GrainManifest LocalGrainManifest { get; } = new GrainManifest(ImmutableDictionary<GrainType, GrainProperties>.Empty, ImmutableDictionary<GrainInterfaceType, GrainInterfaceProperties>.Empty); private async IAsyncEnumerable<ClusterManifest> GetUpdates() { yield return this.Current; await Task.Delay(100); yield break; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Reflection; using PipelineResultTypes = System.Management.Automation.Runspaces.PipelineResultTypes; namespace System.Management.Automation { #region Auxiliary /// <summary> /// An interface that a /// <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/> /// must implement to indicate that it has dynamic parameters. /// </summary> /// <remarks> /// Dynamic parameters allow a /// <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/> /// to define additional parameters based on the value of /// the formal arguments. For example, the parameters of /// "set-itemproperty" for the file system provider vary /// depending on whether the target object is a file or directory. /// </remarks> /// <seealso cref="Cmdlet"/> /// <seealso cref="PSCmdlet"/> /// <seealso cref="RuntimeDefinedParameter"/> /// <seealso cref="RuntimeDefinedParameterDictionary"/> #nullable enable public interface IDynamicParameters { /// <summary> /// Returns an instance of an object that defines the /// dynamic parameters for this /// <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/>. /// </summary> /// <returns> /// This method should return an object that has properties and fields /// decorated with parameter attributes similar to a /// <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/>. /// These attributes include <see cref="ParameterAttribute"/>, /// <see cref="AliasAttribute"/>, argument transformation and /// validation attributes, etc. /// /// Alternately, it can return a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/> /// instead. /// /// The <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/> /// should hold on to a reference to the object which it returns from /// this method, since the argument values for the dynamic parameters /// specified by that object will be set in that object. /// /// This method will be called after all formal (command-line) /// parameters are set, but before <see cref="Cmdlet.BeginProcessing"/> /// is called and before any incoming pipeline objects are read. /// Therefore, parameters which allow input from the pipeline /// may not be set at the time this method is called, /// even if the parameters are mandatory. /// </returns> object? GetDynamicParameters(); } #nullable restore /// <summary> /// Type used to define a parameter on a cmdlet script of function that /// can only be used as a switch. /// </summary> public readonly struct SwitchParameter { private readonly bool _isPresent; /// <summary> /// Returns true if the parameter was specified on the command line, false otherwise. /// </summary> /// <value>True if the parameter was specified, false otherwise</value> public bool IsPresent { get { return _isPresent; } } /// <summary> /// Implicit cast operator for casting SwitchParameter to bool. /// </summary> /// <param name="switchParameter">The SwitchParameter object to convert to bool.</param> /// <returns>The corresponding boolean value.</returns> public static implicit operator bool(SwitchParameter switchParameter) { return switchParameter.IsPresent; } /// <summary> /// Implicit cast operator for casting bool to SwitchParameter. /// </summary> /// <param name="value">The bool to convert to SwitchParameter.</param> /// <returns>The corresponding boolean value.</returns> public static implicit operator SwitchParameter(bool value) { return new SwitchParameter(value); } /// <summary> /// Explicit method to convert a SwitchParameter to a boolean value. /// </summary> /// <returns>The boolean equivalent of the SwitchParameter.</returns> public bool ToBool() { return _isPresent; } /// <summary> /// Construct a SwitchParameter instance with a particular value. /// </summary> /// <param name="isPresent"> /// If true, it indicates that the switch is present, flase otherwise. /// </param> public SwitchParameter(bool isPresent) { _isPresent = isPresent; } /// <summary> /// Static method that returns a instance of SwitchParameter that indicates that it is present. /// </summary> /// <value>An instance of a switch parameter that will convert to true in a boolean context</value> public static SwitchParameter Present { get { return new SwitchParameter(true); } } /// <summary> /// Compare this switch parameter to another object. /// </summary> /// <param name="obj">An object to compare against.</param> /// <returns>True if the objects are the same value.</returns> public override bool Equals(object obj) { if (obj is bool) { return _isPresent == (bool)obj; } else if (obj is SwitchParameter) { return _isPresent == ((SwitchParameter)obj).IsPresent; } else { return false; } } /// <summary> /// Returns the hash code for this switch parameter. /// </summary> /// <returns>The hash code for this cobject.</returns> public override int GetHashCode() { return _isPresent.GetHashCode(); } /// <summary> /// Implement the == operator for switch parameters objects. /// </summary> /// <param name="first">First object to compare.</param> /// <param name="second">Second object to compare.</param> /// <returns>True if they are the same.</returns> public static bool operator ==(SwitchParameter first, SwitchParameter second) { return first.Equals(second); } /// <summary> /// Implement the != operator for switch parameters. /// </summary> /// <param name="first">First object to compare.</param> /// <param name="second">Second object to compare.</param> /// <returns>True if they are different.</returns> public static bool operator !=(SwitchParameter first, SwitchParameter second) { return !first.Equals(second); } /// <summary> /// Implement the == operator for switch parameters and booleans. /// </summary> /// <param name="first">First object to compare.</param> /// <param name="second">Second object to compare.</param> /// <returns>True if they are the same.</returns> public static bool operator ==(SwitchParameter first, bool second) { return first.Equals(second); } /// <summary> /// Implement the != operator for switch parameters and booleans. /// </summary> /// <param name="first">First object to compare.</param> /// <param name="second">Second object to compare.</param> /// <returns>True if they are different.</returns> public static bool operator !=(SwitchParameter first, bool second) { return !first.Equals(second); } /// <summary> /// Implement the == operator for bool and switch parameters. /// </summary> /// <param name="first">First object to compare.</param> /// <param name="second">Second object to compare.</param> /// <returns>True if they are the same.</returns> public static bool operator ==(bool first, SwitchParameter second) { return first.Equals(second); } /// <summary> /// Implement the != operator for bool and switch parameters. /// </summary> /// <param name="first">First object to compare.</param> /// <param name="second">Second object to compare.</param> /// <returns>True if they are different.</returns> public static bool operator !=(bool first, SwitchParameter second) { return !first.Equals(second); } /// <summary> /// Returns the string representation for this object. /// </summary> /// <returns>The string for this object.</returns> public override string ToString() { return _isPresent.ToString(); } } /// <summary> /// Interfaces that cmdlets can use to build script blocks and execute scripts. /// </summary> public class CommandInvocationIntrinsics { private readonly ExecutionContext _context; private readonly PSCmdlet _cmdlet; private readonly MshCommandRuntime _commandRuntime; internal CommandInvocationIntrinsics(ExecutionContext context, PSCmdlet cmdlet) { _context = context; if (cmdlet != null) { _cmdlet = cmdlet; _commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; } } internal CommandInvocationIntrinsics(ExecutionContext context) : this(context, null) { } /// <summary> /// If an error occurred while executing the cmdlet, this will be set to true. /// </summary> public bool HasErrors { get { return _commandRuntime.PipelineProcessor.ExecutionFailed; } set { _commandRuntime.PipelineProcessor.ExecutionFailed = value; } } /// <summary> /// Returns a string with all of the variable and expression substitutions done. /// </summary> /// <param name="source">The string to expand. /// </param> /// <returns>The expanded string.</returns> /// <exception cref="ParseException"> /// Thrown if a parse exception occurred during subexpression substitution. /// </exception> public string ExpandString(string source) { if (_cmdlet != null) _cmdlet.ThrowIfStopping(); return _context.Engine.Expand(source); } /// <summary> /// </summary> /// <param name="commandName"></param> /// <param name="type"></param> /// <returns></returns> public CommandInfo GetCommand(string commandName, CommandTypes type) { return GetCommand(commandName, type, null); } /// <summary> /// Returns a command info for a given command name and type, using the specified arguments /// to resolve dynamic parameters. /// </summary> /// <param name="commandName">The command name to search for.</param> /// <param name="type">The command type to search for.</param> /// <param name="arguments">The command arguments used to resolve dynamic parameters.</param> /// <returns>A CommandInfo result that represents the resolved command.</returns> public CommandInfo GetCommand(string commandName, CommandTypes type, object[] arguments) { CommandInfo result = null; try { CommandOrigin commandOrigin = CommandOrigin.Runspace; if (_cmdlet != null) { commandOrigin = _cmdlet.CommandOrigin; } else if (_context != null) { commandOrigin = _context.EngineSessionState.CurrentScope.ScopeOrigin; } result = CommandDiscovery.LookupCommandInfo(commandName, type, SearchResolutionOptions.None, commandOrigin, _context); if ((result != null) && (arguments != null) && (arguments.Length > 0)) { // We've been asked to retrieve dynamic parameters if (result.ImplementsDynamicParameters) { result = result.CreateGetCommandCopy(arguments); } } } catch (CommandNotFoundException) { } return result; } /// <summary> /// This event handler is called when a command is not found. /// If should have a single string parameter that is the name /// of the command and should return a CommandInfo object or null. By default /// it will search the module path looking for a module that exports the /// desired command. /// </summary> public System.EventHandler<CommandLookupEventArgs> CommandNotFoundAction { get; set; } /// <summary> /// This event handler is called before the command lookup is done. /// If should have a single string parameter that is the name /// of the command and should return a CommandInfo object or null. /// </summary> public System.EventHandler<CommandLookupEventArgs> PreCommandLookupAction { get; set; } /// <summary> /// This event handler is after the command lookup is done but before the event object is /// returned to the caller. This allows things like interning scripts to work. /// If should have a single string parameter that is the name /// of the command and should return a CommandInfo object or null. /// </summary> public System.EventHandler<CommandLookupEventArgs> PostCommandLookupAction { get; set; } /// <summary> /// Gets or sets the action that is invoked everytime the runspace location (cwd) is changed. /// </summary> public System.EventHandler<LocationChangedEventArgs> LocationChangedAction { get; set; } /// <summary> /// Returns the CmdletInfo object that corresponds to the name argument. /// </summary> /// <param name="commandName">The name of the cmdlet to look for.</param> /// <returns>The cmdletInfo object if found, null otherwise.</returns> public CmdletInfo GetCmdlet(string commandName) { return GetCmdlet(commandName, _context); } /// <summary> /// Returns the CmdletInfo object that corresponds to the name argument. /// </summary> /// <param name="commandName">The name of the cmdlet to look for.</param> /// <param name="context">The execution context instance to use for lookup.</param> /// <returns>The cmdletInfo object if found, null otherwise.</returns> internal static CmdletInfo GetCmdlet(string commandName, ExecutionContext context) { CmdletInfo current = null; CommandSearcher searcher = new CommandSearcher( commandName, SearchResolutionOptions.None, CommandTypes.Cmdlet, context); while (true) { try { if (!searcher.MoveNext()) { break; } } catch (ArgumentException) { continue; } catch (PathTooLongException) { continue; } catch (FileLoadException) { continue; } catch (MetadataException) { continue; } catch (FormatException) { continue; } current = ((IEnumerator)searcher).Current as CmdletInfo; } return current; } /// <summary> /// Get the cmdlet info using the name of the cmdlet's implementing type. This bypasses /// session state and retrieves the command directly. Note that the help file and snapin/module /// info will both be null on returned object. /// </summary> /// <param name="cmdletTypeName">The type name of the class implementing this cmdlet.</param> /// <returns>CmdletInfo for the cmdlet if found, null otherwise.</returns> public CmdletInfo GetCmdletByTypeName(string cmdletTypeName) { if (string.IsNullOrEmpty(cmdletTypeName)) { throw PSTraceSource.NewArgumentNullException(nameof(cmdletTypeName)); } Exception e = null; Type cmdletType = TypeResolver.ResolveType(cmdletTypeName, out e); if (e != null) { throw e; } if (cmdletType == null) { return null; } CmdletAttribute ca = null; foreach (var attr in cmdletType.GetCustomAttributes(true)) { ca = attr as CmdletAttribute; if (ca != null) break; } if (ca == null) { throw PSTraceSource.NewNotSupportedException(); } string noun = ca.NounName; string verb = ca.VerbName; string cmdletName = verb + "-" + noun; return new CmdletInfo(cmdletName, cmdletType, null, null, _context); } /// <summary> /// Returns a list of all cmdlets... /// </summary> /// <returns></returns> public List<CmdletInfo> GetCmdlets() { return GetCmdlets("*"); } /// <summary> /// Returns all cmdlets whose names match the pattern... /// </summary> /// <returns>A list of CmdletInfo objects...</returns> public List<CmdletInfo> GetCmdlets(string pattern) { if (pattern == null) throw PSTraceSource.NewArgumentNullException(nameof(pattern)); List<CmdletInfo> cmdlets = new List<CmdletInfo>(); CmdletInfo current = null; CommandSearcher searcher = new CommandSearcher( pattern, SearchResolutionOptions.CommandNameIsPattern, CommandTypes.Cmdlet, _context); while (true) { try { if (!searcher.MoveNext()) { break; } } catch (ArgumentException) { continue; } catch (PathTooLongException) { continue; } catch (FileLoadException) { continue; } catch (MetadataException) { continue; } catch (FormatException) { continue; } current = ((IEnumerator)searcher).Current as CmdletInfo; if (current != null) cmdlets.Add(current); } return cmdlets; } /// <summary> /// Searches for PowerShell commands, optionally using wildcard patterns /// and optionally return the full path to applications and scripts rather than /// the simple command name. /// </summary> /// <param name="name">The name of the command to use.</param> /// <param name="nameIsPattern">If true treat the name as a pattern to search for.</param> /// <param name="returnFullName">If true, return the full path to scripts and applications.</param> /// <returns>A list of command names...</returns> public List<string> GetCommandName(string name, bool nameIsPattern, bool returnFullName) { if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } List<string> commands = new List<string>(); foreach (CommandInfo current in this.GetCommands(name, CommandTypes.All, nameIsPattern)) { if (current.CommandType == CommandTypes.Application) { string cmdExtension = System.IO.Path.GetExtension(current.Name); if (!string.IsNullOrEmpty(cmdExtension)) { // Only add the application in PATHEXT... foreach (string extension in CommandDiscovery.PathExtensions) { if (extension.Equals(cmdExtension, StringComparison.OrdinalIgnoreCase)) { if (returnFullName) { commands.Add(current.Definition); } else { commands.Add(current.Name); } } } } } else if (current.CommandType == CommandTypes.ExternalScript) { if (returnFullName) { commands.Add(current.Definition); } else { commands.Add(current.Name); } } else { commands.Add(current.Name); } } return commands; } /// <summary> /// Searches for PowerShell commands, optionally using wildcard patterns. /// </summary> /// <param name="name">The name of the command to use.</param> /// <param name="commandTypes">Type of commands to support.</param> /// <param name="nameIsPattern">If true treat the name as a pattern to search for.</param> /// <returns>Collection of command names...</returns> public IEnumerable<CommandInfo> GetCommands(string name, CommandTypes commandTypes, bool nameIsPattern) { if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } SearchResolutionOptions options = nameIsPattern ? (SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveFunctionPatterns | SearchResolutionOptions.ResolveAliasPatterns) : SearchResolutionOptions.None; return GetCommands(name, commandTypes, options); } internal IEnumerable<CommandInfo> GetCommands(string name, CommandTypes commandTypes, SearchResolutionOptions options, CommandOrigin? commandOrigin = null) { CommandSearcher searcher = new CommandSearcher( name, options, commandTypes, _context); if (commandOrigin != null) { searcher.CommandOrigin = commandOrigin.Value; } while (true) { try { if (!searcher.MoveNext()) { break; } } catch (ArgumentException) { continue; } catch (PathTooLongException) { continue; } catch (FileLoadException) { continue; } catch (MetadataException) { continue; } catch (FormatException) { continue; } CommandInfo commandInfo = ((IEnumerator)searcher).Current as CommandInfo; if (commandInfo != null) { yield return commandInfo; } } } /// <summary> /// Executes a piece of text as a script synchronously in the caller's session state. /// The given text will be executed in a child scope rather than dot-sourced. /// </summary> /// <param name="script">The script text to evaluate.</param> /// <returns>A collection of MshCobjects generated by the script. Never null, but may be empty.</returns> /// <exception cref="ParseException">Thrown if there was a parsing error in the script.</exception> /// <exception cref="RuntimeException">Represents a script-level exception.</exception> /// <exception cref="FlowControlException"></exception> public Collection<PSObject> InvokeScript(string script) { return InvokeScript(script, useNewScope: true, PipelineResultTypes.None, input: null); } /// <summary> /// Executes a piece of text as a script synchronously in the caller's session state. /// The given text will be executed in a child scope rather than dot-sourced. /// </summary> /// <param name="script">The script text to evaluate.</param> /// <param name="args">The arguments to the script, available as $args.</param> /// <returns>A collection of MshCobjects generated by the script. Never null, but may be empty.</returns> /// <exception cref="ParseException">Thrown if there was a parsing error in the script.</exception> /// <exception cref="RuntimeException">Represents a script-level exception.</exception> /// <exception cref="FlowControlException"></exception> public Collection<PSObject> InvokeScript(string script, params object[] args) { return InvokeScript(script, useNewScope: true, PipelineResultTypes.None, input: null, args); } /// <summary> /// Executes a given scriptblock synchonously in the given session state. /// The scriptblock will be executed in the calling scope (dot-sourced) rather than in a new child scope. /// </summary> /// <param name="sessionState">The session state in which to execute the scriptblock.</param> /// <param name="scriptBlock">The scriptblock to execute.</param> /// <param name="args">The arguments to the scriptblock, available as $args.</param> /// <returns>A collection of the PSObjects emitted by the executing scriptblock. Never null, but may be empty.</returns> public Collection<PSObject> InvokeScript( SessionState sessionState, ScriptBlock scriptBlock, params object[] args) { if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } SessionStateInternal _oldSessionState = _context.EngineSessionState; try { _context.EngineSessionState = sessionState.Internal; return InvokeScript( sb: scriptBlock, useNewScope: false, writeToPipeline: PipelineResultTypes.None, input: null, args: args); } finally { _context.EngineSessionState = _oldSessionState; } } /// <summary> /// Invoke a scriptblock in the current runspace, controlling if it gets a new scope. /// </summary> /// <param name="useLocalScope">If true, executes the scriptblock in a new child scope, otherwise the scriptblock is dot-sourced into the calling scope.</param> /// <param name="scriptBlock">The scriptblock to execute.</param> /// <param name="input">Optionall input to the command.</param> /// <param name="args">Arguments to pass to the scriptblock.</param> /// <returns> /// A collection of the PSObjects generated by executing the script. Never null, but may be empty. /// </returns> public Collection<PSObject> InvokeScript( bool useLocalScope, ScriptBlock scriptBlock, IList input, params object[] args) { if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } // Force the current runspace onto the callers thread - this is needed // if this API is going to be callable through the SessionStateProxy on the runspace. var old = System.Management.Automation.Runspaces.Runspace.DefaultRunspace; System.Management.Automation.Runspaces.Runspace.DefaultRunspace = _context.CurrentRunspace; try { return InvokeScript(scriptBlock, useLocalScope, PipelineResultTypes.None, input, args); } finally { System.Management.Automation.Runspaces.Runspace.DefaultRunspace = old; } } /// <summary> /// Executes a piece of text as a script synchronously using the options provided. /// </summary> /// <param name="script">The script to evaluate.</param> /// <param name="useNewScope">If true, evaluate the script in its own scope. /// If false, the script will be evaluated in the current scope i.e. it will be dot-sourced.</param> /// <param name="writeToPipeline">If set to Output, all output will be streamed /// to the output pipe of the calling cmdlet. If set to None, the result will be returned /// to the caller as a collection of PSObjects. No other flags are supported at this time and /// will result in an exception if used.</param> /// <param name="input">The list of objects to use as input to the script.</param> /// <param name="args">The array of arguments to the command, available as $args.</param> /// <returns>A collection of PSObjects generated by the script. This will be /// empty if output was redirected. Never null.</returns> /// <exception cref="ParseException">Thrown if there was a parsing error in the script.</exception> /// <exception cref="RuntimeException">Represents a script-level exception.</exception> /// <exception cref="NotImplementedException">Thrown if any redirect other than output is attempted.</exception> /// <exception cref="FlowControlException"></exception> public Collection<PSObject> InvokeScript( string script, bool useNewScope, PipelineResultTypes writeToPipeline, IList input, params object[] args) { if (script == null) throw new ArgumentNullException(nameof(script)); // Compile the script text into an executable script block. ScriptBlock sb = ScriptBlock.Create(_context, script); return InvokeScript(sb, useNewScope, writeToPipeline, input, args); } private Collection<PSObject> InvokeScript( ScriptBlock sb, bool useNewScope, PipelineResultTypes writeToPipeline, IList input, params object[] args) { if (_cmdlet != null) _cmdlet.ThrowIfStopping(); Cmdlet cmdletToUse = null; ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe; // Check if they want output if ((writeToPipeline & PipelineResultTypes.Output) == PipelineResultTypes.Output) { cmdletToUse = _cmdlet; writeToPipeline &= (~PipelineResultTypes.Output); } // Check if they want error if ((writeToPipeline & PipelineResultTypes.Error) == PipelineResultTypes.Error) { errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe; writeToPipeline &= (~PipelineResultTypes.Error); } if (writeToPipeline != PipelineResultTypes.None) { // The only output types are Output and Error. throw PSTraceSource.NewNotImplementedException(); } // If the cmdletToUse is not null, then the result of the evaluation will be // streamed out the output pipe of the cmdlet. object rawResult; if (cmdletToUse != null) { sb.InvokeUsingCmdlet( contextCmdlet: cmdletToUse, useLocalScope: useNewScope, errorHandlingBehavior: errorHandlingBehavior, dollarUnder: AutomationNull.Value, input: input, scriptThis: AutomationNull.Value, args: args); rawResult = AutomationNull.Value; } else { rawResult = sb.DoInvokeReturnAsIs( useLocalScope: useNewScope, errorHandlingBehavior: errorHandlingBehavior, dollarUnder: AutomationNull.Value, input: input, scriptThis: AutomationNull.Value, args: args); } if (rawResult == AutomationNull.Value) { return new Collection<PSObject>(); } // If the result is already a collection of PSObjects, just return it... Collection<PSObject> result = rawResult as Collection<PSObject>; if (result != null) return result; result = new Collection<PSObject>(); IEnumerator list = null; list = LanguagePrimitives.GetEnumerator(rawResult); if (list != null) { while (list.MoveNext()) { object val = list.Current; result.Add(LanguagePrimitives.AsPSObjectOrNull(val)); } } else { result.Add(LanguagePrimitives.AsPSObjectOrNull(rawResult)); } return result; } /// <summary> /// Compile a string into a script block. /// </summary> /// <param name="scriptText">The source text to compile.</param> /// <returns>The compiled script block.</returns> /// <exception cref="ParseException"></exception> public ScriptBlock NewScriptBlock(string scriptText) { if (_commandRuntime != null) _commandRuntime.ThrowIfStopping(); ScriptBlock result = ScriptBlock.Create(_context, scriptText); return result; } } #endregion Auxiliary /// <summary> /// Defines members used by Cmdlets. /// All Cmdlets must derive from /// <see cref="System.Management.Automation.Cmdlet"/>. /// </summary> /// <remarks> /// Do not attempt to create instances of /// <see cref="System.Management.Automation.Cmdlet"/> /// or its subclasses. /// Instead, derive your own subclasses and mark them with /// <see cref="System.Management.Automation.CmdletAttribute"/>, /// and when your assembly is included in a shell, the Engine will /// take care of instantiating your subclass. /// </remarks> public abstract partial class PSCmdlet : Cmdlet { #region private_members internal bool HasDynamicParameters { get { return this is IDynamicParameters; } } #endregion private_members #region public members /// <summary> /// The name of the parameter set in effect. /// </summary> /// <value>the parameter set name</value> public string ParameterSetName { get { using (PSTransactionManager.GetEngineProtectionScope()) { return _ParameterSetName; } } } /// <summary> /// Contains information about the identity of this cmdlet /// and how it was invoked. /// </summary> /// <value></value> public new InvocationInfo MyInvocation { get { using (PSTransactionManager.GetEngineProtectionScope()) { return base.MyInvocation; } } } /// <summary> /// If the cmdlet declares paging support (via <see cref="CmdletCommonMetadataAttribute.SupportsPaging"/>), /// then <see cref="PagingParameters"/> property contains arguments of the paging parameters. /// Otherwise <see cref="PagingParameters"/> property is <see langword="null"/>. /// </summary> public PagingParameters PagingParameters { get { using (PSTransactionManager.GetEngineProtectionScope()) { if (!this.CommandInfo.CommandMetadata.SupportsPaging) { return null; } if (_pagingParameters == null) { MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { _pagingParameters = mshCommandRuntime.PagingParameters ?? new PagingParameters(mshCommandRuntime); } } return _pagingParameters; } } } private PagingParameters _pagingParameters; #region InvokeCommand private CommandInvocationIntrinsics _invokeCommand; /// <summary> /// Provides access to utility routines for executing scripts /// and creating script blocks. /// </summary> /// <value>Returns an object exposing the utility routines.</value> public CommandInvocationIntrinsics InvokeCommand { get { using (PSTransactionManager.GetEngineProtectionScope()) { return _invokeCommand ??= new CommandInvocationIntrinsics(Context, this); } } } #endregion InvokeCommand #endregion public members } }
// The MIT License (MIT) // Copyright 2015 Siney/Pangweiwei siney@yeah.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace SLua { using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System; using System.Reflection; using UnityEditor; using LuaInterface; using System.Text; using System.Text.RegularExpressions; public class LuaCodeGen : MonoBehaviour { public const string Path = "Assets/Slua/LuaObject/"; public delegate void ExportGenericDelegate(Type t, string ns); static bool autoRefresh = true; static bool IsCompiling { get { if (EditorApplication.isCompiling) { Debug.Log("Unity Editor is compiling, please wait."); } return EditorApplication.isCompiling; } } [InitializeOnLoad] public class Startup { static Startup() { bool ok = System.IO.Directory.Exists(Path); if (!ok && EditorUtility.DisplayDialog("Slua", "Not found lua interface for Unity, generate it now?", "Generate", "No")) { GenerateAll(); } } } [MenuItem("SLua/All/Make")] static public void GenerateAll() { autoRefresh = false; Generate(); GenerateUI(); Custom(); Generate3rdDll(); autoRefresh = true; AssetDatabase.Refresh(); } [MenuItem("SLua/Unity/Make UnityEngine")] static public void Generate() { if (IsCompiling) { return; } Assembly assembly = Assembly.Load("UnityEngine"); Type[] types = assembly.GetExportedTypes(); List<string> uselist; List<string> noUseList; CustomExport.OnGetNoUseList(out noUseList); CustomExport.OnGetUseList(out uselist); List<Type> exports = new List<Type>(); string path = Path + "Unity/"; foreach (Type t in types) { bool export = true; // check type in uselist if (uselist != null && uselist.Count > 0) { export = false; foreach (string str in uselist) { if (t.FullName == str) { export = true; break; } } } else { // check type not in nouselist foreach (string str in noUseList) { if (t.FullName.Contains(str)) { export = false; break; } } } if (export) { if (Generate(t,path)) exports.Add(t); } } GenerateBind(exports, "BindUnity", 0,path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate engine interface finished"); } [MenuItem("SLua/Unity/Make UI (for Unity4.6+)")] static public void GenerateUI() { if (IsCompiling) { return; } List<string> noUseList = new List<string> { "CoroutineTween", "GraphicRebuildTracker", }; Assembly assembly = Assembly.Load("UnityEngine.UI"); Type[] types = assembly.GetExportedTypes(); List<Type> exports = new List<Type>(); string path = Path + "Unity/"; foreach (Type t in types) { bool export = true; foreach (string str in noUseList) { if (t.FullName.Contains(str)) export = false; } if (export) { if (Generate(t, path)) exports.Add(t); } } GenerateBind(exports, "BindUnityUI", 1,path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate UI interface finished"); } [MenuItem("SLua/Unity/Clear Uinty UI")] static public void ClearUnity() { clear(new string[] { Path + "Unity" }); Debug.Log("Clear Unity & UI complete."); } static public bool IsObsolete(MemberInfo t) { return t.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length > 0; } [MenuItem("SLua/Custom/Make")] static public void Custom() { if (IsCompiling) { return; } List<Type> exports = new List<Type>(); string path = Path + "Custom/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } ExportGenericDelegate fun = (Type t, string ns) => { if (Generate(t, ns, path)) exports.Add(t); }; // export self-dll Assembly assembly = Assembly.Load("Assembly-CSharp"); Type[] types = assembly.GetExportedTypes(); foreach (Type t in types) { if (t.GetCustomAttributes(typeof(CustomLuaClassAttribute), false).Length > 0) { fun(t, null); } } CustomExport.OnAddCustomClass(fun); GenerateBind(exports, "BindCustom", 3,path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate custom interface finished"); } [MenuItem("SLua/3rdDll/Make")] static public void Generate3rdDll() { if (IsCompiling) { return; } List<Type> cust = new List<Type>(); Assembly assembly = Assembly.Load("Assembly-CSharp"); Type[] types = assembly.GetExportedTypes(); List<string> assemblyList = new List<string>(); CustomExport.OnAddCustomAssembly(ref assemblyList); foreach (string assemblyItem in assemblyList) { assembly = Assembly.Load(assemblyItem); types = assembly.GetExportedTypes(); foreach (Type t in types) { cust.Add(t); } } if (cust.Count > 0) { List<Type> exports = new List<Type>(); string path = Path + "Dll/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } foreach (Type t in cust) { if (Generate(t,path)) exports.Add(t); } GenerateBind(exports, "BindDll", 2, path); if(autoRefresh) AssetDatabase.Refresh(); Debug.Log("Generate 3rdDll interface finished"); } } [MenuItem("SLua/3rdDll/Clear")] static public void Clear3rdDll() { clear(new string[] { Path + "Dll" }); Debug.Log("Clear AssemblyDll complete."); } [MenuItem("SLua/Custom/Clear")] static public void ClearCustom() { clear(new string[] { Path + "Custom" }); Debug.Log("Clear custom complete."); } [MenuItem("SLua/All/Clear")] static public void ClearALL() { clear(new string[] { Path.Substring(0, Path.Length - 1) }); Debug.Log("Clear all complete."); } static void clear(string[] paths) { try { foreach (string path in paths) { System.IO.Directory.Delete(path, true); } } catch { } AssetDatabase.Refresh(); } static bool Generate(Type t, string path) { return Generate(t, null, path); } static bool Generate(Type t, string ns, string path) { if (t.IsInterface) return false; CodeGenerator cg = new CodeGenerator(); cg.givenNamespace = ns; cg.path = path; return cg.Generate(t); } static void GenerateBind(List<Type> list, string name, int order,string path) { CodeGenerator cg = new CodeGenerator(); cg.path = path; cg.GenerateBind(list, name, order); } } class CodeGenerator { static List<string> memberFilter = new List<string> { "AnimationClip.averageDuration", "AnimationClip.averageAngularSpeed", "AnimationClip.averageSpeed", "AnimationClip.apparentSpeed", "AnimationClip.isLooping", "AnimationClip.isAnimatorMotion", "AnimationClip.isHumanMotion", "AnimatorOverrideController.PerformOverrideClipListCleanup", "Caching.SetNoBackupFlag", "Caching.ResetNoBackupFlag", "Light.areaSize", "Security.GetChainOfTrustValue", "Texture2D.alphaIsTransparency", "WWW.movie", "WebCamTexture.MarkNonReadable", "WebCamTexture.isReadable", // i don't why below 2 functions missed in iOS platform "Graphic.OnRebuildRequested", "Text.OnRebuildRequested", // il2cpp not exixts "Application.ExternalEval", "GameObject.networkView", "Component.networkView", // unity5 "AnimatorControllerParameter.name", "Input.IsJoystickPreconfigured", "Resources.LoadAssetAtPath", #if UNITY_4_6 "Motion.ValidateIfRetargetable", "Motion.averageDuration", "Motion.averageAngularSpeed", "Motion.averageSpeed", "Motion.apparentSpeed", "Motion.isLooping", "Motion.isAnimatorMotion", "Motion.isHumanMotion", #endif }; HashSet<string> funcname = new HashSet<string>(); Dictionary<string, bool> directfunc = new Dictionary<string, bool>(); public string givenNamespace; public string path; class PropPair { public string get = "null"; public string set = "null"; public bool isInstance = true; } Dictionary<string, PropPair> propname = new Dictionary<string, PropPair>(); int indent = 0; public void GenerateBind(List<Type> list, string name, int order) { HashSet<Type> exported = new HashSet<Type>(); string f = path + name + ".cs"; StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); Write(file, "using System;"); Write(file, "namespace SLua {"); Write(file, "[LuaBinder({0})]", order); Write(file, "public class {0} {{", name); Write(file, "public static void Bind(IntPtr l) {"); foreach (Type t in list) { WriteBindType(file, t, list, exported); } Write(file, "}"); Write(file, "}"); Write(file, "}"); file.Close(); } void WriteBindType(StreamWriter file, Type t, List<Type> exported, HashSet<Type> binded) { if (t == null || binded.Contains(t) || !exported.Contains(t)) return; WriteBindType(file, t.BaseType, exported, binded); Write(file, "{0}.reg(l);", ExportName(t), binded); binded.Add(t); } public bool Generate(Type t) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!t.IsGenericTypeDefinition && (!IsObsolete(t) && t != typeof(YieldInstruction) && t != typeof(Coroutine)) || (t.BaseType != null && t.BaseType == typeof(System.MulticastDelegate))) { if (t.IsEnum) { StreamWriter file = Begin(t); WriteHead(t, file); RegEnumFunction(t, file); End(file); } else if (t.BaseType == typeof(System.MulticastDelegate)) { string f; if (t.IsGenericType) { if (t.ContainsGenericParameters) return false; f = path + string.Format("Lua{0}_{1}.cs", _Name(GenericBaseName(t)), _Name(GenericName(t))); } else { f = path + "LuaDelegate_" + _Name(t.FullName) + ".cs"; } StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); WriteDelegate(t, file); file.Close(); return false; } else { funcname.Clear(); propname.Clear(); directfunc.Clear(); StreamWriter file = Begin(t); WriteHead(t, file); WriteConstructor(t, file); WriteFunction(t, file); WriteFunction(t, file, true); WriteField(t, file); RegFunction(t, file); End(file); if (t.BaseType != null && t.BaseType.Name == "UnityEvent`1") { string f = path + "LuaUnityEvent_" + _Name(GenericName(t.BaseType)) + ".cs"; file = new StreamWriter(f, false, Encoding.UTF8); WriteEvent(t, file); file.Close(); } } return true; } return false; } void WriteDelegate(Type t, StreamWriter file) { string temp = @" using System; using System.Collections.Generic; using LuaInterface; using UnityEngine; namespace SLua { public partial class LuaDelegation : LuaObject { static internal int checkDelegate(IntPtr l,int p,out $FN ua) { int op = extractFunction(l,p); if(LuaDLL.lua_isnil(l,p)) { ua=null; return op; } else if (LuaDLL.lua_isuserdata(l, p)==1) { ua = ($FN)checkObj(l, p); return op; } LuaDelegate ld; checkType(l, -1, out ld); if(ld.d!=null) { ua = ($FN)ld.d; return op; } LuaDLL.lua_pop(l,1); l = LuaState.get(l).L; ua = ($ARGS) => { int error = pushTry(l); "; temp = temp.Replace("$TN", t.Name); temp = temp.Replace("$FN", SimpleType(t)); MethodInfo mi = t.GetMethod("Invoke"); List<int> outindex = new List<int>(); List<int> refindex = new List<int>(); temp = temp.Replace("$ARGS", ArgsList(mi, ref outindex, ref refindex)); Write(file, temp); this.indent = 4; for (int n = 0; n < mi.GetParameters().Length; n++) { if (!outindex.Contains(n)) Write(file, "pushValue(l,a{0});", n + 1); } Write(file, "ld.pcall({0}, error);", mi.GetParameters().Length - outindex.Count); if (mi.ReturnType != typeof(void)) WriteValueCheck(file, mi.ReturnType, 1, "ret", "error+"); foreach (int i in outindex) { string a = string.Format("a{0}", i + 1); WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + 1, a, "error+"); } foreach (int i in refindex) { string a = string.Format("a{0}", i + 1); WriteCheckType(file, mi.GetParameters()[i].ParameterType, i + 1, a, "error+"); } Write(file, "LuaDLL.lua_settop(l, error-1);"); if (mi.ReturnType != typeof(void)) Write(file, "return ret;"); Write(file, "};"); Write(file, "ld.d=ua;"); Write(file, "return op;"); Write(file, "}"); Write(file, "}"); Write(file, "}"); } string ArgsList(MethodInfo m, ref List<int> outindex, ref List<int> refindex) { string str = ""; ParameterInfo[] pars = m.GetParameters(); for (int n = 0; n < pars.Length; n++) { string t = SimpleType(pars[n].ParameterType); ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef && p.IsOut) { str += string.Format("out {0} a{1}", t, n + 1); outindex.Add(n); } else if (p.ParameterType.IsByRef) { str += string.Format("ref {0} a{1}", t, n + 1); refindex.Add(n); } else str += string.Format("{0} a{1}", t, n + 1); if (n < pars.Length - 1) str += ","; } return str; } void tryMake(Type t) { if (t.BaseType == typeof(System.MulticastDelegate)) { CodeGenerator cg = new CodeGenerator(); cg.path = this.path; cg.Generate(t); } } void WriteEvent(Type t, StreamWriter file) { string temp = @" using System; using System.Collections.Generic; using LuaInterface; using UnityEngine; using UnityEngine.EventSystems; namespace SLua { public class LuaUnityEvent_$CLS : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int AddListener(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); UnityEngine.Events.UnityAction<$GN> a1; checkType(l, 2, out a1); self.AddListener(a1); return 0; } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RemoveListener(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); UnityEngine.Events.UnityAction<$GN> a1; checkType(l, 2, out a1); self.RemoveListener(a1); return 0; } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Invoke(IntPtr l) { try { UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l); $GN o; checkType(l,2,out o); self.Invoke(o); return 0; } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } static public void reg(IntPtr l) { getTypeTable(l, typeof(LuaUnityEvent_$CLS).FullName); addMember(l, AddListener); addMember(l, RemoveListener); addMember(l, Invoke); createTypeMetatable(l, null, typeof(LuaUnityEvent_$CLS), typeof(UnityEngine.Events.UnityEventBase)); } static bool checkType(IntPtr l,int p,out UnityEngine.Events.UnityAction<$GN> ua) { LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TFUNCTION); LuaDelegate ld; checkType(l, p, out ld); if (ld.d != null) { ua = (UnityEngine.Events.UnityAction<$GN>)ld.d; return true; } l = LuaState.get(l).L; ua = ($GN v) => { int error = pushTry(l); pushValue(l, v); ld.pcall(1, error); LuaDLL.lua_settop(l,error - 1); }; ld.d = ua; return true; } } }"; temp = temp.Replace("$CLS", _Name(GenericName(t.BaseType))); temp = temp.Replace("$FNAME", FullName(t)); temp = temp.Replace("$GN", GenericName(t.BaseType)); Write(file, temp); } void RegEnumFunction(Type t, StreamWriter file) { // Write export function Write(file, "static public void reg(IntPtr l) {"); Write(file, "getEnumTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace); FieldInfo[] fields = t.GetFields(); foreach (FieldInfo f in fields) { if (f.Name == "value__") continue; Write(file, "addMember(l,{0},\"{1}\");", (int)f.GetValue(null), f.Name); } Write(file, "LuaDLL.lua_pop(l, 1);"); Write(file, "}"); } StreamWriter Begin(Type t) { string clsname = ExportName(t); string f = path + clsname + ".cs"; StreamWriter file = new StreamWriter(f, false, Encoding.UTF8); return file; } private void End(StreamWriter file) { Write(file, "}"); file.Flush(); file.Close(); } private void WriteHead(Type t, StreamWriter file) { Write(file, "using UnityEngine;"); Write(file, "using System;"); Write(file, "using LuaInterface;"); Write(file, "using SLua;"); Write(file, "using System.Collections.Generic;"); Write(file, "public class {0} : LuaObject {{", ExportName(t)); } private void WriteFunction(Type t, StreamWriter file, bool writeStatic = false) { BindingFlags bf = BindingFlags.Public | BindingFlags.DeclaredOnly; if (writeStatic) bf |= BindingFlags.Static; else bf |= BindingFlags.Instance; MethodInfo[] members = t.GetMethods(bf); foreach (MethodInfo mi in members) { bool instanceFunc; if (writeStatic && isPInvoke(mi, out instanceFunc)) { directfunc.Add(t.FullName + "." + mi.Name, instanceFunc); continue; } string fn = writeStatic ? staticName(mi.Name) : mi.Name; if (mi.MemberType == MemberTypes.Method && !IsObsolete(mi) && !DontExport(mi) && !funcname.Contains(fn) && isUsefullMethod(mi) && !MemberInFilter(t, mi)) { WriteFunctionDec(file, fn); WriteFunctionImpl(file, mi, t, bf); funcname.Add(fn); } } } bool isPInvoke(MethodInfo mi, out bool instanceFunc) { object[] attrs = mi.GetCustomAttributes(typeof(MonoPInvokeCallbackAttribute), false); if (attrs.Length > 0) { instanceFunc = mi.GetCustomAttributes(typeof(StaticExportAttribute), false).Length == 0; return true; } instanceFunc = true; return false; } string staticName(string name) { if (name.StartsWith("op_")) return name; return name + "_s"; } bool MemberInFilter(Type t, MemberInfo mi) { return memberFilter.Contains(t.Name + "." + mi.Name); } bool IsObsolete(MemberInfo mi) { return LuaCodeGen.IsObsolete(mi); } void RegFunction(Type t, StreamWriter file) { // Write export function Write(file, "static public void reg(IntPtr l) {"); if (t.BaseType != null && t.BaseType.Name.Contains("UnityEvent`")) { Write(file, "LuaUnityEvent_{1}.reg(l);", FullName(t), _Name((GenericName(t.BaseType)))); } Write(file, "getTypeTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace); foreach (string f in funcname) { Write(file, "addMember(l,{0});", f); } foreach (string f in directfunc.Keys) { bool instance = directfunc[f]; Write(file, "addMember(l,{0},{1});", f, instance ? "true" : "false"); } foreach (string f in propname.Keys) { PropPair pp = propname[f]; Write(file, "addMember(l,\"{0}\",{1},{2},{3});", f, pp.get, pp.set, pp.isInstance ? "true" : "false"); } if (t.BaseType != null && !CutBase(t.BaseType)) { if (t.BaseType.Name.Contains("UnityEvent`1")) Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof(LuaUnityEvent_{1}));", TypeDecl(t), _Name(GenericName(t.BaseType)), constructorOrNot(t)); else Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof({1}));", TypeDecl(t), TypeDecl(t.BaseType), constructorOrNot(t)); } else Write(file, "createTypeMetatable(l,{1}, typeof({0}));", TypeDecl(t), constructorOrNot(t)); Write(file, "}"); } string constructorOrNot(Type t) { ConstructorInfo[] cons = GetValidConstructor(t); if (cons.Length > 0 || t.IsValueType) return "constructor"; return "null"; } bool CutBase(Type t) { if (t.FullName.StartsWith("System.Object")) return true; return false; } void WriteSet(StreamWriter file, Type t, string cls, string fn, bool isstatic = false) { if (t.BaseType == typeof(MulticastDelegate)) { if (isstatic) { Write(file, "if(op==0) {0}.{1}=v;", cls, fn); Write(file, "else if(op==1) {0}.{1}+=v;", cls, fn); Write(file, "else if(op==2) {0}.{1}-=v;", cls, fn); } else { Write(file, "if(op==0) self.{0}=v;", fn); Write(file, "else if(op==1) self.{0}+=v;", fn); Write(file, "else if(op==2) self.{0}-=v;", fn); } } else { if (isstatic) { Write(file, "{0}.{1}=v;", cls, fn); } else { Write(file, "self.{0}=v;", fn); } } } private void WriteField(Type t, StreamWriter file) { // Write field set/get FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo fi in fields) { if (DontExport(fi) || IsObsolete(fi)) continue; PropPair pp = new PropPair(); pp.isInstance = !fi.IsStatic; if (fi.FieldType.BaseType != typeof(MulticastDelegate)) { WriteFunctionAttr(file); Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.IsStatic) { WritePushValue(fi.FieldType, file, string.Format("{0}.{1}", TypeDecl(t), fi.Name)); } else { WriteCheckSelf(file, t); WritePushValue(fi.FieldType, file, string.Format("self.{0}", fi.Name)); } Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); pp.get = "get_" + fi.Name; } if (!fi.IsLiteral && !fi.IsInitOnly) { WriteFunctionAttr(file); Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.IsStatic) { Write(file, "{0} v;", TypeDecl(fi.FieldType)); WriteCheckType(file, fi.FieldType, 2); WriteSet(file, fi.FieldType, TypeDecl(t), fi.Name, true); } else { WriteCheckSelf(file, t); Write(file, "{0} v;", TypeDecl(fi.FieldType)); WriteCheckType(file, fi.FieldType, 2); WriteSet(file, fi.FieldType, t.FullName, fi.Name); } if (t.IsValueType && !fi.IsStatic) Write(file, "setBack(l,self);"); Write(file, "return 0;"); WriteCatchExecption(file); Write(file, "}"); pp.set = "set_" + fi.Name; } propname.Add(fi.Name, pp); tryMake(fi.FieldType); } //for this[] List<PropertyInfo> getter = new List<PropertyInfo>(); List<PropertyInfo> setter = new List<PropertyInfo>(); // Write property set/get PropertyInfo[] props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (PropertyInfo fi in props) { //if (fi.Name == "Item" || IsObsolete(fi) || MemberInFilter(t,fi) || DontExport(fi)) if (IsObsolete(fi) || MemberInFilter(t, fi) || DontExport(fi)) continue; if (fi.Name == "Item" || (t.Name == "String" && fi.Name == "Chars")) // for string[] { //for this[] if (!fi.GetGetMethod().IsStatic && fi.GetIndexParameters().Length == 1) { if (fi.CanRead && !IsNotSupport(fi.PropertyType)) getter.Add(fi); if (fi.CanWrite && fi.GetSetMethod() != null) setter.Add(fi); } continue; } PropPair pp = new PropPair(); bool isInstance = true; if (fi.CanRead && fi.GetGetMethod() != null) { if (!IsNotSupport(fi.PropertyType)) { WriteFunctionAttr(file); Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.GetGetMethod().IsStatic) { isInstance = false; WritePushValue(fi.PropertyType, file, string.Format("{0}.{1}", TypeDecl(t), fi.Name)); } else { WriteCheckSelf(file, t); WritePushValue(fi.PropertyType, file, string.Format("self.{0}", fi.Name)); } Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); pp.get = "get_" + fi.Name; } } if (fi.CanWrite && fi.GetSetMethod() != null) { WriteFunctionAttr(file); Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name); WriteTry(file); if (fi.GetSetMethod().IsStatic) { WriteValueCheck(file, fi.PropertyType, 2); WriteSet(file, fi.PropertyType, TypeDecl(t), fi.Name, true); isInstance = false; } else { WriteCheckSelf(file, t); WriteValueCheck(file, fi.PropertyType, 2); WriteSet(file, fi.PropertyType, TypeDecl(t), fi.Name); } if (t.IsValueType) Write(file, "setBack(l,self);"); Write(file, "return 0;"); WriteCatchExecption(file); Write(file, "}"); pp.set = "set_" + fi.Name; } pp.isInstance = isInstance; propname.Add(fi.Name, pp); tryMake(fi.PropertyType); } //for this[] WriteItemFunc(t, file, getter, setter); } void WriteItemFunc(Type t, StreamWriter file, List<PropertyInfo> getter, List<PropertyInfo> setter) { //Write property this[] set/get if (getter.Count > 0) { //get bool first_get = true; WriteFunctionAttr(file); Write(file, "static public int getItem(IntPtr l) {"); WriteTry(file); WriteCheckSelf(file, t); if (getter.Count == 1) { PropertyInfo _get = getter[0]; ParameterInfo[] infos = _get.GetIndexParameters(); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); Write(file, "var ret = self[v];"); WritePushValue(_get.PropertyType, file, "ret"); Write(file, "return 1;"); } else { Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);"); for (int i = 0; i < getter.Count; i++) { PropertyInfo fii = getter[i]; ParameterInfo[] infos = fii.GetIndexParameters(); Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_get ? "if" : "else if", infos[0].ParameterType); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); Write(file, "var ret = self[v];"); WritePushValue(fii.PropertyType, file, "ret"); Write(file, "return 1;"); Write(file, "}"); first_get = false; } Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");"); Write(file, "return 0;"); } WriteCatchExecption(file); Write(file, "}"); funcname.Add("getItem"); } if (setter.Count > 0) { bool first_set = true; WriteFunctionAttr(file); Write(file, "static public int setItem(IntPtr l) {"); WriteTry(file); WriteCheckSelf(file, t); if (setter.Count == 1) { PropertyInfo _set = setter[0]; ParameterInfo[] infos = _set.GetIndexParameters(); WriteValueCheck(file, infos[0].ParameterType, 2); WriteValueCheck(file, _set.PropertyType, 3, "c"); Write(file, "self[v]=c;"); } else { Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);"); for (int i = 0; i < setter.Count; i++) { PropertyInfo fii = setter[i]; if (t.BaseType != typeof(MulticastDelegate)) { ParameterInfo[] infos = fii.GetIndexParameters(); Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_set ? "if" : "else if", infos[0].ParameterType); WriteValueCheck(file, infos[0].ParameterType, 2, "v"); WriteValueCheck(file, fii.PropertyType, 3, "c"); Write(file, "self[v]=c;"); Write(file, "return 0;"); Write(file, "}"); first_set = false; } if (t.IsValueType) Write(file, "setBack(l,self);"); } Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");"); } Write(file, "return 0;"); WriteCatchExecption(file); Write(file, "}"); funcname.Add("setItem"); } } void WriteTry(StreamWriter file) { #if _LUADEBUG Write(file, "try {"); #endif } void WriteCatchExecption(StreamWriter file) { #if _LUADEBUG Write(file, "}"); Write(file, "catch(Exception e) {"); Write(file, "LuaDLL.luaL_error(l, e.ToString());"); Write(file, "return 0;"); Write(file, "}"); #endif } void WriteCheckType(StreamWriter file, Type t, int n, string v = "v", string nprefix = "") { if (t.IsEnum) Write(file, "checkEnum(l,{2}{0},out {1});", n, v, nprefix); else if (t.BaseType == typeof(System.MulticastDelegate)) Write(file, "int op=LuaDelegation.checkDelegate(l,{2}{0},out {1});", n, v, nprefix); else if (t.IsValueType && !IsBaseType(t)) Write(file, "checkValueType(l,{2}{0},out {1});", n, v, nprefix); else Write(file, "checkType(l,{2}{0},out {1});", n, v, nprefix); } void WriteValueCheck(StreamWriter file, Type t, int n, string v = "v", string nprefix = "") { Write(file, "{0} {1};", SimpleType(t), v); WriteCheckType(file, t, n, v, nprefix); } private void WriteFunctionAttr(StreamWriter file) { Write(file, "[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]"); } ConstructorInfo[] GetValidConstructor(Type t) { List<ConstructorInfo> ret = new List<ConstructorInfo>(); if (t.GetConstructor(Type.EmptyTypes) == null && t.IsAbstract && t.IsSealed) return ret.ToArray(); if (t.BaseType != null && t.BaseType.Name == "MonoBehaviour") return ret.ToArray(); ConstructorInfo[] cons = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public); foreach (ConstructorInfo ci in cons) { if (!IsObsolete(ci) && !DontExport(ci) && !ContainUnsafe(ci)) ret.Add(ci); } return ret.ToArray(); } bool ContainUnsafe(MethodBase mi) { foreach (ParameterInfo p in mi.GetParameters()) { if (p.ParameterType.FullName.Contains("*")) return true; } return false; } bool DontExport(MemberInfo mi) { return mi.GetCustomAttributes(typeof(DoNotToLuaAttribute), false).Length > 0; } private void WriteConstructor(Type t, StreamWriter file) { ConstructorInfo[] cons = GetValidConstructor(t); if (cons.Length > 0) { WriteFunctionAttr(file); Write(file, "static public int constructor(IntPtr l) {"); WriteTry(file); if (cons.Length > 1) Write(file, "int argc = LuaDLL.lua_gettop(l);"); Write(file, "{0} o;", TypeDecl(t)); bool first = true; for (int n = 0; n < cons.Length; n++) { ConstructorInfo ci = cons[n]; ParameterInfo[] pars = ci.GetParameters(); if (cons.Length > 1) { if (isUniqueArgsCount(cons, ci)) Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", ci.GetParameters().Length + 1); else Write(file, "{0}(matchType(l,argc,2{1})){{", first ? "if" : "else if", TypeDecl(pars)); } for (int k = 0; k < pars.Length; k++) { ParameterInfo p = pars[k]; bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0; CheckArgument(file, p.ParameterType, k, 2, p.IsOut, hasParams); } Write(file, "o=new {0}({1});", TypeDecl(t), FuncCall(ci)); if (t.Name == "String") // if export system.string, push string as ud not lua string Write(file, "pushObject(l,o);"); else Write(file, "pushValue(l,o);"); Write(file, "return 1;"); if (cons.Length == 1) WriteCatchExecption(file); Write(file, "}"); first = false; } if (cons.Length > 1) { Write(file, "LuaDLL.luaL_error(l,\"New object failed.\");"); Write(file, "return 0;"); WriteCatchExecption(file); Write(file, "}"); } } else if (t.IsValueType) // default constructor { WriteFunctionAttr(file); Write(file, "static public int constructor(IntPtr l) {"); WriteTry(file); Write(file, "{0} o;", FullName(t)); Write(file, "o=new {0}();", FullName(t)); Write(file, "pushValue(l,o);"); Write(file, "return 1;"); WriteCatchExecption(file); Write(file, "}"); } } bool IsNotSupport(Type t) { if (t.IsSubclassOf(typeof(Delegate))) return true; return false; } string[] prefix = new string[] { "System.Collections.Generic" }; string RemoveRef(string s, bool removearray = true) { if (s.EndsWith("&")) s = s.Substring(0, s.Length - 1); if (s.EndsWith("[]") && removearray) s = s.Substring(0, s.Length - 2); if (s.StartsWith(prefix[0])) s = s.Substring(prefix[0].Length + 1, s.Length - prefix[0].Length - 1); s = s.Replace("+", "."); if (s.Contains("`")) { string regstr = @"`\d"; Regex r = new Regex(regstr, RegexOptions.None); s = r.Replace(s, ""); s = s.Replace("[", "<"); s = s.Replace("]", ">"); } return s; } string GenericBaseName(Type t) { string n = t.FullName; if (n.IndexOf('[') > 0) { n = n.Substring(0, n.IndexOf('[')); } return n.Replace("+", "."); } string GenericName(Type t) { try { Type[] tt = t.GetGenericArguments(); string ret = ""; for (int n = 0; n < tt.Length; n++) { string dt = SimpleType(tt[n]); ret += dt; if (n < tt.Length - 1) ret += "_"; } return ret; } catch (Exception e) { Debug.Log(e.ToString()); return ""; } } string _Name(string n) { string ret = ""; for (int i = 0; i < n.Length; i++) { if (char.IsLetterOrDigit(n[i])) ret += n[i]; else ret += "_"; } return ret; } string TypeDecl(ParameterInfo[] pars) { string ret = ""; for (int n = 0; n < pars.Length; n++) { ret += ",typeof("; if (pars[n].IsOut) ret += "LuaOut"; else ret += SimpleType(pars[n].ParameterType); ret += ")"; } return ret; } bool isUsefullMethod(MethodInfo method) { if (method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" && method.Name != "ToString" && method.Name != "Clone" && method.Name != "GetEnumerator" && method.Name != "CopyTo" && method.Name != "op_Implicit" && !method.Name.StartsWith("get_", StringComparison.Ordinal) && !method.Name.StartsWith("set_", StringComparison.Ordinal) && !method.Name.StartsWith("add_", StringComparison.Ordinal) && !IsObsolete(method) && !method.IsGenericMethod && //!method.Name.StartsWith("op_", StringComparison.Ordinal) && !method.Name.StartsWith("remove_", StringComparison.Ordinal)) { return true; } return false; } void WriteFunctionDec(StreamWriter file, string name) { WriteFunctionAttr(file); Write(file, "static public int {0}(IntPtr l) {{", name); } MethodBase[] GetMethods(Type t, string name, BindingFlags bf) { List<MethodBase> methods = new List<MethodBase>(); MemberInfo[] cons = t.GetMember(name, bf); foreach (MemberInfo m in cons) { if (m.MemberType == MemberTypes.Method && !IsObsolete(m) && !DontExport(m) && isUsefullMethod((MethodInfo)m)) methods.Add((MethodBase)m); } methods.Sort((a, b) => { return a.GetParameters().Length - b.GetParameters().Length; }); return methods.ToArray(); } void WriteFunctionImpl(StreamWriter file, MethodInfo m, Type t, BindingFlags bf) { WriteTry(file); MethodBase[] cons = GetMethods(t, m.Name, bf); if (cons.Length == 1) // no override function { if (isUsefullMethod(m) && !m.ReturnType.ContainsGenericParameters && !m.ContainsGenericParameters) // don't support generic method WriteFunctionCall(m, file, t); else { Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");"); Write(file, "return 0;"); } } else // 2 or more override function { Write(file, "int argc = LuaDLL.lua_gettop(l);"); bool first = true; for (int n = 0; n < cons.Length; n++) { if (cons[n].MemberType == MemberTypes.Method) { MethodInfo mi = cons[n] as MethodInfo; ParameterInfo[] pars = mi.GetParameters(); if (isUsefullMethod(mi) && !mi.ReturnType.ContainsGenericParameters /*&& !ContainGeneric(pars)*/) // don't support generic method { if (isUniqueArgsCount(cons, mi)) Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", mi.IsStatic ? mi.GetParameters().Length : mi.GetParameters().Length + 1); else Write(file, "{0}(matchType(l,argc,{1}{2})){{", first ? "if" : "else if", mi.IsStatic ? 1 : 2, TypeDecl(pars)); WriteFunctionCall(mi, file, t); Write(file, "}"); first = false; } } } Write(file, "LuaDLL.luaL_error(l,\"No matched override function to call\");"); Write(file, "return 0;"); } WriteCatchExecption(file); Write(file, "}"); } bool isUniqueArgsCount(MethodBase[] cons, MethodBase mi) { foreach (MethodBase member in cons) { MethodBase m = (MethodBase)member; if (m != mi && mi.GetParameters().Length == m.GetParameters().Length) return false; } return true; } bool ContainGeneric(ParameterInfo[] pars) { foreach (ParameterInfo p in pars) { if (p.ParameterType.IsGenericType || p.ParameterType.IsGenericParameter || p.ParameterType.IsGenericTypeDefinition) return true; } return false; } void WriteCheckSelf(StreamWriter file, Type t) { if (t.IsValueType) { Write(file, "{0} self;", TypeDecl(t)); if(IsBaseType(t)) Write(file, "checkType(l,1,out self);"); else Write(file, "checkValueType(l,1,out self);"); } else Write(file, "{0} self=({0})checkSelf(l);", TypeDecl(t)); } private void WriteFunctionCall(MethodInfo m, StreamWriter file, Type t) { bool hasref = false; ParameterInfo[] pars = m.GetParameters(); int argIndex = 1; if (!m.IsStatic) { WriteCheckSelf(file, t); argIndex++; } for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; string pn = p.ParameterType.Name; if (pn.EndsWith("&")) { hasref = true; } bool hasParams = p.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0; CheckArgument(file, p.ParameterType, n, argIndex, p.IsOut, hasParams); } string ret = ""; if (m.ReturnType != typeof(void)) { ret = "var ret="; } if (m.IsStatic) { if (m.Name == "op_Multiply") Write(file, "{0}a1*a2;", ret); else if (m.Name == "op_Subtraction") Write(file, "{0}a1-a2;", ret); else if (m.Name == "op_Addition") Write(file, "{0}a1+a2;", ret); else if (m.Name == "op_Division") Write(file, "{0}a1/a2;", ret); else if (m.Name == "op_UnaryNegation") Write(file, "{0}-a1;", ret); else if (m.Name == "op_Equality") Write(file, "{0}(a1==a2);", ret); else if (m.Name == "op_Inequality") Write(file, "{0}(a1!=a2);", ret); else if (m.Name == "op_LessThan") Write(file, "{0}(a1<a2);", ret); else if (m.Name == "op_GreaterThan") Write(file, "{0}(a2<a1);", ret); else if (m.Name == "op_LessThanOrEqual") Write(file, "{0}(a1<=a2);", ret); else if (m.Name == "op_GreaterThanOrEqual") Write(file, "{0}(a2<=a1);", ret); else Write(file, "{3}{2}.{0}({1});", m.Name, FuncCall(m), TypeDecl(t), ret); } else Write(file, "{2}self.{0}({1});", m.Name, FuncCall(m), ret); int retcount = 0; if (m.ReturnType != typeof(void)) { WritePushValue(m.ReturnType, file); retcount = 1; } // push out/ref value for return value if (hasref) { for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef) { WritePushValue(p.ParameterType, file, string.Format("a{0}", n + 1)); retcount++; } } } if (t.IsValueType && m.ReturnType == typeof(void) && !m.IsStatic) Write(file, "setBack(l,self);"); Write(file, "return {0};", retcount); } string SimpleType_(Type t) { string tn = t.Name; switch (tn) { case "Single": return "float"; case "String": return "string"; case "Double": return "double"; case "Boolean": return "bool"; case "Int32": return "int"; case "Object": return FullName(t); default: tn = TypeDecl(t); tn = tn.Replace("System.Collections.Generic.", ""); tn = tn.Replace("System.Object", "object"); return tn; } } string SimpleType(Type t) { string ret = SimpleType_(t); return ret; } void WritePushValue(Type t, StreamWriter file) { if (t.IsEnum) Write(file, "pushEnum(l,(int)ret);"); else Write(file, "pushValue(l,ret);"); } void WritePushValue(Type t, StreamWriter file, string ret) { if (t.IsEnum) Write(file, "pushEnum(l,(int){0});", ret); else Write(file, "pushValue(l,{0});", ret); } void Write(StreamWriter file, string fmt, params object[] args) { if (fmt.StartsWith("}")) indent--; for (int n = 0; n < indent; n++) file.Write("\t"); if (args.Length == 0) file.WriteLine(fmt); else { string line = string.Format(fmt, args); file.WriteLine(line); } if (fmt.EndsWith("{")) indent++; } private void CheckArgument(StreamWriter file, Type t, int n, int argstart, bool isout, bool isparams) { Write(file, "{0} a{1};", TypeDecl(t), n + 1); if (!isout) { if (t.IsEnum) Write(file, "checkEnum(l,{0},out a{1});", n + argstart, n + 1); else if (t.BaseType == typeof(System.MulticastDelegate)) { tryMake(t); Write(file, "LuaDelegation.checkDelegate(l,{0},out a{1});", n + argstart, n + 1); } else if (isparams) { if(t.GetElementType().IsValueType && !IsBaseType(t.GetElementType())) Write(file, "checkValueParams(l,{0},out a{1});", n + argstart, n + 1); else Write(file, "checkParams(l,{0},out a{1});", n + argstart, n + 1); } else if (t.IsValueType && !IsBaseType(t)) Write(file, "checkValueType(l,{0},out a{1});", n + argstart, n + 1); else Write(file, "checkType(l,{0},out a{1});", n + argstart, n + 1); } } bool IsBaseType(Type t) { return t.IsPrimitive || t == typeof(Color) || t == typeof(Vector2) || t == typeof(Vector3) || t == typeof(Vector4) || t == typeof(Quaternion); } string FullName(string str) { if (str == null) { throw new NullReferenceException(); } return RemoveRef(str.Replace("+", ".")); } string TypeDecl(Type t) { if (t.IsGenericType) { string ret = GenericBaseName(t); string gs = ""; gs += "<"; Type[] types = t.GetGenericArguments(); for (int n = 0; n < types.Length; n++) { gs += TypeDecl(types[n]); if (n < types.Length - 1) gs += ","; } gs += ">"; ret = Regex.Replace(ret, @"`\d", gs); return ret; } if (t.IsArray) { return TypeDecl(t.GetElementType()) + "[]"; } else return RemoveRef(t.ToString(), false); } string ExportName(Type t) { if (t.IsGenericType) { return string.Format("Lua_{0}_{1}", _Name(GenericBaseName(t)), _Name(GenericName(t))); } else { string name = RemoveRef(t.FullName, true); name = "Lua_" + name; return name.Replace(".", "_"); } } string FullName(Type t) { if (t.FullName == null) { Debug.Log(t.Name); return t.Name; } return FullName(t.FullName); } string FuncCall(MethodBase m) { string str = ""; ParameterInfo[] pars = m.GetParameters(); for (int n = 0; n < pars.Length; n++) { ParameterInfo p = pars[n]; if (p.ParameterType.IsByRef && p.IsOut) str += string.Format("out a{0}", n + 1); else if (p.ParameterType.IsByRef) str += string.Format("ref a{0}", n + 1); else str += string.Format("a{0}", n + 1); if (n < pars.Length - 1) str += ","; } return str; } } }
using System; using System.Data; using DevOffice.Common.Models; using Orchard.ContentManagement; using Orchard.ContentManagement.MetaData; using Orchard.Core.Common.Fields; using Orchard.Core.Contents.Extensions; using Orchard.Data.Migration; using Orchard.Widgets.Models; using Orchard.Widgets.Services; using Provoke.Highlights.Models; using Provoke.Highlights.Models.Widgets; using System.Linq; namespace Provoke.Highlights { public class DatabaseMigrations : DataMigrationImpl { public int Create() { #region Create Scenario, Task, and Step custom content parts SchemaBuilder.CreateTable("ScenarioRecord", table => table .ContentPartRecord() // This will add a column 'Id', set it as the primary key and be an identity. .Column<string>("Title") .Column<string>("Description", column => column.Unlimited()) ); SchemaBuilder.CreateTable("TaskRecord", table => table .Column<int>("Id", column => column.PrimaryKey().Identity()) .Column<int>("ScenarioRecord_Id") .Column<string>("Description", column => column.Unlimited()) .Column<int>("SortOrder") ); SchemaBuilder.CreateTable("StepRecord", table => table .Column<int>("Id", column => column.PrimaryKey().Identity()) .Column<int>("TaskRecord_Id") .Column<string>("Title") .Column<string>("Description", column => column.Unlimited()) .Column<int>("SortOrder") .Column<double>("TopPosition") .Column<double>("LeftPosition") .Column<string>("Anchor") .Column<string>("Image") ); ContentDefinitionManager.AlterPartDefinition( typeof(ScenarioPart).Name, builder => builder.Attachable() ); #endregion #region Create Highlight content type ContentDefinitionManager.AlterPartDefinition("HighlightPart", builder => builder .WithField("Version", definitionBuilder => definitionBuilder .OfType("NumericField") .WithDisplayName("Version") .WithSetting("NumericFieldSettings.Hint", "The current version of the highlight")) ); ContentDefinitionManager.AlterTypeDefinition("Highlight", builder => builder .DisplayedAs("Highlight") .WithPart("TitlePart") .WithPart(typeof(ScenarioPart).Name) .WithPart("HighlightsPart") .WithPart("CommonPart") //.WithPart("AutoroutePart", definitionBuilder => definitionBuilder // .WithSetting("AutorouteSettings.AllowCustomPattern", "true") // .WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "false") // .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: '/page-title'}]") // .WithSetting("AutorouteSettings.DefaultPatternIndex", "0")) .Draftable() .Creatable() ); #endregion return 1; } public int UpdateFrom1() { #region Alter the Tasks table to include Title<string> and Duration<string> columns SchemaBuilder.AlterTable("TaskRecord", table => table .AddColumn<string>("Title") ); SchemaBuilder.AlterTable("TaskRecord", table => table .AddColumn<string>("Duration") ); #endregion return 2; } public int UpdateFrom2() { #region Make the related resources table, attach it to Highlight SchemaBuilder.CreateTable("RelatedResourceRecord", table => table .Column<int>("Id", column => column.PrimaryKey().Identity()) .Column<int>("ScenarioRecord_Id") .Column<string>("Title") .Column<string>("Type") .Column<string>("Url") .Column<int>("SortOrder") ); ContentDefinitionManager.AlterPartDefinition( typeof(RelatedResourcePart).Name, cfg => cfg.Attachable()); ContentDefinitionManager.AlterTypeDefinition( "Highlight", cfg => cfg .WithPart("RelatedResourcePart")); return 3; #endregion } } public class WidgetMigrations : DataMigrationImpl { private readonly IContentManager _contentManager; private readonly IWidgetsService _widgetsService; private LayerPart _homePageLayer; public LayerPart HomePageLayer { get { return _homePageLayer ?? (_homePageLayer = _widgetsService.GetLayers().Single(layer => layer.Name == "TheHomepage")); } } public WidgetMigrations(IContentManager contentManager, IWidgetsService widgetsService) { _contentManager = contentManager; _widgetsService = widgetsService; } public int Create() { #region Create Highlights Widget ContentDefinitionManager.AlterPartDefinition(typeof (HighlightsWidgetPart).Name, builder => builder.Attachable()); ContentDefinitionManager.AlterTypeDefinition("HighlightsWidget", cfg => cfg .WithPart("WidgetPart") .WithPart("IdentityPart") .WithPart("HighlightsWidgetPart") .WithPart("CommonPart") .WithPart("LocalizationPart") .WithSetting("Stereotype", "Widget") ); ContentDefinitionManager.AlterPartDefinition(typeof(HighlightsWidgetPart).Name, builder => builder .WithField("HighlightPicker", cfg => cfg .OfType("ContentPickerField") .WithDisplayName("Highlight Picker") .WithSetting("ContentPickerFieldSettings.Multiple", "True") .WithSetting("ContentPickerFieldSettings.ShowContentTab", "True") .WithSetting("ContentPickerFieldSettings.DisplayedContentTypes", "Highlight") .WithSetting("ContentPickerFieldSettings.Hint", "Choose a highlight to link to this widget")) ); #endregion // This will be done manually in production, but for dev purposes, this can be uncommented to put a Highlights widget on the home page. //#region Place Highlights Widget on Home Page //WidgetPart highlightsWidget = _widgetsService.CreateWidget(HomePageLayer.Id, "HighlightsWidget", "Highlights Widget", "1", "Content"); //highlightsWidget.RenderTitle = false; //highlightsWidget.Name = "HighlightsWidget"; //_contentManager.Publish(highlightsWidget.ContentItem); //#endregion return 1; } public int UpdateFrom1() { ContentDefinitionManager.AlterPartDefinition( "CommonHighlightPart", builder => builder .WithDescription("Fields common to all modules within a highlight content type") .WithField("PageIntro", cfg => cfg .OfType(typeof(TextField).Name) .WithDisplayName("Page Intro") .WithSetting("TextFieldSettings.Flavor", "html") .WithSetting("TextFieldSettings.Hint", "Text to appear beneath the page title and above the labs")) .WithField("LabIntro", cfg => cfg .OfType(typeof(TextField).Name) .WithDisplayName("Lab Intro") .WithSetting("TextFieldSettings.Flavor", "large") .WithSetting("TextFieldSettings.Hint", "Text to appear above the labs (ex. 'Work your way through the Hands on Labs')")) .WithField("RelatedResourcesIntro", cfg => cfg .OfType(typeof(TextField).Name) .WithDisplayName("Related Resource Intro") .WithSetting("TextFieldSettings.Flavor", "html") .WithSetting("TextFieldSettings.Hint", "Text to appear above the list of related resources")) ); ContentDefinitionManager.AlterTypeDefinition( "HighlightsWidget", cfg => cfg .WithPart("CommonHighlightPart")); return 2; } } }
// 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. namespace System.Collections.Specialized { /// <devdoc> /// <para>Represents a collection of strings.</para> /// </devdoc> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class StringCollection : IList { private readonly ArrayList data = new ArrayList(); // Do not rename (binary serialization) /// <devdoc> /// <para>Represents the entry at the specified index of the <see cref='System.Collections.Specialized.StringCollection'/>.</para> /// </devdoc> public string? this[int index] { get { return ((string?)data[index]); } set { data[index] = value; } } /// <devdoc> /// <para>Gets the number of strings in the /// <see cref='System.Collections.Specialized.StringCollection'/> .</para> /// </devdoc> public int Count { get { return data.Count; } } bool IList.IsReadOnly { get { return false; } } bool IList.IsFixedSize { get { return false; } } /// <devdoc> /// <para>Adds a string with the specified value to the /// <see cref='System.Collections.Specialized.StringCollection'/> .</para> /// </devdoc> public int Add(string? value) { return data.Add(value); } /// <devdoc> /// <para>Copies the elements of a string array to the end of the <see cref='System.Collections.Specialized.StringCollection'/>.</para> /// </devdoc> public void AddRange(string[] value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } data.AddRange(value); } /// <devdoc> /// <para>Removes all the strings from the /// <see cref='System.Collections.Specialized.StringCollection'/> .</para> /// </devdoc> public void Clear() { data.Clear(); } /// <devdoc> /// <para>Gets a value indicating whether the /// <see cref='System.Collections.Specialized.StringCollection'/> contains a string with the specified /// value.</para> /// </devdoc> public bool Contains(string? value) { return data.Contains(value); } /// <devdoc> /// <para>Copies the <see cref='System.Collections.Specialized.StringCollection'/> values to a one-dimensional <see cref='System.Array'/> instance at the /// specified index.</para> /// </devdoc> public void CopyTo(string[] array, int index) { data.CopyTo(array, index); } /// <devdoc> /// <para>Returns an enumerator that can iterate through /// the <see cref='System.Collections.Specialized.StringCollection'/> .</para> /// </devdoc> public StringEnumerator GetEnumerator() { return new StringEnumerator(this); } /// <devdoc> /// <para>Returns the index of the first occurrence of a string in /// the <see cref='System.Collections.Specialized.StringCollection'/> .</para> /// </devdoc> public int IndexOf(string? value) { return data.IndexOf(value); } /// <devdoc> /// <para>Inserts a string into the <see cref='System.Collections.Specialized.StringCollection'/> at the specified /// index.</para> /// </devdoc> public void Insert(int index, string? value) { data.Insert(index, value); } /// <devdoc> /// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.StringCollection'/> is read-only.</para> /// </devdoc> public bool IsReadOnly { get { return false; } } /// <devdoc> /// <para>Gets a value indicating whether access to the /// <see cref='System.Collections.Specialized.StringCollection'/> /// is synchronized (thread-safe).</para> /// </devdoc> public bool IsSynchronized { get { return false; } } /// <devdoc> /// <para> Removes a specific string from the /// <see cref='System.Collections.Specialized.StringCollection'/> .</para> /// </devdoc> public void Remove(string? value) { data.Remove(value); } /// <devdoc> /// <para>Removes the string at the specified index of the <see cref='System.Collections.Specialized.StringCollection'/>.</para> /// </devdoc> public void RemoveAt(int index) { data.RemoveAt(index); } /// <devdoc> /// <para>Gets an object that can be used to synchronize access to the <see cref='System.Collections.Specialized.StringCollection'/>.</para> /// </devdoc> public object SyncRoot { get { return data.SyncRoot; } } object? IList.this[int index] { get { return this[index]; } set { this[index] = (string?)value; } } int IList.Add(object? value) { return Add((string?)value); } bool IList.Contains(object? value) { return Contains((string?)value); } int IList.IndexOf(object? value) { return IndexOf((string?)value); } void IList.Insert(int index, object? value) { Insert(index, (string?)value); } void IList.Remove(object? value) { Remove((string?)value); } void ICollection.CopyTo(Array array, int index) { data.CopyTo(array, index); } IEnumerator IEnumerable.GetEnumerator() { return data.GetEnumerator(); } } public class StringEnumerator { private readonly System.Collections.IEnumerator _baseEnumerator; private readonly System.Collections.IEnumerable _temp; internal StringEnumerator(StringCollection mappings) { _temp = (IEnumerable)(mappings); _baseEnumerator = _temp.GetEnumerator(); } public string? Current { get { return (string?)(_baseEnumerator.Current); } } public bool MoveNext() { return _baseEnumerator.MoveNext(); } public void Reset() { _baseEnumerator.Reset(); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Alerts.Alerts File: AlertService.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Alerts { using System; using System.IO; using System.Linq; using System.Speech.Synthesis; using System.Windows.Media; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Configuration; using Ecng.Serialization; using Ecng.Xaml; using StockSharp.Community; using StockSharp.Logging; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// Alert service. /// </summary> public class AlertService : Disposable, IAlertService { private readonly BlockingQueue<Tuple<AlertTypes, string, string, DateTimeOffset>> _alerts = new BlockingQueue<Tuple<AlertTypes, string, string, DateTimeOffset>>(); private readonly SynchronizedDictionary<Type, AlertSchema> _schemas = new SynchronizedDictionary<Type, AlertSchema>(); /// <summary> /// Initializes a new instance of the <see cref="AlertService"/>. /// </summary> /// <param name="dumpDir">Temp files directory.</param> public AlertService(string dumpDir) { if (dumpDir.IsEmpty()) throw new ArgumentNullException(nameof(dumpDir)); ThreadingHelper .Thread(() => { try { var player = new MediaPlayer(); var fileName = Path.Combine(dumpDir, "alert.mp3"); if (!File.Exists(fileName)) Properties.Resources.Alert.Save(fileName); player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute)); var logManager = ConfigManager.GetService<LogManager>(); using (var speech = new SpeechSynthesizer()) using (var client = new NotificationClient()) using (player.MakeDisposable(p => p.Close())) { while (!IsDisposed) { Tuple<AlertTypes, string, string, DateTimeOffset> alert; if (!_alerts.TryDequeue(out alert)) break; try { switch (alert.Item1) { case AlertTypes.Sound: player.Play(); break; case AlertTypes.Speech: speech.Speak(alert.Item2); break; case AlertTypes.Popup: GuiDispatcher.GlobalDispatcher.AddAction(() => new AlertPopupWindow { Title = alert.Item2, Message = alert.Item3, Time = alert.Item4.UtcDateTime }.Show()); break; case AlertTypes.Sms: client.SendSms(alert.Item2); break; case AlertTypes.Email: client.SendEmail(alert.Item2, alert.Item3); break; case AlertTypes.Log: logManager.Application.AddWarningLog(() => LocalizedStrings.Str3033Params .Put(alert.Item4, alert.Item2, Environment.NewLine + alert.Item3)); break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception ex) { ex.LogError(); } } } } catch (Exception ex) { ex.LogError(); } }) .Name("Alert thread") .Launch(); } /// <summary> /// Add alert at the output. /// </summary> /// <param name="type">Alert type.</param> /// <param name="caption">Signal header.</param> /// <param name="message">Alert text.</param> /// <param name="time">Creation time.</param> public void PushAlert(AlertTypes type, string caption, string message, DateTimeOffset time) { _alerts.Enqueue(Tuple.Create(type, caption, message, time)); } /// <summary> /// Register schema. /// </summary> /// <param name="schema">Schema.</param> public void Register(AlertSchema schema) { if (schema == null) throw new ArgumentNullException(nameof(schema)); _schemas[schema.MessageType] = schema; } /// <summary> /// Remove previously registered by <see cref="Register"/> schema. /// </summary> /// <param name="schema">Schema.</param> public void UnRegister(AlertSchema schema) { if (schema == null) throw new ArgumentNullException(nameof(schema)); _schemas.Remove(schema.MessageType); } /// <summary> /// Check message on alert conditions. /// </summary> /// <param name="message">Message.</param> public void Process(Message message) { if (message == null) throw new ArgumentNullException(nameof(message)); var schema = _schemas.TryGetValue(message.GetType()); var type = schema?.AlertType; if (type == null) return; var canAlert = schema.Rules.All(rule => { var value = rule.Property.GetValue(message, null); switch (rule.Operator) { case ComparisonOperator.Equal: return rule.Value.Equals(value); case ComparisonOperator.NotEqual: return !rule.Value.Equals(value); case ComparisonOperator.Greater: return OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) == 1; case ComparisonOperator.GreaterOrEqual: return OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) >= 0; case ComparisonOperator.Less: return OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) == -1; case ComparisonOperator.LessOrEqual: return OperatorRegistry.GetOperator(rule.Property.PropertyType).Compare(rule.Value, value) <= 0; case ComparisonOperator.Any: return true; default: throw new ArgumentOutOfRangeException(); } }); if (canAlert) PushAlert((AlertTypes)type, schema.Caption, schema.Message, message.LocalTime); } /// <summary> /// Release resources. /// </summary> protected override void DisposeManaged() { _alerts.Close(); base.DisposeManaged(); } } }
/* Copyright 2021 Jeffrey Sharp Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ using System.Management.Automation; // TODO: enable #nullable disable namespace PSql; using static ApplicationIntent; [Cmdlet(VerbsCommon.New, nameof(SqlContext), DefaultParameterSetName = GenericName)] [OutputType(typeof(SqlContext))] public class NewSqlContextCommand : PSCmdlet { private const string GenericName = "Generic", AzureName = "Azure", CloneName = "Clone"; // -Azure [Parameter(ParameterSetName = AzureName, Mandatory = true)] public SwitchParameter Azure { get; set; } // -Source [Parameter(ParameterSetName = CloneName, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNull] public SqlContext Source { get; set; } // -ResourceGroupName [Alias("ResourceGroup", "ServerResourceGroupName")] [Parameter(ParameterSetName = AzureName, Position = 0)] [Parameter(ParameterSetName = CloneName)] [AllowNull, AllowEmptyString] public string ResourceGroupName { get; set; } // -ServerResourceName [Alias("Resource")] [Parameter(ParameterSetName = AzureName, Position = 1)] [Parameter(ParameterSetName = CloneName)] [AllowNull, AllowEmptyString] public string ServerResourceName { get; set; } // -ServerName [Alias("Server")] [Parameter(ParameterSetName = GenericName, Position = 0)] [Parameter(ParameterSetName = AzureName)] [Parameter(ParameterSetName = CloneName, Position = 0)] [AllowNull, AllowEmptyString] public string ServerName { get; set; } // -DatabaseName [Alias("Database")] [Parameter(ParameterSetName = GenericName, Position = 1)] [Parameter(ParameterSetName = AzureName, Position = 2)] [Parameter(ParameterSetName = CloneName, Position = 1)] [AllowNull, AllowEmptyString] public string DatabaseName { get; set; } // -AuthenticationMode [Alias("Auth")] [Parameter(ParameterSetName = AzureName)] [Parameter(ParameterSetName = CloneName)] public AzureAuthenticationMode AuthenticationMode { get; set; } // -Credential [Parameter] [Credential] [AllowNull] public PSCredential Credential { get; set; } = PSCredential.Empty; // -EncryptionMode [Alias("Encryption")] [Parameter(ParameterSetName = GenericName)] [Parameter(ParameterSetName = CloneName)] public EncryptionMode EncryptionMode { get; set; } // -ServerPort [Alias("Port")] [Parameter(ParameterSetName = GenericName)] [Parameter(ParameterSetName = CloneName)] [ValidateNullOrPositiveUInt16] public ushort? ServerPort { get; set; } // -InstanceName [Alias("Instance")] [Parameter(ParameterSetName = GenericName)] [Parameter(ParameterSetName = CloneName)] [AllowNull, AllowEmptyString] public string InstanceName { get; set; } // -ReadOnlyIntent [Alias("ReadOnly")] [Parameter] public SwitchParameter ReadOnlyIntent { get; set; } // -ClientName [Alias("Client")] [Parameter] [AllowNull, AllowEmptyString] public string ClientName { get; set; } // -ApplicationName [Alias("Application")] [Parameter] [AllowNull, AllowEmptyString] public string ApplicationName { get; set; } // -ConnectTimeout [Alias("Timeout")] [Parameter] [ValidateNullOrTimeout] public TimeSpan? ConnectTimeout { get; set; } // -ExposeCredentialInConnectionString [Parameter] public SwitchParameter ExposeCredentialInConnectionString { get; set; } // -Pooling [Parameter] public SwitchParameter Pooling { get; set; } // -MultipleActiveResultSets [Alias("Mars")] [Parameter] public SwitchParameter MultipleActiveResultSets { get; set; } // -Frozen [Parameter] public SwitchParameter Frozen { get; set; } protected override void ProcessRecord() { var context = Source?.Clone() ?? CreateContext(); foreach (var parameterName in MyInvocation.BoundParameters.Keys) ApplyParameterValue(context, parameterName); if (Frozen) context.Freeze(); WriteObject(context); } private void ApplyParameterValue(SqlContext context, string parameterName) { switch (parameterName) { case nameof(ResourceGroupName): SetServerResourceGroupName (context); break; case nameof(ServerResourceName): SetServerResourceName (context); break; case nameof(ServerName): SetServerName (context); break; case nameof(ServerPort): SetServerPort (context); break; case nameof(InstanceName): SetInstanceName (context); break; case nameof(DatabaseName): SetDatabaseName (context); break; case nameof(AuthenticationMode): SetAuthenticationMode (context); break; case nameof(Credential): SetCredential (context); break; case nameof(EncryptionMode): SetEncryptionMode (context); break; case nameof(ConnectTimeout): SetConnectTimeout (context); break; case nameof(ClientName): SetClientName (context); break; case nameof(ApplicationName): SetApplicationName (context); break; case nameof(ReadOnlyIntent): SetApplicationIntent (context); break; case nameof(ExposeCredentialInConnectionString): SetExposeCredentialInConnectionString (context); break; case nameof(Pooling): SetEnableConnectionPooling (context); break; case nameof(MultipleActiveResultSets): SetEnableMultipleActiveResultSets (context); break; } } private SqlContext CreateContext() { return Azure.IsPresent ? new AzureSqlContext() : new SqlContext(); } private void SetServerResourceGroupName(SqlContext context) { if (context is AzureSqlContext azureContext) azureContext.ServerResourceGroupName = ResourceGroupName.NullIfEmpty(); else WarnIgnoredBecauseNotAzureContext(nameof(ResourceGroupName)); } private void SetServerResourceName(SqlContext context) { if (context is AzureSqlContext azureContext) azureContext.ServerResourceName = ServerResourceName.NullIfEmpty(); else WarnIgnoredBecauseNotAzureContext(nameof(ServerResourceName)); } private void SetServerName(SqlContext context) { context.ServerName = ServerName.NullIfEmpty(); } private void SetServerPort(SqlContext context) { context.ServerPort = ServerPort; } private void SetInstanceName(SqlContext context) { context.InstanceName = InstanceName.NullIfEmpty(); } private void SetDatabaseName(SqlContext context) { context.DatabaseName = DatabaseName.NullIfEmpty(); } private void SetAuthenticationMode(SqlContext context) { if (context is AzureSqlContext azureContext) azureContext.AuthenticationMode = AuthenticationMode; else WarnIgnoredBecauseNotAzureContext(nameof(AuthenticationMode)); } private void SetCredential(SqlContext context) { //var credential = Credential.IsNullOrEmpty() ? null : Credential; context.Credential = Credential; } private void SetEncryptionMode(SqlContext context) { if (context is AzureSqlContext) WarnIgnoredBecauseAzureContext(nameof(EncryptionMode)); else context.EncryptionMode = EncryptionMode; } private void SetConnectTimeout(SqlContext context) { context.ConnectTimeout = ConnectTimeout; } private void SetClientName(SqlContext context) { context.ClientName = ClientName.NullIfEmpty(); } private void SetApplicationName(SqlContext context) { context.ApplicationName = ApplicationName.NullIfEmpty(); } private void SetApplicationIntent(SqlContext context) { context.ApplicationIntent = ReadOnlyIntent ? ReadOnly : ReadWrite; } private void SetExposeCredentialInConnectionString(SqlContext context) { context.ExposeCredentialInConnectionString = ExposeCredentialInConnectionString; } private void SetEnableConnectionPooling(SqlContext context) { context.EnableConnectionPooling = Pooling; } private void SetEnableMultipleActiveResultSets(SqlContext context) { context.EnableMultipleActiveResultSets = MultipleActiveResultSets; } private void WarnIgnoredBecauseAzureContext(string parameterName) { WriteWarning(string.Format( "The '{0}' argument was ignored because " + "the context is an Azure SQL Database context.", parameterName )); } private void WarnIgnoredBecauseNotAzureContext(string parameterName) { WriteWarning(string.Format( "The '{0}' argument was ignored because " + "the context is not an Azure SQL Database context.", parameterName )); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime; namespace System.Collections.ObjectModel { [Serializable] [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ReadOnlyCollection<T> : IList<T>, IList, IReadOnlyList<T> { private IList<T> list; // Do not rename (binary serialization) [NonSerialized] private Object _syncRoot; public ReadOnlyCollection(IList<T> list) { if (list == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } this.list = list; } public int Count { get { return list.Count; } } public T this[int index] { get { return list[index]; } } public bool Contains(T value) { return list.Contains(value); } public void CopyTo(T[] array, int index) { list.CopyTo(array, index); } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } public int IndexOf(T value) { return list.IndexOf(value); } protected IList<T> Items { get { return list; } } bool ICollection<T>.IsReadOnly { get { return true; } } T IList<T>.this[int index] { get { return list[index]; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } void ICollection<T>.Add(T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void ICollection<T>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList<T>.Insert(int index, T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } bool ICollection<T>.Remove(T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return false; } void IList<T>.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)list).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { ICollection c = list as ICollection; if (c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } } return _syncRoot; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } T[] items = array as T[]; if (items != null) { list.CopyTo(items, index); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = list.Count; try { for (int i = 0; i < count; i++) { objects[index++] = list[i]; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } object IList.this[int index] { get { return list[index]; } set { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } int IList.Add(object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return -1; } void IList.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } bool IList.Contains(object value) { if (IsCompatibleObject(value)) { return Contains((T)value); } return false; } int IList.IndexOf(object value) { if (IsCompatibleObject(value)) { return IndexOf((T)value); } return -1; } void IList.Insert(int index, object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList.Remove(object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } void IList.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } } }
using System; using System.IO; using ICSharpCode.SharpZipLib.Checksum; namespace ICSharpCode.SharpZipLib.BZip2 { /// <summary> /// An input stream that decompresses files in the BZip2 format /// </summary> public class BZip2InputStream : Stream { #region Constants const int START_BLOCK_STATE = 1; const int RAND_PART_A_STATE = 2; const int RAND_PART_B_STATE = 3; const int RAND_PART_C_STATE = 4; const int NO_RAND_PART_A_STATE = 5; const int NO_RAND_PART_B_STATE = 6; const int NO_RAND_PART_C_STATE = 7; #endregion #region Constructors /// <summary> /// Construct instance for reading from stream /// </summary> /// <param name="stream">Data source</param> public BZip2InputStream(Stream stream) { // init arrays for (int i = 0; i < BZip2Constants.GroupCount; ++i) { limit[i] = new int[BZip2Constants.MaximumAlphaSize]; baseArray[i] = new int[BZip2Constants.MaximumAlphaSize]; perm[i] = new int[BZip2Constants.MaximumAlphaSize]; } BsSetStream(stream); Initialize(); InitBlock(); SetupBlock(); } #endregion /// <summary> /// Get/set flag indicating ownership of underlying stream. /// When the flag is true <see cref="Close"></see> will close the underlying stream also. /// </summary> public bool IsStreamOwner { get { return isStreamOwner; } set { isStreamOwner = value; } } #region Stream Overrides /// <summary> /// Gets a value indicating if the stream supports reading /// </summary> public override bool CanRead { get { return baseStream.CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return baseStream.CanSeek; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// This property always returns false /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> public override long Length { get { return baseStream.Length; } } /// <summary> /// Gets or sets the streams position. /// Setting the position is not supported and will throw a NotSupportException /// </summary> /// <exception cref="NotSupportedException">Any attempt to set the position</exception> public override long Position { get { return baseStream.Position; } set { throw new NotSupportedException("BZip2InputStream position cannot be set"); } } /// <summary> /// Flushes the stream. /// </summary> public override void Flush() { if (baseStream != null) { baseStream.Flush(); } } /// <summary> /// Set the streams position. This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> /// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param> /// <returns>The new position of the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("BZip2InputStream Seek not supported"); } /// <summary> /// Sets the length of this stream to the given value. /// This operation is not supported and will throw a NotSupportedExceptionortedException /// </summary> /// <param name="value">The new length for the stream.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("BZip2InputStream SetLength not supported"); } /// <summary> /// Writes a block of bytes to this stream using data from a buffer. /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="buffer">The buffer to source data from.</param> /// <param name="offset">The offset to start obtaining data from.</param> /// <param name="count">The number of bytes of data to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("BZip2InputStream Write not supported"); } /// <summary> /// Writes a byte to the current position in the file stream. /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="value">The value to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void WriteByte(byte value) { throw new NotSupportedException("BZip2InputStream WriteByte not supported"); } /// <summary> /// Read a sequence of bytes and advances the read position by one byte. /// </summary> /// <param name="buffer">Array of bytes to store values in</param> /// <param name="offset">Offset in array to begin storing data</param> /// <param name="count">The maximum number of bytes to read</param> /// <returns>The total number of bytes read into the buffer. This might be less /// than the number of bytes requested if that number of bytes are not /// currently available or zero if the end of the stream is reached. /// </returns> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } for (int i = 0; i < count; ++i) { int rb = ReadByte(); if (rb == -1) { return i; } buffer[offset + i] = (byte)rb; } return count; } /// <summary> /// Closes the stream, releasing any associated resources. /// </summary> public override void Close() { if (IsStreamOwner && (baseStream != null)) { baseStream.Close(); } } /// <summary> /// Read a byte from stream advancing position /// </summary> /// <returns>byte read or -1 on end of stream</returns> public override int ReadByte() { if (streamEnd) { return -1; // ok } int retChar = currentChar; switch (currentState) { case RAND_PART_B_STATE: SetupRandPartB(); break; case RAND_PART_C_STATE: SetupRandPartC(); break; case NO_RAND_PART_B_STATE: SetupNoRandPartB(); break; case NO_RAND_PART_C_STATE: SetupNoRandPartC(); break; case START_BLOCK_STATE: case NO_RAND_PART_A_STATE: case RAND_PART_A_STATE: break; } return retChar; } #endregion void MakeMaps() { nInUse = 0; for (int i = 0; i < 256; ++i) { if (inUse[i]) { seqToUnseq[nInUse] = (byte)i; unseqToSeq[i] = (byte)nInUse; nInUse++; } } } void Initialize() { char magic1 = BsGetUChar(); char magic2 = BsGetUChar(); char magic3 = BsGetUChar(); char magic4 = BsGetUChar(); if (magic1 != 'B' || magic2 != 'Z' || magic3 != 'h' || magic4 < '1' || magic4 > '9') { streamEnd = true; return; } SetDecompressStructureSizes(magic4 - '0'); computedCombinedCRC = 0; } void InitBlock() { char magic1 = BsGetUChar(); char magic2 = BsGetUChar(); char magic3 = BsGetUChar(); char magic4 = BsGetUChar(); char magic5 = BsGetUChar(); char magic6 = BsGetUChar(); if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) { Complete(); return; } if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) { BadBlockHeader(); streamEnd = true; return; } storedBlockCRC = BsGetInt32(); blockRandomised = (BsR(1) == 1); GetAndMoveToFrontDecode(); mCrc.Reset(); currentState = START_BLOCK_STATE; } void EndBlock() { computedBlockCRC = (int)mCrc.Value; // -- A bad CRC is considered a fatal error. -- if (storedBlockCRC != computedBlockCRC) { CrcError(); } // 1528150659 computedCombinedCRC = ((computedCombinedCRC << 1) & 0xFFFFFFFF) | (computedCombinedCRC >> 31); computedCombinedCRC = computedCombinedCRC ^ (uint)computedBlockCRC; } void Complete() { storedCombinedCRC = BsGetInt32(); if (storedCombinedCRC != (int)computedCombinedCRC) { CrcError(); } streamEnd = true; } void BsSetStream(Stream stream) { baseStream = stream; bsLive = 0; bsBuff = 0; } void FillBuffer() { int thech = 0; try { thech = baseStream.ReadByte(); } catch (Exception) { CompressedStreamEOF(); } if (thech == -1) { CompressedStreamEOF(); } bsBuff = (bsBuff << 8) | (thech & 0xFF); bsLive += 8; } int BsR(int n) { while (bsLive < n) { FillBuffer(); } int v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1); bsLive -= n; return v; } char BsGetUChar() { return (char)BsR(8); } int BsGetIntVS(int numBits) { return BsR(numBits); } int BsGetInt32() { int result = BsR(8); result = (result << 8) | BsR(8); result = (result << 8) | BsR(8); result = (result << 8) | BsR(8); return result; } void RecvDecodingTables() { char[][] len = new char[BZip2Constants.GroupCount][]; for (int i = 0; i < BZip2Constants.GroupCount; ++i) { len[i] = new char[BZip2Constants.MaximumAlphaSize]; } bool[] inUse16 = new bool[16]; //--- Receive the mapping table --- for (int i = 0; i < 16; i++) { inUse16[i] = (BsR(1) == 1); } for (int i = 0; i < 16; i++) { if (inUse16[i]) { for (int j = 0; j < 16; j++) { inUse[i * 16 + j] = (BsR(1) == 1); } } else { for (int j = 0; j < 16; j++) { inUse[i * 16 + j] = false; } } } MakeMaps(); int alphaSize = nInUse + 2; //--- Now the selectors --- int nGroups = BsR(3); int nSelectors = BsR(15); for (int i = 0; i < nSelectors; i++) { int j = 0; while (BsR(1) == 1) { j++; } selectorMtf[i] = (byte)j; } //--- Undo the MTF values for the selectors. --- byte[] pos = new byte[BZip2Constants.GroupCount]; for (int v = 0; v < nGroups; v++) { pos[v] = (byte)v; } for (int i = 0; i < nSelectors; i++) { int v = selectorMtf[i]; byte tmp = pos[v]; while (v > 0) { pos[v] = pos[v - 1]; v--; } pos[0] = tmp; selector[i] = tmp; } //--- Now the coding tables --- for (int t = 0; t < nGroups; t++) { int curr = BsR(5); for (int i = 0; i < alphaSize; i++) { while (BsR(1) == 1) { if (BsR(1) == 0) { curr++; } else { curr--; } } len[t][i] = (char)curr; } } //--- Create the Huffman decoding tables --- for (int t = 0; t < nGroups; t++) { int minLen = 32; int maxLen = 0; for (int i = 0; i < alphaSize; i++) { maxLen = Math.Max(maxLen, len[t][i]); minLen = Math.Min(minLen, len[t][i]); } HbCreateDecodeTables(limit[t], baseArray[t], perm[t], len[t], minLen, maxLen, alphaSize); minLens[t] = minLen; } } void GetAndMoveToFrontDecode() { byte[] yy = new byte[256]; int nextSym; int limitLast = BZip2Constants.BaseBlockSize * blockSize100k; origPtr = BsGetIntVS(24); RecvDecodingTables(); int EOB = nInUse + 1; int groupNo = -1; int groupPos = 0; /*-- Setting up the unzftab entries here is not strictly necessary, but it does save having to do it later in a separate pass, and so saves a block's worth of cache misses. --*/ for (int i = 0; i <= 255; i++) { unzftab[i] = 0; } for (int i = 0; i <= 255; i++) { yy[i] = (byte)i; } last = -1; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.GroupSize; } groupPos--; int zt = selector[groupNo]; int zn = minLens[zt]; int zvec = BsR(zn); int zj; while (zvec > limit[zt][zn]) { if (zn > 20) { // the longest code throw new BZip2Exception("Bzip data error"); } zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } if (zvec - baseArray[zt][zn] < 0 || zvec - baseArray[zt][zn] >= BZip2Constants.MaximumAlphaSize) { throw new BZip2Exception("Bzip data error"); } nextSym = perm[zt][zvec - baseArray[zt][zn]]; while (true) { if (nextSym == EOB) { break; } if (nextSym == BZip2Constants.RunA || nextSym == BZip2Constants.RunB) { int s = -1; int n = 1; do { if (nextSym == BZip2Constants.RunA) { s += (0 + 1) * n; } else if (nextSym == BZip2Constants.RunB) { s += (1 + 1) * n; } n <<= 1; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.GroupSize; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - baseArray[zt][zn]]; } while (nextSym == BZip2Constants.RunA || nextSym == BZip2Constants.RunB); s++; byte ch = seqToUnseq[yy[0]]; unzftab[ch] += s; while (s > 0) { last++; ll8[last] = ch; s--; } if (last >= limitLast) { BlockOverrun(); } continue; } else { last++; if (last >= limitLast) { BlockOverrun(); } byte tmp = yy[nextSym - 1]; unzftab[seqToUnseq[tmp]]++; ll8[last] = seqToUnseq[tmp]; for (int j = nextSym - 1; j > 0; --j) { yy[j] = yy[j - 1]; } yy[0] = tmp; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.GroupSize; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - baseArray[zt][zn]]; continue; } } } void SetupBlock() { int[] cftab = new int[257]; cftab[0] = 0; Array.Copy(unzftab, 0, cftab, 1, 256); for (int i = 1; i <= 256; i++) { cftab[i] += cftab[i - 1]; } for (int i = 0; i <= last; i++) { byte ch = ll8[i]; tt[cftab[ch]] = i; cftab[ch]++; } cftab = null; tPos = tt[origPtr]; count = 0; i2 = 0; ch2 = 256; /*-- not a char and not EOF --*/ if (blockRandomised) { rNToGo = 0; rTPos = 0; SetupRandPartA(); } else { SetupNoRandPartA(); } } void SetupRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.RandomNumbers[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; ch2 ^= (int)((rNToGo == 1) ? 1 : 0); i2++; currentChar = ch2; currentState = RAND_PART_B_STATE; mCrc.Update(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } void SetupNoRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; i2++; currentChar = ch2; currentState = NO_RAND_PART_B_STATE; mCrc.Update(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } void SetupRandPartB() { if (ch2 != chPrev) { currentState = RAND_PART_A_STATE; count = 1; SetupRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.RandomNumbers[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; z ^= (byte)((rNToGo == 1) ? 1 : 0); j2 = 0; currentState = RAND_PART_C_STATE; SetupRandPartC(); } else { currentState = RAND_PART_A_STATE; SetupRandPartA(); } } } void SetupRandPartC() { if (j2 < (int)z) { currentChar = ch2; mCrc.Update(ch2); j2++; } else { currentState = RAND_PART_A_STATE; i2++; count = 0; SetupRandPartA(); } } void SetupNoRandPartB() { if (ch2 != chPrev) { currentState = NO_RAND_PART_A_STATE; count = 1; SetupNoRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; currentState = NO_RAND_PART_C_STATE; j2 = 0; SetupNoRandPartC(); } else { currentState = NO_RAND_PART_A_STATE; SetupNoRandPartA(); } } } void SetupNoRandPartC() { if (j2 < (int)z) { currentChar = ch2; mCrc.Update(ch2); j2++; } else { currentState = NO_RAND_PART_A_STATE; i2++; count = 0; SetupNoRandPartA(); } } void SetDecompressStructureSizes(int newSize100k) { if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k && blockSize100k <= 9)) { throw new BZip2Exception("Invalid block size"); } blockSize100k = newSize100k; if (newSize100k == 0) { return; } int n = BZip2Constants.BaseBlockSize * newSize100k; ll8 = new byte[n]; tt = new int[n]; } static void CompressedStreamEOF() { throw new EndOfStreamException("BZip2 input stream end of compressed stream"); } static void BlockOverrun() { throw new BZip2Exception("BZip2 input stream block overrun"); } static void BadBlockHeader() { throw new BZip2Exception("BZip2 input stream bad block header"); } static void CrcError() { throw new BZip2Exception("BZip2 input stream crc error"); } static void HbCreateDecodeTables(int[] limit, int[] baseArray, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) { int pp = 0; for (int i = minLen; i <= maxLen; ++i) { for (int j = 0; j < alphaSize; ++j) { if (length[j] == i) { perm[pp] = j; ++pp; } } } for (int i = 0; i < BZip2Constants.MaximumCodeLength; i++) { baseArray[i] = 0; } for (int i = 0; i < alphaSize; i++) { ++baseArray[length[i] + 1]; } for (int i = 1; i < BZip2Constants.MaximumCodeLength; i++) { baseArray[i] += baseArray[i - 1]; } for (int i = 0; i < BZip2Constants.MaximumCodeLength; i++) { limit[i] = 0; } int vec = 0; for (int i = minLen; i <= maxLen; i++) { vec += (baseArray[i + 1] - baseArray[i]); limit[i] = vec - 1; vec <<= 1; } for (int i = minLen + 1; i <= maxLen; i++) { baseArray[i] = ((limit[i - 1] + 1) << 1) - baseArray[i]; } } #region Instance Fields /*-- index of the last char in the block, so the block size == last + 1. --*/ int last; /*-- index in zptr[] of original string after sorting. --*/ int origPtr; /*-- always: in the range 0 .. 9. The current block size is 100000 * this number. --*/ int blockSize100k; bool blockRandomised; int bsBuff; int bsLive; IChecksum mCrc = new BZip2Crc(); bool[] inUse = new bool[256]; int nInUse; byte[] seqToUnseq = new byte[256]; byte[] unseqToSeq = new byte[256]; byte[] selector = new byte[BZip2Constants.MaximumSelectors]; byte[] selectorMtf = new byte[BZip2Constants.MaximumSelectors]; int[] tt; byte[] ll8; /*-- freq table collected to save a pass over the data during decompression. --*/ int[] unzftab = new int[256]; int[][] limit = new int[BZip2Constants.GroupCount][]; int[][] baseArray = new int[BZip2Constants.GroupCount][]; int[][] perm = new int[BZip2Constants.GroupCount][]; int[] minLens = new int[BZip2Constants.GroupCount]; Stream baseStream; bool streamEnd; int currentChar = -1; int currentState = START_BLOCK_STATE; int storedBlockCRC, storedCombinedCRC; int computedBlockCRC; uint computedCombinedCRC; int count, chPrev, ch2; int tPos; int rNToGo; int rTPos; int i2, j2; byte z; bool isStreamOwner = true; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <devdoc> /// Listens to the system directory change notifications and /// raises events when a directory or file within a directory changes. /// </devdoc> public partial class FileSystemWatcher : Component, ISupportInitialize { /// <devdoc> /// Private instance variables /// </devdoc> // Directory being monitored private string _directory; // Filter for name matching private string _filter; // The watch filter for the API call. private const NotifyFilters c_defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; private NotifyFilters _notifyFilters = c_defaultNotifyFilters; // Flag to watch subtree of this directory private bool _includeSubdirectories = false; // Flag to note whether we are attached to the thread pool and responding to changes private bool _enabled = false; // Are we in init? private bool _initializing = false; // Buffer size private int _internalBufferSize = 8192; // Used for synchronization private bool _disposed; private ISynchronizeInvoke _synchronizingObject; // Event handlers private FileSystemEventHandler _onChangedHandler = null; private FileSystemEventHandler _onCreatedHandler = null; private FileSystemEventHandler _onDeletedHandler = null; private RenamedEventHandler _onRenamedHandler = null; private ErrorEventHandler _onErrorHandler = null; // To validate the input for "path" private static readonly char[] s_wildcards = new char[] { '?', '*' }; private const int c_notifyFiltersValidMask = (int)(NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size); #if DEBUG static FileSystemWatcher() { int s_notifyFiltersValidMask = 0; foreach (int enumValue in Enum.GetValues(typeof(NotifyFilters))) s_notifyFiltersValidMask |= enumValue; Debug.Assert(c_notifyFiltersValidMask == s_notifyFiltersValidMask, "The NotifyFilters enum has changed. The c_notifyFiltersValidMask must be updated to reflect the values of the NotifyFilters enum."); } #endif /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class. /// </devdoc> public FileSystemWatcher() { _directory = string.Empty; _filter = "*.*"; } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory to monitor. /// </devdoc> public FileSystemWatcher(string path) : this(path, "*.*") { } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory and type of files to monitor. /// </devdoc> public FileSystemWatcher(string path, string filter) { if (path == null) throw new ArgumentNullException(nameof(path)); if (filter == null) throw new ArgumentNullException(nameof(filter)); // Early check for directory parameter so that an exception can be thrown as early as possible. if (path.Length == 0 || !Directory.Exists(path)) throw new ArgumentException(SR.Format(SR.InvalidDirName, path), nameof(path)); _directory = path; _filter = filter; } /// <devdoc> /// Gets or sets the type of changes to watch for. /// </devdoc> public NotifyFilters NotifyFilter { get { return _notifyFilters; } set { if (((int)value & ~c_notifyFiltersValidMask) != 0) throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(value), (int)value, nameof(NotifyFilters))); if (_notifyFilters != value) { _notifyFilters = value; Restart(); } } } /// <devdoc> /// Gets or sets a value indicating whether the component is enabled. /// </devdoc> public bool EnableRaisingEvents { get { return _enabled; } set { if (_enabled == value) { return; } if (IsSuspended()) { _enabled = value; // Alert the Component to start watching for events when EndInit is called. } else { if (value) { StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started } else { StopRaisingEvents(); // will set _enabled to false } } } } /// <devdoc> /// Gets or sets the filter string, used to determine what files are monitored in a directory. /// </devdoc> public string Filter { get { return _filter; } set { if (string.IsNullOrEmpty(value)) { // Skip the string compare for "*.*" since it has no case-insensitive representation that differs from // the case-sensitive representation. _filter = "*.*"; } else if (!string.Equals(_filter, value, PathInternal.StringComparison)) { _filter = value; } } } /// <devdoc> /// Gets or sets a value indicating whether subdirectories within the specified path should be monitored. /// </devdoc> public bool IncludeSubdirectories { get { return _includeSubdirectories; } set { if (_includeSubdirectories != value) { _includeSubdirectories = value; Restart(); } } } /// <devdoc> /// Gets or sets the size of the internal buffer. /// </devdoc> public int InternalBufferSize { get { return _internalBufferSize; } set { if (_internalBufferSize != value) { if (value < 4096) { _internalBufferSize = 4096; } else { _internalBufferSize = value; } Restart(); } } } /// <summary>Allocates a buffer of the requested internal buffer size.</summary> /// <returns>The allocated buffer.</returns> private byte[] AllocateBuffer() { try { return new byte[_internalBufferSize]; } catch (OutOfMemoryException) { throw new OutOfMemoryException(SR.Format(SR.BufferSizeTooLarge, _internalBufferSize)); } } /// <devdoc> /// Gets or sets the path of the directory to watch. /// </devdoc> public string Path { get { return _directory; } set { value = (value == null) ? string.Empty : value; if (!string.Equals(_directory, value, PathInternal.StringComparison)) { if (!Directory.Exists(value)) { throw new ArgumentException(SR.Format(SR.InvalidDirName, value)); } _directory = value; Restart(); } } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed. /// </devdoc> public event FileSystemEventHandler Changed { add { _onChangedHandler += value; } remove { _onChangedHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is created. /// </devdoc> public event FileSystemEventHandler Created { add { _onCreatedHandler += value; } remove { _onCreatedHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is deleted. /// </devdoc> public event FileSystemEventHandler Deleted { add { _onDeletedHandler += value; } remove { _onDeletedHandler -= value; } } /// <devdoc> /// Occurs when the internal buffer overflows. /// </devdoc> public event ErrorEventHandler Error { add { _onErrorHandler += value; } remove { _onErrorHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> /// is renamed. /// </devdoc> public event RenamedEventHandler Renamed { add { _onRenamedHandler += value; } remove { _onRenamedHandler -= value; } } /// <devdoc> /// </devdoc> protected override void Dispose(bool disposing) { try { if (disposing) { //Stop raising events cleans up managed and //unmanaged resources. StopRaisingEvents(); // Clean up managed resources _onChangedHandler = null; _onCreatedHandler = null; _onDeletedHandler = null; _onRenamedHandler = null; _onErrorHandler = null; } else { FinalizeDispose(); } } finally { _disposed = true; base.Dispose(disposing); } } /// <devdoc> /// Sees if the name given matches the name filter we have. /// </devdoc> /// <internalonly/> private bool MatchPattern(string relativePath) { string name = System.IO.Path.GetFileName(relativePath); return name != null ? PatternMatcher.StrictMatchPattern(_filter, name) : false; } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyInternalBufferOverflowEvent() { _onErrorHandler?.Invoke(this, new ErrorEventArgs( new InternalBufferOverflowException(SR.Format(SR.FSW_BufferOverflow, _directory)))); } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyRenameEventArgs(WatcherChangeTypes action, string name, string oldName) { // filter if there's no handler or neither new name or old name match a specified pattern RenamedEventHandler handler = _onRenamedHandler; if (handler != null && (MatchPattern(name) || MatchPattern(oldName))) { handler(this, new RenamedEventArgs(action, _directory, name, oldName)); } } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string name) { FileSystemEventHandler handler = null; switch (changeType) { case WatcherChangeTypes.Created: handler = _onCreatedHandler; break; case WatcherChangeTypes.Deleted: handler = _onDeletedHandler; break; case WatcherChangeTypes.Changed: handler = _onChangedHandler; break; default: Debug.Fail("Unknown FileSystemEvent change type! Value: " + changeType); break; } if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name)) { handler(this, new FileSystemEventArgs(changeType, _directory, name)); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnChanged(FileSystemEventArgs e) { InvokeOn(e, _onChangedHandler); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnCreated(FileSystemEventArgs e) { InvokeOn(e, _onCreatedHandler); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnDeleted(FileSystemEventArgs e) { InvokeOn(e, _onDeletedHandler); } private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler handler) { if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnError(ErrorEventArgs e) { ErrorEventHandler handler = _onErrorHandler; if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnRenamed(RenamedEventArgs e) { RenamedEventHandler handler = _onRenamedHandler; if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) => WaitForChanged(changeType, Timeout.Infinite); public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { // The full framework implementation doesn't do any argument validation, so // none is done here, either. var tcs = new TaskCompletionSource<WaitForChangedResult>(); FileSystemEventHandler fseh = null; RenamedEventHandler reh = null; // Register the event handlers based on what events are desired. The full framework // doesn't register for the Error event, so this doesn't either. if ((changeType & (WatcherChangeTypes.Created | WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed)) != 0) { fseh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, oldName: null, timedOut: false)); } }; if ((changeType & WatcherChangeTypes.Created) != 0) Created += fseh; if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted += fseh; if ((changeType & WatcherChangeTypes.Changed) != 0) Changed += fseh; } if ((changeType & WatcherChangeTypes.Renamed) != 0) { reh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, timedOut: false)); } }; Renamed += reh; } try { // Enable the FSW if it wasn't already. bool wasEnabled = EnableRaisingEvents; if (!wasEnabled) { EnableRaisingEvents = true; } // Block until an appropriate event arrives or until we timeout. Debug.Assert(EnableRaisingEvents, "Expected EnableRaisingEvents to be true"); tcs.Task.Wait(timeout); // Reset the enabled state to what it was. EnableRaisingEvents = wasEnabled; } finally { // Unregister the event handlers. if (reh != null) { Renamed -= reh; } if (fseh != null) { if ((changeType & WatcherChangeTypes.Changed) != 0) Changed -= fseh; if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted -= fseh; if ((changeType & WatcherChangeTypes.Created) != 0) Created -= fseh; } } // Return the results. return tcs.Task.Status == TaskStatus.RanToCompletion ? tcs.Task.Result : WaitForChangedResult.TimedOutResult; } /// <devdoc> /// Stops and starts this object. /// </devdoc> /// <internalonly/> private void Restart() { if ((!IsSuspended()) && _enabled) { StopRaisingEvents(); StartRaisingEventsIfNotDisposed(); } } private void StartRaisingEventsIfNotDisposed() { //Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed. if (_disposed) throw new ObjectDisposedException(GetType().Name); StartRaisingEvents(); } public override ISite Site { get { return base.Site; } set { base.Site = value; // set EnableRaisingEvents to true at design time so the user // doesn't have to manually. if (Site != null && Site.DesignMode) EnableRaisingEvents = true; } } public ISynchronizeInvoke SynchronizingObject { get { return _synchronizingObject; } set { _synchronizingObject = value; } } public void BeginInit() { bool oldEnabled = _enabled; StopRaisingEvents(); _enabled = oldEnabled; _initializing = true; } public void EndInit() { _initializing = false; // Start listening to events if _enabled was set to true at some point. if (_directory.Length != 0 && _enabled) StartRaisingEvents(); } private bool IsSuspended() { return _initializing || DesignMode; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Constants = Lucene.Net.Util.Constants; namespace Lucene.Net.Store { /// <summary>File-based {@link Directory} implementation that uses /// mmap for reading, and {@link /// SimpleFSDirectory.SimpleFSIndexOutput} for writing. /// /// <p/><b>NOTE</b>: memory mapping uses up a portion of the /// virtual memory address space in your process equal to the /// size of the file being mapped. Before using this class, /// be sure your have plenty of virtual address space, e.g. by /// using a 64 bit JRE, or a 32 bit JRE with indexes that are /// guaranteed to fit within the address space. /// On 32 bit platforms also consult {@link #setMaxChunkSize} /// if you have problems with mmap failing because of fragmented /// address space. If you get an OutOfMemoryException, it is recommened /// to reduce the chunk size, until it works. /// /// <p/>Due to <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038"> /// this bug</a> in Sun's JRE, MMapDirectory's {@link IndexInput#close} /// is unable to close the underlying OS file handle. Only when GC /// finally collects the underlying objects, which could be quite /// some time later, will the file handle be closed. /// /// <p/>This will consume additional transient disk usage: on Windows, /// attempts to delete or overwrite the files will result in an /// exception; on other platforms, which typically have a &quot;delete on /// last close&quot; semantics, while such operations will succeed, the bytes /// are still consuming space on disk. For many applications this /// limitation is not a problem (e.g. if you have plenty of disk space, /// and you don't rely on overwriting files on Windows) but it's still /// an important limitation to be aware of. /// /// <p/>This class supplies the workaround mentioned in the bug report /// (disabled by default, see {@link #setUseUnmap}), which may fail on /// non-Sun JVMs. It forcefully unmaps the buffer on close by using /// an undocumented internal cleanup functionality. /// {@link #UNMAP_SUPPORTED} is <code>true</code>, if the workaround /// can be enabled (with no guarantees). /// </summary> public class MMapDirectory:FSDirectory { private class AnonymousClassPrivilegedExceptionAction // : SupportClass.IPriviligedAction // {{Aroush-2.9}} { public AnonymousClassPrivilegedExceptionAction(byte[] buffer, MMapDirectory enclosingInstance) { InitBlock(buffer, enclosingInstance); } private void InitBlock(byte[] buffer, MMapDirectory enclosingInstance) { this.buffer = buffer; this.enclosingInstance = enclosingInstance; } private byte[] buffer; private MMapDirectory enclosingInstance; public MMapDirectory Enclosing_Instance { get { return enclosingInstance; } } public virtual System.Object Run() { // {{Aroush-2.9 /* System.Reflection.MethodInfo getCleanerMethod = buffer.GetType().GetMethod("cleaner", (Lucene.Net.Store.MMapDirectory.NO_PARAM_TYPES == null)?new System.Type[0]:(System.Type[]) Lucene.Net.Store.MMapDirectory.NO_PARAM_TYPES); getCleanerMethod.SetAccessible(true); System.Object cleaner = getCleanerMethod.Invoke(buffer, (System.Object[]) Lucene.Net.Store.MMapDirectory.NO_PARAMS); if (cleaner != null) { cleaner.GetType().GetMethod("clean", (Lucene.Net.Store.MMapDirectory.NO_PARAM_TYPES == null)?new System.Type[0]:(System.Type[]) Lucene.Net.Store.MMapDirectory.NO_PARAM_TYPES).Invoke(cleaner, (System.Object[]) Lucene.Net.Store.MMapDirectory.NO_PARAMS); } */ System.Diagnostics.Debug.Fail("Port issue:", "sun.misc.Cleaner()"); // {{Aroush-2.9}} // Aroush-2.9}} return null; } } private void InitBlock() { maxBBuf = Constants.JRE_IS_64BIT?System.Int32.MaxValue:(256 * 1024 * 1024); } /// <summary>Create a new MMapDirectory for the named location. /// /// </summary> /// <param name="path">the path of the directory /// </param> /// <param name="lockFactory">the lock factory to use, or null for the default. /// </param> /// <throws> IOException </throws> [System.Obsolete("Use the constructor that takes a DirectoryInfo, this will be removed in the 3.0 release")] public MMapDirectory(System.IO.FileInfo path, LockFactory lockFactory):base(new System.IO.DirectoryInfo(path.FullName), lockFactory) { InitBlock(); } /// <summary>Create a new MMapDirectory for the named location. /// /// </summary> /// <param name="path">the path of the directory /// </param> /// <param name="lockFactory">the lock factory to use, or null for the default. /// </param> /// <throws> IOException </throws> public MMapDirectory(System.IO.DirectoryInfo path, LockFactory lockFactory) : base(path, lockFactory) { InitBlock(); } /// <summary>Create a new MMapDirectory for the named location and the default lock factory. /// /// </summary> /// <param name="path">the path of the directory /// </param> /// <throws> IOException </throws> [System.Obsolete("Use the constructor that takes a DirectoryInfo, this will be removed in the 3.0 release")] public MMapDirectory(System.IO.FileInfo path):base(new System.IO.DirectoryInfo(path.FullName), null) { InitBlock(); } /// <summary>Create a new MMapDirectory for the named location and the default lock factory. /// /// </summary> /// <param name="path">the path of the directory /// </param> /// <throws> IOException </throws> public MMapDirectory(System.IO.DirectoryInfo path) : base(path, null) { InitBlock(); } // back compatibility so FSDirectory can instantiate via reflection /// <deprecated> /// </deprecated> [Obsolete] internal MMapDirectory() { InitBlock(); } internal static readonly System.Type[] NO_PARAM_TYPES = new System.Type[0]; internal static readonly System.Object[] NO_PARAMS = new System.Object[0]; private bool useUnmapHack = false; private int maxBBuf; /// <summary> <code>true</code>, if this platform supports unmapping mmaped files.</summary> public static bool UNMAP_SUPPORTED; /// <summary> This method enables the workaround for unmapping the buffers /// from address space after closing {@link IndexInput}, that is /// mentioned in the bug report. This hack may fail on non-Sun JVMs. /// It forcefully unmaps the buffer on close by using /// an undocumented internal cleanup functionality. /// <p/><b>NOTE:</b> Enabling this is completely unsupported /// by Java and may lead to JVM crashs if <code>IndexInput</code> /// is closed while another thread is still accessing it (SIGSEGV). /// </summary> /// <throws> IllegalArgumentException if {@link #UNMAP_SUPPORTED} </throws> /// <summary> is <code>false</code> and the workaround cannot be enabled. /// </summary> public virtual void SetUseUnmap(bool useUnmapHack) { if (useUnmapHack && !UNMAP_SUPPORTED) throw new System.ArgumentException("Unmap hack not supported on this platform!"); this.useUnmapHack = useUnmapHack; } /// <summary> Returns <code>true</code>, if the unmap workaround is enabled.</summary> /// <seealso cref="setUseUnmap"> /// </seealso> public virtual bool GetUseUnmap() { return useUnmapHack; } /// <summary> Try to unmap the buffer, this method silently fails if no support /// for that in the JVM. On Windows, this leads to the fact, /// that mmapped files cannot be modified or deleted. /// </summary> internal void CleanMapping(System.IO.MemoryStream buffer) { if (useUnmapHack) { try { // {{Aroush-2.9}} Not converted: java.security.AccessController.doPrivileged() System.Diagnostics.Debug.Fail("Port issue:", "java.security.AccessController.doPrivileged()"); // {{Aroush-2.9}} // AccessController.DoPrivileged(new AnonymousClassPrivilegedExceptionAction(buffer, this)); } catch (System.Exception e) { System.IO.IOException ioe = new System.IO.IOException("unable to unmap the mapped buffer", e.InnerException); throw ioe; } } } /// <summary> Sets the maximum chunk size (default is {@link Integer#MAX_VALUE} for /// 64 bit JVMs and 256 MiBytes for 32 bit JVMs) used for memory mapping. /// Especially on 32 bit platform, the address space can be very fragmented, /// so large index files cannot be mapped. /// Using a lower chunk size makes the directory implementation a little /// bit slower (as the correct chunk must be resolved on each seek) /// but the chance is higher that mmap does not fail. On 64 bit /// Java platforms, this parameter should always be {@link Integer#MAX_VALUE}, /// as the adress space is big enough. /// </summary> public virtual void SetMaxChunkSize(int maxBBuf) { if (maxBBuf <= 0) throw new System.ArgumentException("Maximum chunk size for mmap must be >0"); this.maxBBuf = maxBBuf; } /// <summary> Returns the current mmap chunk size.</summary> /// <seealso cref="setMaxChunkSize"> /// </seealso> public virtual int GetMaxChunkSize() { return maxBBuf; } private class MMapIndexInput:IndexInput, System.ICloneable { private void InitBlock(MMapDirectory enclosingInstance) { this.enclosingInstance = enclosingInstance; } private MMapDirectory enclosingInstance; public MMapDirectory Enclosing_Instance { get { return enclosingInstance; } } private System.IO.MemoryStream buffer; private long length; private bool isClone = false; internal MMapIndexInput(MMapDirectory enclosingInstance, System.IO.FileStream raf) { byte[] data = new byte[raf.Length]; raf.Read(data, 0, (int) raf.Length); InitBlock(enclosingInstance); this.length = raf.Length; this.buffer = new System.IO.MemoryStream(data); } public override byte ReadByte() { try { return (byte) buffer.ReadByte(); } catch (ObjectDisposedException e) { throw new System.IO.IOException("read past EOF"); } } public override void ReadBytes(byte[] b, int offset, int len) { try { buffer.Read(b, offset, len); } catch (ObjectDisposedException e) { throw new System.IO.IOException("read past EOF"); } } public override long GetFilePointer() { return buffer.Position;; } public override void Seek(long pos) { buffer.Seek(pos, System.IO.SeekOrigin.Begin); } public override long Length() { return length; } public override System.Object Clone() { if (buffer == null) throw new AlreadyClosedException("MMapIndexInput already closed"); MMapIndexInput clone = (MMapIndexInput) base.Clone(); clone.isClone = true; // clone.buffer = buffer.duplicate(); // {{Aroush-1.9}} return clone; } public override void Close() { if (isClone || buffer == null) return ; // unmap the buffer (if enabled) and at least unset it for GC try { Enclosing_Instance.CleanMapping(buffer); } finally { buffer = null; } } } // Because Java's ByteBuffer uses an int to address the // values, it's necessary to access a file > // Integer.MAX_VALUE in size using multiple byte buffers. private class MultiMMapIndexInput:IndexInput, System.ICloneable { private void InitBlock(MMapDirectory enclosingInstance) { this.enclosingInstance = enclosingInstance; } private MMapDirectory enclosingInstance; public MMapDirectory Enclosing_Instance { get { return enclosingInstance; } } private System.IO.MemoryStream[] buffers; private int[] bufSizes; // keep here, ByteBuffer.size() method is optional private long length; private int curBufIndex; private int maxBufSize; private System.IO.MemoryStream curBuf; // redundant for speed: buffers[curBufIndex] private int curAvail; // redundant for speed: (bufSizes[curBufIndex] - curBuf.position()) private bool isClone = false; public MultiMMapIndexInput(MMapDirectory enclosingInstance, System.IO.FileStream raf, int maxBufSize) { InitBlock(enclosingInstance); this.length = raf.Length; this.maxBufSize = maxBufSize; if (maxBufSize <= 0) throw new System.ArgumentException("Non positive maxBufSize: " + maxBufSize); if ((length / maxBufSize) > System.Int32.MaxValue) { throw new System.ArgumentException("RandomAccessFile too big for maximum buffer size: " + raf.ToString()); } int nrBuffers = (int) (length / maxBufSize); if (((long) nrBuffers * maxBufSize) < length) nrBuffers++; this.buffers = new System.IO.MemoryStream[nrBuffers]; this.bufSizes = new int[nrBuffers]; long bufferStart = 0; System.IO.FileStream rafc = raf; for (int bufNr = 0; bufNr < nrBuffers; bufNr++) { byte[] data = new byte[rafc.Length]; raf.Read(data, 0, (int) rafc.Length); int bufSize = (length > (bufferStart + maxBufSize))?maxBufSize:(int) (length - bufferStart); this.buffers[bufNr] = new System.IO.MemoryStream(data); this.bufSizes[bufNr] = bufSize; bufferStart += bufSize; } Seek(0L); } public override byte ReadByte() { // Performance might be improved by reading ahead into an array of // e.g. 128 bytes and readByte() from there. if (curAvail == 0) { curBufIndex++; if (curBufIndex >= buffers.Length) throw new System.IO.IOException("read past EOF"); curBuf = buffers[curBufIndex]; curBuf.Seek(0, System.IO.SeekOrigin.Begin); curAvail = bufSizes[curBufIndex]; } curAvail--; return (byte) curBuf.ReadByte(); } public override void ReadBytes(byte[] b, int offset, int len) { while (len > curAvail) { curBuf.Read(b, offset, curAvail); len -= curAvail; offset += curAvail; curBufIndex++; if (curBufIndex >= buffers.Length) throw new System.IO.IOException("read past EOF"); curBuf = buffers[curBufIndex]; curBuf.Seek(0, System.IO.SeekOrigin.Begin); curAvail = bufSizes[curBufIndex]; } curBuf.Read(b, offset, len); curAvail -= len; } public override long GetFilePointer() { return ((long) curBufIndex * maxBufSize) + curBuf.Position; } public override void Seek(long pos) { curBufIndex = (int) (pos / maxBufSize); curBuf = buffers[curBufIndex]; int bufOffset = (int) (pos - ((long) curBufIndex * maxBufSize)); curBuf.Seek(bufOffset, System.IO.SeekOrigin.Begin); curAvail = bufSizes[curBufIndex] - bufOffset; } public override long Length() { return length; } public override System.Object Clone() { MultiMMapIndexInput clone = (MultiMMapIndexInput) base.Clone(); clone.isClone = true; clone.buffers = new System.IO.MemoryStream[buffers.Length]; // No need to clone bufSizes. // Since most clones will use only one buffer, duplicate() could also be // done lazy in clones, e.g. when adapting curBuf. for (int bufNr = 0; bufNr < buffers.Length; bufNr++) { clone.buffers[bufNr] = buffers[bufNr]; // clone.buffers[bufNr] = buffers[bufNr].duplicate(); // {{Aroush-1.9}} how do we clone?! } try { clone.Seek(GetFilePointer()); } catch (System.IO.IOException ioe) { System.SystemException newException = new System.SystemException(ioe.Message, ioe); throw newException; } return clone; } public override void Close() { if (isClone || buffers == null) return ; try { for (int bufNr = 0; bufNr < buffers.Length; bufNr++) { // unmap the buffer (if enabled) and at least unset it for GC try { Enclosing_Instance.CleanMapping(buffers[bufNr]); } finally { buffers[bufNr] = null; } } } finally { buffers = null; } } } /// <summary>Creates an IndexInput for the file with the given name. </summary> public override IndexInput OpenInput(System.String name, int bufferSize) { EnsureOpen(); System.String path = System.IO.Path.Combine(GetDirectory().FullName, name); System.IO.FileStream raf = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read); try { return (raf.Length <= (long) maxBBuf)?(IndexInput) new MMapIndexInput(this, raf):(IndexInput) new MultiMMapIndexInput(this, raf, maxBBuf); } finally { raf.Close(); } } /// <summary>Creates an IndexOutput for the file with the given name. </summary> public override IndexOutput CreateOutput(System.String name) { InitOutput(name); return new SimpleFSDirectory.SimpleFSIndexOutput(new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name))); } static MMapDirectory() { { bool v; try { // {{Aroush-2.9 /* System.Type.GetType("sun.misc.Cleaner"); // {{Aroush-2.9}} port issue? System.Type.GetType("java.nio.DirectByteBuffer").GetMethod("cleaner", (NO_PARAM_TYPES == null)?new System.Type[0]:(System.Type[]) NO_PARAM_TYPES); */ System.Diagnostics.Debug.Fail("Port issue:", "sun.misc.Cleaner.clean()"); // {{Aroush-2.9}} // Aroush-2.9}} v = true; } catch (System.Exception e) { v = false; } UNMAP_SUPPORTED = v; } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Diagnostics; using System.Threading; using Mono.Collections.Generic; namespace Mono.Cecil { public struct CustomAttributeArgument { readonly TypeReference type; readonly object value; public TypeReference Type { get { return type; } } public object Value { get { return value; } } public CustomAttributeArgument (TypeReference type, object value) { Mixin.CheckType (type); this.type = type; this.value = value; } } public struct CustomAttributeNamedArgument { readonly string name; readonly CustomAttributeArgument argument; public string Name { get { return name; } } public CustomAttributeArgument Argument { get { return argument; } } public CustomAttributeNamedArgument (string name, CustomAttributeArgument argument) { Mixin.CheckName (name); this.name = name; this.argument = argument; } } public interface ICustomAttribute { TypeReference AttributeType { get; } bool HasFields { get; } bool HasProperties { get; } bool HasConstructorArguments { get; } Collection<CustomAttributeNamedArgument> Fields { get; } Collection<CustomAttributeNamedArgument> Properties { get; } Collection<CustomAttributeArgument> ConstructorArguments { get; } } [DebuggerDisplay ("{AttributeType}")] public sealed class CustomAttribute : ICustomAttribute { internal CustomAttributeValueProjection projection; readonly internal uint signature; internal bool resolved; MethodReference constructor; byte [] blob; internal Collection<CustomAttributeArgument> arguments; internal Collection<CustomAttributeNamedArgument> fields; internal Collection<CustomAttributeNamedArgument> properties; public MethodReference Constructor { get { return constructor; } set { constructor = value; } } public TypeReference AttributeType { get { return constructor.DeclaringType; } } public bool IsResolved { get { return resolved; } } public bool HasConstructorArguments { get { Resolve (); return !arguments.IsNullOrEmpty (); } } public Collection<CustomAttributeArgument> ConstructorArguments { get { Resolve (); if (arguments == null) Interlocked.CompareExchange (ref arguments, new Collection<CustomAttributeArgument> (), null); return arguments; } } public bool HasFields { get { Resolve (); return !fields.IsNullOrEmpty (); } } public Collection<CustomAttributeNamedArgument> Fields { get { Resolve (); if (fields == null) Interlocked.CompareExchange (ref fields, new Collection<CustomAttributeNamedArgument> (), null); return fields; } } public bool HasProperties { get { Resolve (); return !properties.IsNullOrEmpty (); } } public Collection<CustomAttributeNamedArgument> Properties { get { Resolve (); if (properties == null) Interlocked.CompareExchange (ref properties, new Collection<CustomAttributeNamedArgument> (), null); return properties; } } internal bool HasImage { get { return constructor != null && constructor.HasImage; } } internal ModuleDefinition Module { get { return constructor.Module; } } internal CustomAttribute (uint signature, MethodReference constructor) { this.signature = signature; this.constructor = constructor; this.resolved = false; } public CustomAttribute (MethodReference constructor) { this.constructor = constructor; this.resolved = true; } public CustomAttribute (MethodReference constructor, byte [] blob) { this.constructor = constructor; this.resolved = false; this.blob = blob; } public byte [] GetBlob () { if (blob != null) return blob; if (!HasImage) throw new NotSupportedException (); return Module.Read (ref blob, this, (attribute, reader) => reader.ReadCustomAttributeBlob (attribute.signature)); } void Resolve () { if (resolved || !HasImage) return; lock (Module.SyncRoot) { if (resolved) return; Module.Read (this, (attribute, reader) => { try { reader.ReadCustomAttributeSignature (attribute); resolved = true; } catch (ResolutionException) { if (arguments != null) arguments.Clear (); if (fields != null) fields.Clear (); if (properties != null) properties.Clear (); resolved = false; } }); } } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #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 Newtonsoft.Json.Utilities; using System.Diagnostics; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON property. /// </summary> public class JProperty : JContainer { private readonly List<JToken> _content = new List<JToken>(); private readonly string _name; /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _content; } } /// <summary> /// Gets the property name. /// </summary> /// <value>The property name.</value> public string Name { [DebuggerStepThrough] get { return _name; } } /// <summary> /// Gets or sets the property value. /// </summary> /// <value>The property value.</value> public JToken Value { [DebuggerStepThrough] get { return (_content.Count > 0) ? _content[0] : null; } set { CheckReentrancy(); JToken newValue = value ?? new JValue((object) null); if (_content.Count == 0) { InsertItem(0, newValue, false); } else { SetItem(0, newValue); } } } /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class from another <see cref="JProperty"/> object. /// </summary> /// <param name="other">A <see cref="JProperty"/> object to copy from.</param> public JProperty(JProperty other) : base(other) { _name = other.Name; } internal override JToken GetItem(int index) { if (index != 0) throw new ArgumentOutOfRangeException(); return Value; } internal override void SetItem(int index, JToken item) { if (index != 0) throw new ArgumentOutOfRangeException(); if (IsTokenUnchanged(Value, item)) return; if (Parent != null) ((JObject)Parent).InternalPropertyChanging(this); base.SetItem(0, item); if (Parent != null) ((JObject)Parent).InternalPropertyChanged(this); } internal override bool RemoveItem(JToken item) { throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override void RemoveItemAt(int index) { throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override void InsertItem(int index, JToken item, bool skipParentCheck) { if (Value != null) throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); base.InsertItem(0, item, false); } internal override bool ContainsItem(JToken item) { return (Value == item); } internal override void ClearItems() { throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override bool DeepEquals(JToken node) { JProperty t = node as JProperty; return (t != null && _name == t.Name && ContentsEqual(t)); } internal override JToken CloneToken() { return new JProperty(this); } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { [DebuggerStepThrough] get { return JTokenType.Property; } } internal JProperty(string name) { // called from JTokenWriter ValidationUtils.ArgumentNotNull(name, "name"); _name = name; } /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class. /// </summary> /// <param name="name">The property name.</param> /// <param name="content">The property content.</param> public JProperty(string name, params object[] content) : this(name, (object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class. /// </summary> /// <param name="name">The property name.</param> /// <param name="content">The property content.</param> public JProperty(string name, object content) { ValidationUtils.ArgumentNotNull(name, "name"); _name = name; Value = IsMultiContent(content) ? new JArray(content) : CreateFromContent(content); } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WritePropertyName(_name); JToken value = Value; if (value != null) value.WriteTo(writer, converters); else writer.WriteNull(); } internal override int GetDeepHashCode() { return _name.GetHashCode() ^ ((Value != null) ? Value.GetDeepHashCode() : 0); } /// <summary> /// Loads an <see cref="JProperty"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JProperty"/>.</param> /// <returns>A <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JProperty Load(JsonReader reader) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader."); } while (reader.TokenType == JsonToken.Comment) { reader.Read(); } if (reader.TokenType != JsonToken.PropertyName) throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JProperty p = new JProperty((string)reader.Value); p.SetLineInfo(reader as IJsonLineInfo); p.ReadTokenFrom(reader); return p; } } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using ServiceStack.Common; using ServiceStack.Redis; using ServiceStack.Text; namespace ServiceStack.ServiceInterface.Auth { public class RedisAuthRepository : IUserAuthRepository, IClearable { //http://stackoverflow.com/questions/3588623/c-sharp-regex-for-a-username-with-a-few-restrictions public Regex ValidUserNameRegEx = new Regex(@"^(?=.{3,15}$)([A-Za-z0-9][._-]?)*$", RegexOptions.Compiled); private readonly IRedisClientManagerFacade factory; public RedisAuthRepository(IRedisClientsManager factory) : this(new RedisClientManagerFacade(factory)) {} public RedisAuthRepository(IRedisClientManagerFacade factory) { this.factory = factory; } private string IndexUserAuthAndProviderIdsSet(long userAuthId) { return "urn:UserAuth>UserOAuthProvider:" + userAuthId; } private string IndexProviderToUserIdHash(string provider) { return "hash:ProviderUserId>OAuthProviderId:" + provider; } private string IndexUserNameToUserId { get { return "hash:UserAuth:UserName>UserId"; } } private string IndexEmailToUserId { get { return "hash:UserAuth:Email>UserId"; } } public UserAuth CreateUserAuth(UserAuth newUser, string password) { newUser.ThrowIfNull("newUser"); password.ThrowIfNullOrEmpty("password"); if (newUser.UserName.IsNullOrEmpty() && newUser.Email.IsNullOrEmpty()) throw new ArgumentNullException("UserName or Email is required"); if (!newUser.UserName.IsNullOrEmpty()) { if (!ValidUserNameRegEx.IsMatch(newUser.UserName)) throw new ArgumentException("UserName contains invalid characters", "UserName"); } using (var redis = factory.GetClient()) { var effectiveUserName = newUser.UserName ?? newUser.Email; var userAuth = GetUserAuthByUserName(redis, newUser.UserName); if (userAuth != null) throw new ArgumentException("User {0} already exists".Fmt(effectiveUserName)); var saltedHash = new SaltedHash(); string salt; string hash; saltedHash.GetHashAndSaltString(password, out hash, out salt); newUser.PasswordHash = hash; newUser.Salt = salt; newUser.Id = redis.As<UserAuth>().GetNextSequence(); if (!newUser.UserName.IsNullOrEmpty()) redis.SetEntryInHash(IndexUserNameToUserId, newUser.UserName, newUser.Id.ToString()); if (!newUser.Email.IsNullOrEmpty()) redis.SetEntryInHash(IndexEmailToUserId, newUser.Email, newUser.Id.ToString()); redis.Store(newUser); return newUser; } } public UserAuth GetUserAuthByUserName(string userNameOrEmail) { using (var redis = factory.GetClient()) { return GetUserAuthByUserName(redis, userNameOrEmail); } } private UserAuth GetUserAuthByUserName(IRedisClientFacade redis, string userNameOrEmail) { var isEmail = userNameOrEmail.Contains("@"); var userId = isEmail ? redis.GetValueFromHash(IndexEmailToUserId, userNameOrEmail) : redis.GetValueFromHash(IndexUserNameToUserId, userNameOrEmail); return userId == null ? null : redis.As<UserAuth>().GetById(userId); } public bool TryAuthenticate(string userName, string password, out string userId) { userId = null; var userAuth = GetUserAuthByUserName(userName); if (userAuth == null) return false; var saltedHash = new SaltedHash(); if (saltedHash.VerifyHashString(password, userAuth.PasswordHash, userAuth.Salt)) { userId = userAuth.Id.ToString(); return true; } return false; } public virtual void LoadUserAuth(IAuthSession session, IOAuthTokens tokens) { session.ThrowIfNull("session"); var userAuth = GetUserAuth(session, tokens); LoadUserAuth(session, userAuth); } private void LoadUserAuth(IAuthSession session, UserAuth userAuth) { if (userAuth == null) return; session.UserAuthId = userAuth.Id.ToString(); session.DisplayName = userAuth.DisplayName; session.FirstName = userAuth.FirstName; session.LastName = userAuth.LastName; session.Email = userAuth.Email; } private UserAuth GetUserAuth(IRedisClientFacade redis, string userAuthId) { long longId; if (userAuthId == null || !long.TryParse(userAuthId, out longId)) return null; return redis.As<UserAuth>().GetById(longId); } public UserAuth GetUserAuth(string userAuthId) { using (var redis = factory.GetClient()) return GetUserAuth(redis, userAuthId); } public void SaveUserAuth(IAuthSession authSession) { using (var redis = factory.GetClient()) { var userAuth = !authSession.UserAuthId.IsNullOrEmpty() ? GetUserAuth(redis, authSession.UserAuthId) : authSession.TranslateTo<UserAuth>(); if (userAuth.Id == default(int) && !authSession.UserAuthId.IsNullOrEmpty()) userAuth.Id = int.Parse(authSession.UserAuthId); redis.Store(userAuth); } } public void SaveUserAuth(UserAuth userAuth) { using (var redis = factory.GetClient()) redis.Store(userAuth); } public List<UserOAuthProvider> GetUserOAuthProviders(string userAuthId) { userAuthId.ThrowIfNullOrEmpty("userAuthId"); using (var redis = factory.GetClient()) { var idx = IndexUserAuthAndProviderIdsSet(long.Parse(userAuthId)); var authProiverIds = redis.GetAllItemsFromSet(idx); return redis.As<UserOAuthProvider>().GetByIds(authProiverIds).ToList(); } } public UserAuth GetUserAuth(IAuthSession authSession, IOAuthTokens tokens) { using (var redis = factory.GetClient()) return GetUserAuth(redis, authSession, tokens); } private UserAuth GetUserAuth(IRedisClientFacade redis, IAuthSession authSession, IOAuthTokens tokens) { if (!authSession.UserAuthId.IsNullOrEmpty()) { var userAuth = GetUserAuth(redis, authSession.UserAuthId); if (userAuth != null) return userAuth; } if (!authSession.UserName.IsNullOrEmpty()) { var userAuth = GetUserAuthByUserName(authSession.UserName); if (userAuth != null) return userAuth; } if (tokens == null || tokens.Provider.IsNullOrEmpty() || tokens.UserId.IsNullOrEmpty()) return null; var oAuthProviderId = GetAuthProviderByUserId(redis, tokens.Provider, tokens.UserId); if (!oAuthProviderId.IsNullOrEmpty()) { var oauthProvider = redis.As<UserOAuthProvider>().GetById(oAuthProviderId); if (oauthProvider != null) return redis.As<UserAuth>().GetById(oauthProvider.UserAuthId); } return null; } public string CreateOrMergeAuthSession(IAuthSession authSession, IOAuthTokens tokens) { using (var redis = factory.GetClient()) { UserOAuthProvider oAuthProvider = null; var oAuthProviderId = GetAuthProviderByUserId(redis, tokens.Provider, tokens.UserId); if (!oAuthProviderId.IsNullOrEmpty()) oAuthProvider = redis.As<UserOAuthProvider>().GetById(oAuthProviderId); var userAuth = GetUserAuth(redis, authSession, tokens) ?? new UserAuth { Id = redis.As<UserAuth>().GetNextSequence(), }; if (oAuthProvider == null) { oAuthProvider = new UserOAuthProvider { Id = redis.As<UserOAuthProvider>().GetNextSequence(), UserAuthId = userAuth.Id, Provider = tokens.Provider, UserId = tokens.UserId, }; var idx = IndexProviderToUserIdHash(tokens.Provider); redis.SetEntryInHash(idx, tokens.UserId, oAuthProvider.Id.ToString()); } oAuthProvider.PopulateMissing(tokens); userAuth.PopulateMissing(oAuthProvider); redis.Store(userAuth); redis.Store(oAuthProvider); redis.AddItemToSet(IndexUserAuthAndProviderIdsSet(userAuth.Id), oAuthProvider.Id.ToString()); return userAuth.Id.ToString(); } } private string GetAuthProviderByUserId(IRedisClientFacade redis, string provider, string userId) { var idx = IndexProviderToUserIdHash(provider); var oAuthProviderId = redis.GetValueFromHash(idx, userId); return oAuthProviderId; } public void Clear() { this.factory.Clear(); } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.MosaTypeSystem; using System; using System.Collections.Generic; using System.Diagnostics; namespace Mosa.Compiler.Framework { /// <summary> /// Performs memory layout of a type for compilation. /// </summary> public class MosaTypeLayout { #region Data members /// <summary> /// Holds a set of types /// </summary> private HashSet<MosaType> typeSet = new HashSet<MosaType>(); /// <summary> /// Holds a list of interfaces /// </summary> private List<MosaType> interfaces = new List<MosaType>(); /// <summary> /// Holds the method table offsets value for each method /// </summary> private Dictionary<MosaMethod, int> methodTableOffsets = new Dictionary<MosaMethod, int>(new MosaMethodFullNameComparer()); /// <summary> /// Holds the slot value for each interface /// </summary> private Dictionary<MosaType, int> interfaceSlots = new Dictionary<MosaType, int>(); /// <summary> /// Holds the size of each type /// </summary> private Dictionary<MosaType, int> typeSizes = new Dictionary<MosaType, int>(); /// <summary> /// Holds the size of each field /// </summary> private Dictionary<MosaField, int> fieldSizes = new Dictionary<MosaField, int>(); /// <summary> /// Holds the offset for each field /// </summary> private Dictionary<MosaField, int> fieldOffsets = new Dictionary<MosaField, int>(); /// <summary> /// Holds a list of methods for each type /// </summary> private Dictionary<MosaType, List<MosaMethod>> typeMethodTables = new Dictionary<MosaType, List<MosaMethod>>(); /// <summary> /// The method stack sizes /// </summary> private Dictionary<MosaMethod, int> methodStackSizes = new Dictionary<MosaMethod, int>(new MosaMethodFullNameComparer()); /// <summary> /// The method parameter stack sizes /// </summary> private Dictionary<MosaMethod, int> methodParameterStackSizes = new Dictionary<MosaMethod, int>(new MosaMethodFullNameComparer()); #endregion Data members #region Properties /// <summary> /// Gets the type system associated with this instance. /// </summary> /// <value>The type system.</value> public TypeSystem TypeSystem { get; private set; } /// <summary> /// Gets the size of the native pointer. /// </summary> /// <value>The size of the native pointer.</value> public int NativePointerSize { get; private set; } /// <summary> /// Gets the native pointer alignment. /// </summary> /// <value>The native pointer alignment.</value> public int NativePointerAlignment { get; private set; } /// <summary> /// Get a list of interfaces /// </summary> public IList<MosaType> Interfaces { get { return interfaces; } } #endregion Properties /// <summary> /// Initializes a new instance of the <see cref="MosaTypeLayout" /> class. /// </summary> /// <param name="typeSystem">The type system.</param> /// <param name="nativePointerSize">Size of the native pointer.</param> /// <param name="nativePointerAlignment">The native pointer alignment.</param> public MosaTypeLayout(TypeSystem typeSystem, int nativePointerSize, int nativePointerAlignment) { NativePointerAlignment = nativePointerAlignment; NativePointerSize = nativePointerSize; TypeSystem = typeSystem; Debug.Assert(nativePointerSize >= 4); ResolveLayouts(); } /// <summary> /// Gets the method table offset. /// </summary> /// <param name="method">The method.</param> /// <returns></returns> public int GetMethodTableOffset(MosaMethod method) { ResolveType(method.DeclaringType); return methodTableOffsets[method]; } /// <summary> /// Gets the interface slot offset. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public int GetInterfaceSlotOffset(MosaType type) { ResolveType(type); return interfaceSlots[type]; } /// <summary> /// Gets the size of the type. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public int GetTypeSize(MosaType type) { ResolveType(type); var size = 0; typeSizes.TryGetValue(type, out size); return size; } /// <summary> /// Gets the size of the field. /// </summary> /// <param name="field">The field.</param> /// <returns></returns> public int GetFieldSize(MosaField field) { var size = 0; //FIXME: This is not thread safe! if (fieldSizes.TryGetValue(field, out size)) { return size; } else { ResolveType(field.DeclaringType); } // If the field is another struct, we have to dig down and compute its size too. if (field.FieldType.IsValueType) { size = GetTypeSize(field.FieldType); } else { size = GetMemorySize(field.FieldType); } fieldSizes.Add(field, size); return size; } /// <summary> /// Gets the size of the field. /// </summary> /// <param name="field">The field.</param> /// <returns></returns> public int GetFieldOffset(MosaField field) { ResolveType(field.DeclaringType); var offset = 0; fieldOffsets.TryGetValue(field, out offset); return offset; } /// <summary> /// Gets the type methods. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public IList<MosaMethod> GetMethodTable(MosaType type) { if (type.IsModule) return null; if (type.BaseType == null && !type.IsInterface && type.FullName != "System.Object") // ghost types like generic params, function ptr, etc. return null; if (type.Modifier != null) // For types having modifiers, use the method table of element type instead. return GetMethodTable(type.ElementType); ResolveType(type); return typeMethodTables[type]; } /// <summary> /// Gets the interface table. /// </summary> /// <param name="type">The type.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public MosaMethod[] GetInterfaceTable(MosaType type, MosaType interfaceType) { if (type.Interfaces.Count == 0) return null; ResolveType(type); var methodTable = new MosaMethod[interfaceType.Methods.Count]; // Implicit Interface Methods for (int slot = 0; slot < interfaceType.Methods.Count; slot++) { methodTable[slot] = FindInterfaceMethod(type, interfaceType.Methods[slot]); } // Explicit Interface Methods ScanExplicitInterfaceImplementations(type, interfaceType, methodTable); return methodTable; } public bool IsCompoundType(MosaType type) { // i.e. whether copying of the type requires multiple move int? primitiveSize = type.GetPrimitiveSize(NativePointerSize); if (primitiveSize != null && primitiveSize > 8) return true; if (!type.IsUserValueType) return false; int typeSize = GetTypeSize(type); if (typeSize > NativePointerSize) return true; return false; } public void SetMethodStackSize(MosaMethod method, int size) { lock (methodStackSizes) { methodStackSizes.Remove(method); methodStackSizes.Add(method, size); } } public void SetMethodParameterStackSize(MosaMethod method, int size) { lock (methodParameterStackSizes) { methodParameterStackSizes.Remove(method); methodParameterStackSizes.Add(method, size); } } public int GetMethodStackSize(MosaMethod method) { var size = 0; lock (methodStackSizes) { if (!methodStackSizes.TryGetValue(method, out size)) { if ((method.MethodAttributes & MosaMethodAttributes.Abstract) == MosaMethodAttributes.Abstract) return 0; return 0; //throw new InvalidCompilerException(); } } return size; } public int GetMethodParameterStackSize(MosaMethod method) { var size = 0; lock (methodParameterStackSizes) { if (!methodParameterStackSizes.TryGetValue(method, out size)) { if ((method.MethodAttributes & MosaMethodAttributes.Abstract) == MosaMethodAttributes.Abstract) return 0; return 0; //throw new InvalidCompilerException(); } } return size; } #region Internal - Layout private void ResolveLayouts() { // Enumerate all types and do an appropriate type layout foreach (var type in TypeSystem.AllTypes) { ResolveType(type); } } private void ResolveType(MosaType type) { if (type.IsModule) return; if (type.BaseType == null && !type.IsInterface && type.FullName != "System.Object") // ghost types like generic params, function ptr, etc. return; if (type.Modifier != null) // For types having modifiers, resolve the element type instead. { ResolveType(type.ElementType); return; } // FIXME: This is not threadsafe!!!!! if (typeSet.Contains(type)) return; typeSet.Add(type); if (type.BaseType != null) { ResolveType(type.BaseType); } if (type.IsInterface) { ResolveInterfaceType(type); CreateMethodTable(type); return; } foreach (var interfaceType in type.Interfaces) { ResolveInterfaceType(interfaceType); } int? size = type.GetPrimitiveSize(NativePointerSize); if (size != null) { typeSizes[type] = size.Value; } else if (type.IsExplicitLayout) { ComputeExplicitLayout(type); } else { ComputeSequentialLayout(type); } CreateMethodTable(type); } /// <summary> /// Builds a list of interfaces and assigns interface a unique index number /// </summary> /// <param name="type">The type.</param> private void ResolveInterfaceType(MosaType type) { Debug.Assert(type.IsInterface); if (type.IsModule) return; if (interfaces.Contains(type)) return; interfaces.Add(type); interfaceSlots.Add(type, interfaceSlots.Count); } private void ComputeSequentialLayout(MosaType type) { Debug.Assert(type != null, @"No type given."); if (typeSizes.ContainsKey(type)) return; // Instance size int typeSize = 0; // Receives the size/alignment int packingSize = type.PackingSize ?? NativePointerAlignment; if (type.BaseType != null) { if (!type.IsValueType) { typeSize = GetTypeSize(type.BaseType); } } foreach (MosaField field in type.Fields) { if (!field.IsStatic) { // Set the field address fieldOffsets.Add(field, typeSize); int fieldSize = GetFieldSize(field); typeSize += fieldSize; // Pad the field in the type if (packingSize != 0) { int padding = (packingSize - (typeSize % packingSize)) % packingSize; typeSize += padding; } } } typeSizes.Add(type, typeSize); } /// <summary> /// Applies the explicit layout to the given type. /// </summary> /// <param name="type">The type.</param> private void ComputeExplicitLayout(MosaType type) { Debug.Assert(type != null, @"No type given."); //Debug.Assert(type.BaseType.LayoutSize != 0, @"Type size not set for explicit layout."); int size = 0; foreach (MosaField field in type.Fields) { if (field.Offset == null) continue; int offset = (int)field.Offset.Value; fieldOffsets.Add(field, offset); size = Math.Max(size, offset + GetFieldSize(field)); // Explicit layout assigns a physical offset from the start of the structure // to the field. We just assign this offset. Debug.Assert(fieldSizes[field] != 0, @"Non-static field doesn't have layout!"); } typeSizes.Add(type, (type.ClassSize == null || type.ClassSize == -1) ? size : (int)type.ClassSize); } #endregion Internal - Layout #region Internal - Interface private void ScanExplicitInterfaceImplementations(MosaType type, MosaType interfaceType, MosaMethod[] methodTable) { foreach (var method in type.Methods) { foreach (var overrideTarget in method.Overrides) { // Get clean name for overrideTarget var cleanOverrideTargetName = GetCleanMethodName(overrideTarget.Name); int slot = 0; foreach (var interfaceMethod in interfaceType.Methods) { // Get clean name for interfaceMethod var cleanInterfaceMethodName = GetCleanMethodName(interfaceMethod.Name); // Check that the signatures match, the types and the names if (overrideTarget.Equals(interfaceMethod) && overrideTarget.DeclaringType.Equals(interfaceType) && cleanOverrideTargetName.Equals(cleanInterfaceMethodName)) { methodTable[slot] = method; } slot++; } } } } private MosaMethod FindInterfaceMethod(MosaType type, MosaMethod interfaceMethod) { MosaMethod methodFound = null; if (type.BaseType != null) { methodFound = FindImplicitInterfaceMethod(type.BaseType, interfaceMethod); } var cleanInterfaceMethodName = GetCleanMethodName(interfaceMethod.Name); foreach (var method in type.Methods) { if (IsExplicitInterfaceMethod(method.FullName) && methodFound != null) continue; string cleanMethodName = GetCleanMethodName(method.Name); if (cleanInterfaceMethodName.Equals(cleanMethodName)) { if (interfaceMethod.Equals(method)) { return method; } } } if (type.BaseType != null) { methodFound = FindInterfaceMethod(type.BaseType, interfaceMethod); } if (methodFound != null) return methodFound; throw new InvalidOperationException(@"Failed to find implicit interface implementation for type " + type + " and interface method " + interfaceMethod); } private MosaMethod FindImplicitInterfaceMethod(MosaType type, MosaMethod interfaceMethod) { MosaMethod methodFound = null; var cleanInterfaceMethodName = GetCleanMethodName(interfaceMethod.Name); foreach (var method in type.Methods) { if (IsExplicitInterfaceMethod(method.FullName)) continue; string cleanMethodName = GetCleanMethodName(method.Name); if (cleanInterfaceMethodName.Equals(cleanMethodName)) { if (interfaceMethod.Equals(method)) { return method; } } } if (type.BaseType != null) { methodFound = FindImplicitInterfaceMethod(type.BaseType, interfaceMethod); } return methodFound; } private string GetCleanMethodName(string fullName) { if (!fullName.Contains(".")) return fullName; return fullName.Substring(fullName.LastIndexOf(".") + 1); } private bool IsExplicitInterfaceMethod(string fullname) { if (fullname.Contains(":")) fullname = fullname.Substring(fullname.LastIndexOf(":") + 1); return fullname.Contains("."); } #endregion Internal - Interface #region Internal private List<MosaMethod> CreateMethodTable(MosaType type) { List<MosaMethod> methodTable; if (typeMethodTables.TryGetValue(type, out methodTable)) { return methodTable; } methodTable = GetMethodTableFromBaseType(type); foreach (var method in type.Methods) { if (method.IsVirtual) { if (method.IsNewSlot) { int slot = methodTable.Count; methodTable.Add(method); methodTableOffsets.Add(method, slot); } else { int slot = FindOverrideSlot(methodTable, method); if (slot != -1) { methodTable[slot] = method; methodTableOffsets.Add(method, slot); } else { slot = methodTable.Count; methodTable.Add(method); methodTableOffsets.Add(method, slot); } } } else { if (method.IsStatic && method.IsRTSpecialName) { int slot = methodTable.Count; methodTable.Add(method); methodTableOffsets.Add(method, slot); } else if (!method.IsInternal && method.ExternMethod == null) { int slot = methodTable.Count; methodTable.Add(method); methodTableOffsets.Add(method, slot); } } } typeMethodTables.Add(type, methodTable); return methodTable; } private List<MosaMethod> GetMethodTableFromBaseType(MosaType type) { var methodTable = new List<MosaMethod>(); if (type.BaseType != null) { List<MosaMethod> baseMethodTable; if (!typeMethodTables.TryGetValue(type.BaseType, out baseMethodTable)) { // Method table for the base type has not been create yet, so create it now baseMethodTable = CreateMethodTable(type.BaseType); } methodTable = new List<MosaMethod>(baseMethodTable); } return methodTable; } private int FindOverrideSlot(IList<MosaMethod> methodTable, MosaMethod method) { int slot = -1; foreach (var baseMethod in methodTable) { if (baseMethod.Name.Equals(method.Name) && baseMethod.Equals(method)) { if (baseMethod.GenericArguments.Count == 0) return methodTableOffsets[baseMethod]; else slot = methodTableOffsets[baseMethod]; } } if (slot >= 0) // non generic methods are more exact return slot; //throw new InvalidOperationException(@"Failed to find override method slot."); return -1; } /// <summary> /// Gets the type memory requirements. /// </summary> /// <param name="type">The signature type.</param> /// <returns></returns> private int GetMemorySize(MosaType type) { Debug.Assert(!type.IsValueType); return NativePointerSize; } #endregion Internal } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// A collection of metadata entries that can be exchanged during a call. /// gRPC supports these types of metadata: /// <list type="bullet"> /// <item><term>Request headers</term><description>are sent by the client at the beginning of a remote call before any request messages are sent.</description></item> /// <item><term>Response headers</term><description>are sent by the server at the beginning of a remote call handler before any response messages are sent.</description></item> /// <item><term>Response trailers</term><description>are sent by the server at the end of a remote call along with resulting call status.</description></item> /// </list> /// </summary> public sealed class Metadata : IList<Metadata.Entry> { /// <summary> /// All binary headers should have this suffix. /// </summary> public const string BinaryHeaderSuffix = "-bin"; /// <summary> /// An read-only instance of metadata containing no entries. /// </summary> public static readonly Metadata Empty = new Metadata().Freeze(); /// <summary> /// To be used in initial metadata to request specific compression algorithm /// for given call. Direct selection of compression algorithms is an internal /// feature and is not part of public API. /// </summary> internal const string CompressionRequestAlgorithmMetadataKey = "grpc-internal-encoding-request"; readonly List<Entry> entries; bool readOnly; /// <summary> /// Initializes a new instance of <c>Metadata</c>. /// </summary> public Metadata() { this.entries = new List<Entry>(); } /// <summary> /// Makes this object read-only. /// </summary> /// <returns>this object</returns> internal Metadata Freeze() { this.readOnly = true; return this; } // TODO: add support for access by key #region IList members /// <summary> /// <see cref="T:IList`1"/> /// </summary> public int IndexOf(Metadata.Entry item) { return entries.IndexOf(item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void Insert(int index, Metadata.Entry item) { GrpcPreconditions.CheckNotNull(item); CheckWriteable(); entries.Insert(index, item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void RemoveAt(int index) { CheckWriteable(); entries.RemoveAt(index); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public Metadata.Entry this[int index] { get { return entries[index]; } set { GrpcPreconditions.CheckNotNull(value); CheckWriteable(); entries[index] = value; } } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void Add(Metadata.Entry item) { GrpcPreconditions.CheckNotNull(item); CheckWriteable(); entries.Add(item); } /// <summary> /// Adds a new ASCII-valued metadata entry. See <c>Metadata.Entry</c> constructor for params. /// </summary> public void Add(string key, string value) { Add(new Entry(key, value)); } /// <summary> /// Adds a new binary-valued metadata entry. See <c>Metadata.Entry</c> constructor for params. /// </summary> public void Add(string key, byte[] valueBytes) { Add(new Entry(key, valueBytes)); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void Clear() { CheckWriteable(); entries.Clear(); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public bool Contains(Metadata.Entry item) { return entries.Contains(item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void CopyTo(Metadata.Entry[] array, int arrayIndex) { entries.CopyTo(array, arrayIndex); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public int Count { get { return entries.Count; } } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public bool IsReadOnly { get { return readOnly; } } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public bool Remove(Metadata.Entry item) { CheckWriteable(); return entries.Remove(item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public IEnumerator<Metadata.Entry> GetEnumerator() { return entries.GetEnumerator(); } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return entries.GetEnumerator(); } private void CheckWriteable() { GrpcPreconditions.CheckState(!readOnly, "Object is read only"); } #endregion /// <summary> /// Metadata entry /// </summary> public class Entry { readonly string key; readonly string value; readonly byte[] valueBytes; private Entry(string key, string value, byte[] valueBytes) { this.key = key; this.value = value; this.valueBytes = valueBytes; } /// <summary> /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with a binary value. /// </summary> /// <param name="key">Metadata key. Gets converted to lowercase. Needs to have suffix indicating a binary valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens and dots.</param> /// <param name="valueBytes">Value bytes.</param> public Entry(string key, byte[] valueBytes) { this.key = NormalizeKey(key); GrpcPreconditions.CheckArgument(HasBinaryHeaderSuffix(this.key), "Key for binary valued metadata entry needs to have suffix indicating binary value."); this.value = null; GrpcPreconditions.CheckNotNull(valueBytes, "valueBytes"); this.valueBytes = new byte[valueBytes.Length]; Buffer.BlockCopy(valueBytes, 0, this.valueBytes, 0, valueBytes.Length); // defensive copy to guarantee immutability } /// <summary> /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with an ASCII value. /// </summary> /// <param name="key">Metadata key. Gets converted to lowercase. Must not use suffix indicating a binary valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens and dots.</param> /// <param name="value">Value string. Only ASCII characters are allowed.</param> public Entry(string key, string value) { this.key = NormalizeKey(key); GrpcPreconditions.CheckArgument(!HasBinaryHeaderSuffix(this.key), "Key for ASCII valued metadata entry cannot have suffix indicating binary value."); this.value = GrpcPreconditions.CheckNotNull(value, "value"); this.valueBytes = null; } /// <summary> /// Gets the metadata entry key. /// </summary> public string Key { get { return this.key; } } /// <summary> /// Gets the binary value of this metadata entry. /// </summary> public byte[] ValueBytes { get { if (valueBytes == null) { return MarshalUtils.GetBytesASCII(value); } // defensive copy to guarantee immutability var bytes = new byte[valueBytes.Length]; Buffer.BlockCopy(valueBytes, 0, bytes, 0, valueBytes.Length); return bytes; } } /// <summary> /// Gets the string value of this metadata entry. /// </summary> public string Value { get { GrpcPreconditions.CheckState(!IsBinary, "Cannot access string value of a binary metadata entry"); return value ?? MarshalUtils.GetStringASCII(valueBytes); } } /// <summary> /// Returns <c>true</c> if this entry is a binary-value entry. /// </summary> public bool IsBinary { get { return value == null; } } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="Grpc.Core.Metadata.Entry"/>. /// </summary> public override string ToString() { if (IsBinary) { return string.Format("[Entry: key={0}, valueBytes={1}]", key, valueBytes); } return string.Format("[Entry: key={0}, value={1}]", key, value); } /// <summary> /// Gets the serialized value for this entry. For binary metadata entries, this leaks /// the internal <c>valueBytes</c> byte array and caller must not change contents of it. /// </summary> internal byte[] GetSerializedValueUnsafe() { return valueBytes ?? MarshalUtils.GetBytesASCII(value); } /// <summary> /// Creates a binary value or ascii value metadata entry from data received from the native layer. /// We trust C core to give us well-formed data, so we don't perform any checks or defensive copying. /// </summary> internal static Entry CreateUnsafe(string key, byte[] valueBytes) { if (HasBinaryHeaderSuffix(key)) { return new Entry(key, null, valueBytes); } return new Entry(key, MarshalUtils.GetStringASCII(valueBytes), null); } private static string NormalizeKey(string key) { GrpcPreconditions.CheckNotNull(key, "key"); GrpcPreconditions.CheckArgument(IsValidKey(key, out bool isLowercase), "Metadata entry key not valid. Keys can only contain lowercase alphanumeric characters, underscores, hyphens and dots."); if (isLowercase) { // save allocation of a new string if already lowercase return key; } return key.ToLowerInvariant(); } private static bool IsValidKey(string input, out bool isLowercase) { isLowercase = true; for (int i = 0; i < input.Length; i++) { char c = input[i]; if ('a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '.' || c == '_' || c == '-' ) continue; if ('A' <= c && c <= 'Z') { isLowercase = false; continue; } return false; } return true; } /// <summary> /// Returns <c>true</c> if the key has "-bin" binary header suffix. /// </summary> private static bool HasBinaryHeaderSuffix(string key) { // We don't use just string.EndsWith because its implementation is extremely slow // on CoreCLR and we've seen significant differences in gRPC benchmarks caused by it. // See https://github.com/dotnet/coreclr/issues/5612 int len = key.Length; if (len >= 4 && key[len - 4] == '-' && key[len - 3] == 'b' && key[len - 2] == 'i' && key[len - 1] == 'n') { return true; } return false; } } } }
/* * Copyright 2011 The Poderosa Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * $Id: SCPClient.cs,v 1.2 2012/05/05 12:42:45 kzmi Exp $ */ using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Diagnostics; using System.IO; using System.Globalization; using System.Text.RegularExpressions; using Granados.SSH1; using Granados.SSH2; using Granados.IO; using Granados.IO.SSH2; using Granados.Util; using Granados.Poderosa.FileTransfer; namespace Granados.Poderosa.SCP { /// <summary> /// Statuses of the file transfer /// </summary> public enum SCPFileTransferStatus { /// <summary>Not started</summary> None, /// <summary>Creating a local or remote directory</summary> CreateDirectory, /// <summary>Created a local or remote directory</summary> DirectoryCreated, /// <summary>Opening remote or local file</summary> Open, /// <summary>Data is transmitting</summary> Transmitting, /// <summary>File was closed successfully</summary> CompletedSuccess, /// <summary>File transfer was aborted by cancellation</summary> CompletedAbort, } /// <summary> /// Delegate notifies progress of the file transfer. /// </summary> /// <param name="localFullPath">Full path of the local file or local directory.</param> /// <param name="fileName">Name of the file or directory.</param> /// <param name="status">Status of the file transfer.</param> /// <param name="fileSize">File size. Zero if target is a directory.</param> /// <param name="transmitted">Transmitted data length. Zero if target is a directory.</param> public delegate void SCPFileTransferProgressDelegate( string localFullPath, string fileName, SCPFileTransferStatus status, ulong fileSize, ulong transmitted); /// <summary> /// SCP Client /// </summary> /// /// <remarks> /// <para>This class is designed to be used in the worker thread.</para> /// <para>Each method blocks thread while transmitting the files.</para> /// </remarks> public class SCPClient { #region Private classes /// <summary> /// File or directory entry to create. /// Used in sink mode. /// </summary> private class SCPEntry { public readonly bool IsDirectory; public readonly int Permissions; public readonly long FileSize; public readonly string Name; public SCPEntry(bool isDirectory, int permissions, long fileSize, string name) { IsDirectory = isDirectory; Permissions = permissions; FileSize = fileSize; Name = name; } } /// <summary> /// Time modification informations. /// Used in sink mode. /// </summary> private class SCPModTime { public readonly DateTime MTime; public readonly DateTime ATime; public SCPModTime(DateTime mtime, DateTime atime) { MTime = mtime; ATime = atime; } } #endregion #region Private fields private readonly SSHConnection _connection; private Encoding _encoding = Encoding.UTF8; private int _defaultFilePermissions = 0x1a4; // 0644 private int _defaultDirectoryPermissions = 0x1ed; // 0755 private int _protocolTimeout = 5000; private static readonly byte[] ZERO = new byte[] { 0 }; private static readonly DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0); #endregion #region Private constants private const int FILE_TRANSFER_BLOCK_SIZE = 10240; // FIXME: should it be flexible ? private const byte LF = 0xa; #endregion #region Properties /// <summary> /// Protocol timeout in milliseconds. /// </summary> public int ProtocolTimeout { get { return _protocolTimeout; } set { _protocolTimeout = value; } } /// <summary> /// Gets or sets encoding to convert path name or file name. /// </summary> public Encoding Encoding { get { return _encoding; } set { _encoding = value; } } /// <summary> /// Unix permissions used when creating a remote file. /// </summary> public int DefaultFilePermissions { get { return _defaultFilePermissions; } set { _defaultFilePermissions = value; } } /// <summary> /// Unix permissions used when creating a remote directory. /// </summary> public int DefaultDirectoryPermissions { get { return _defaultDirectoryPermissions; } set { _defaultDirectoryPermissions = value; } } #endregion #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="connection">SSH connection. Currently only SSH2 connection is accepted.</param> public SCPClient(SSHConnection connection) { this._connection = connection; } #endregion #region Upload /// <summary> /// Upload files or directories. /// </summary> /// <remarks> /// <para>Unfortunately, Granados sends a command line in the ASCII encoding. /// So the "remotePath" must be an ASCII text.</para> /// </remarks> /// <param name="localPath">Local path (Windows' path)</param> /// <param name="remotePath">Remote path (Unix path)</param> /// <param name="recursive">Specifies recursive mode</param> /// <param name="preserveTime">Specifies to preserve time of the directory or file.</param> /// <param name="cancellation">An object to request the cancellation. Set null if the cancellation is not needed.</param> /// <param name="progressDelegate">Delegate to notify progress. Set null if notification is not needed.</param> public void Upload(string localPath, string remotePath, bool recursive, bool preserveTime, Cancellation cancellation, SCPFileTransferProgressDelegate progressDelegate) { if (!IsAscii(remotePath)) throw new SCPClientException("Remote path must consist of ASCII characters."); bool isDirectory = Directory.Exists(localPath); if (!File.Exists(localPath) && !isDirectory) throw new SCPClientException("File or directory not found: " + localPath); if (isDirectory && !recursive) throw new SCPClientException("Cannot copy directory in non-recursive mode"); string absLocalPath = Path.GetFullPath(localPath); string command = "scp -t "; if (recursive) command += "-r "; if (preserveTime) command += "-p "; command += EscapeUnixPath(remotePath); using (SCPChannelStream stream = new SCPChannelStream()) { stream.Open(_connection, command, _protocolTimeout); CheckResponse(stream); if (isDirectory) { // implies recursive mode UploadDirectory(absLocalPath, stream, preserveTime, cancellation, progressDelegate); } else { UploadFile(absLocalPath, stream, preserveTime, cancellation, progressDelegate); } } } private bool UploadDirectory(string fullPath, SCPChannelStream stream, bool preserveTime, Cancellation cancellation, SCPFileTransferProgressDelegate progressDelegate) { Debug.Assert(fullPath != null); if (cancellation != null && cancellation.IsRequested) { return false; // cancel } string directoryName = Path.GetFileName(fullPath); if (directoryName != null) { // not a root directory if (progressDelegate != null) progressDelegate(fullPath, directoryName, SCPFileTransferStatus.CreateDirectory, 0, 0); if (preserveTime) { SendModTime( stream, Directory.GetLastWriteTimeUtc(fullPath), Directory.GetLastAccessTimeUtc(fullPath) ); } string line = new StringBuilder() .Append('D') .Append(GetPermissionsText(true)) .Append(" 0 ") .Append(directoryName) .Append('\n') .ToString(); stream.Write(_encoding.GetBytes(line)); CheckResponse(stream); if (progressDelegate != null) progressDelegate(fullPath, directoryName, SCPFileTransferStatus.DirectoryCreated, 0, 0); } foreach (String fullSubDirPath in Directory.GetDirectories(fullPath)) { bool continued = UploadDirectory(fullSubDirPath, stream, preserveTime, cancellation, progressDelegate); if (!continued) return false; // cancel } foreach (String fullFilePath in Directory.GetFiles(fullPath)) { bool continued = UploadFile(fullFilePath, stream, preserveTime, cancellation, progressDelegate); if (!continued) return false; // cancel } if (directoryName != null) { // not a root directory string line = "E\n"; stream.Write(_encoding.GetBytes(line)); CheckResponse(stream); } return true; // continue } private bool UploadFile(string fullPath, SCPChannelStream stream, bool preserveTime, Cancellation cancellation, SCPFileTransferProgressDelegate progressDelegate) { Debug.Assert(fullPath != null); string fileName = Path.GetFileName(fullPath); FileInfo fileInfo = new FileInfo(fullPath); long fileSize = fileInfo.Length; ulong transmitted = 0; if (progressDelegate != null) progressDelegate(fullPath, fileName, SCPFileTransferStatus.Open, (ulong)fileSize, transmitted); if (preserveTime) { SendModTime( stream, File.GetLastWriteTimeUtc(fullPath), File.GetLastAccessTimeUtc(fullPath) ); } using (FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { string line = new StringBuilder() .Append('C') .Append(GetPermissionsText(false)) .Append(' ') .Append(fileSize.ToString(NumberFormatInfo.InvariantInfo)) .Append(' ') .Append(fileName) .Append('\n') .ToString(); stream.Write(_encoding.GetBytes(line)); CheckResponse(stream); byte[] buff = new byte[FILE_TRANSFER_BLOCK_SIZE]; long remain = fileSize; while (remain > 0) { if (cancellation != null && cancellation.IsRequested) { if (progressDelegate != null) progressDelegate(fullPath, fileName, SCPFileTransferStatus.CompletedAbort, (ulong)fileSize, transmitted); return false; // cancel } int readLength = fileStream.Read(buff, 0, buff.Length); if (readLength <= 0) break; if (readLength > remain) readLength = (int)remain; stream.Write(buff, readLength); remain -= readLength; transmitted += (ulong)readLength; if (progressDelegate != null) progressDelegate(fullPath, fileName, SCPFileTransferStatus.Transmitting, (ulong)fileSize, transmitted); } stream.Write(ZERO); CheckResponse(stream); } if (progressDelegate != null) progressDelegate(fullPath, fileName, SCPFileTransferStatus.CompletedSuccess, (ulong)fileSize, transmitted); return true; } private void SendModTime(SCPChannelStream stream, DateTime mtime, DateTime atime) { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0); long mtimeSec = (mtime.Ticks - epoch.Ticks) / 10000000L; long mtimeUSec = ((mtime.Ticks - epoch.Ticks) % 10000000L) / 10L; long atimeSec = (atime.Ticks - epoch.Ticks) / 10000000L; long atimeUSec = ((atime.Ticks - epoch.Ticks) % 10000000L) / 10L; string line = new StringBuilder() .Append('T') .Append(mtimeSec.ToString(NumberFormatInfo.InvariantInfo)) .Append(' ') .Append(mtimeUSec.ToString(NumberFormatInfo.InvariantInfo)) .Append(' ') .Append(atimeSec.ToString(NumberFormatInfo.InvariantInfo)) .Append(' ') .Append(atimeUSec.ToString(NumberFormatInfo.InvariantInfo)) .Append('\n') .ToString(); stream.Write(_encoding.GetBytes(line)); CheckResponse(stream); } #endregion #region Download /// <summary> /// Download files or directories. /// </summary> /// <remarks> /// <para>Unfortunately, Granados sends a command line in the ASCII encoding. /// So the "remotePath" must be an ASCII text.</para> /// </remarks> /// <param name="remotePath">Remote path (Unix path)</param> /// <param name="localPath">Local path (Windows' path)</param> /// <param name="recursive">Specifies recursive mode</param> /// <param name="preserveTime">Specifies to preserve time of the directory or file.</param> /// <param name="cancellation">An object to request the cancellation. Set null if the cancellation is not needed.</param> /// <param name="progressDelegate">Delegate to notify progress. Set null if notification is not needed.</param> public void Download(string remotePath, string localPath, bool recursive, bool preserveTime, Cancellation cancellation, SCPFileTransferProgressDelegate progressDelegate) { if (!IsAscii(remotePath)) throw new SCPClientException("Remote path must consist of ASCII characters."); string absLocalPath = Path.GetFullPath(localPath); string command = "scp -f "; if (recursive) command += "-r "; if (preserveTime) command += "-p "; command += EscapeUnixPath(remotePath); string localBasePath = null; // local directory to store SCPModTime modTime = null; Stack<string> localBasePathStack = new Stack<string>(); using (SCPChannelStream stream = new SCPChannelStream()) { stream.Open(_connection, command, _protocolTimeout); stream.Write(ZERO); while (true) { byte[] lineBytes = stream.ReadUntil(LF, _protocolTimeout); if (lineBytes[0] == 1 || lineBytes[0] == 2) { // Warning or Error string message = _encoding.GetString(lineBytes, 1, lineBytes.Length - 2); throw new SCPClientException(message); } if (lineBytes[0] == 0x43 /*'C'*/ || lineBytes[0] == 0x44 /*'D'*/) { SCPEntry entry; try { entry = ParseEntry(lineBytes); } catch (Exception e) { SendError(stream, e.Message); throw; } if (entry.IsDirectory) { string directoryPath = DeterminePathToCreate(localBasePath, absLocalPath, entry); bool continued = CreateDirectory(stream, directoryPath, modTime, cancellation, progressDelegate); if (!continued) break; modTime = null; localBasePathStack.Push(localBasePath); localBasePath = directoryPath; } else { string filePath = DeterminePathToCreate(localBasePath, absLocalPath, entry); bool continued = CreateFile(stream, filePath, entry, modTime, cancellation, progressDelegate); if (!continued) break; modTime = null; if (!recursive) break; } } else if (lineBytes[0] == 0x54 /*'T'*/) { if (preserveTime) { try { modTime = ParseModTime(lineBytes); } catch (Exception e) { SendError(stream, e.Message); throw; } } stream.Write(ZERO); } else if (lineBytes[0] == 0x45 /*'E'*/) { if (localBasePathStack.Count > 0) { localBasePath = localBasePathStack.Pop(); if (localBasePath == null) break; } stream.Write(ZERO); } else { SendError(stream, "Invalid control"); throw new SCPClientException("Invalid control"); } } } } private string DeterminePathToCreate(string localBasePath, string initialLocalPath, SCPEntry entry) { Debug.Assert(initialLocalPath != null); if (localBasePath == null) { // first creation // use initialLocalPath if (Directory.Exists(initialLocalPath)) return Path.Combine(initialLocalPath, entry.Name); else return initialLocalPath; } else { return Path.Combine(localBasePath, entry.Name); } } private bool CreateDirectory(SCPChannelStream stream, string directoryPath, SCPModTime modTime, Cancellation cancellation, SCPFileTransferProgressDelegate progressDelegate) { if (cancellation != null && cancellation.IsRequested) { return false; // cancel } string directoryName = Path.GetFileName(directoryPath); if (progressDelegate != null) progressDelegate(directoryPath, directoryName, SCPFileTransferStatus.CreateDirectory, 0, 0); if (!Directory.Exists(directoryPath)) { // skip if already exists try { Directory.CreateDirectory(directoryPath); } catch (Exception e) { SendError(stream, "failed to create a directory"); throw new SCPClientException("Failed to create a directory: " + directoryPath, e); } } if (modTime != null) { try { Directory.SetLastWriteTimeUtc(directoryPath, modTime.MTime); Directory.SetLastAccessTimeUtc(directoryPath, modTime.ATime); } catch (Exception e) { SendError(stream, "failed to modify time of a directory"); throw new SCPClientException("Failed to modify time of a directory: " + directoryPath, e); } } stream.Write(ZERO); if (progressDelegate != null) progressDelegate(directoryPath, directoryName, SCPFileTransferStatus.DirectoryCreated, 0, 0); return true; } private bool CreateFile(SCPChannelStream stream, string filePath, SCPEntry entry, SCPModTime modTime, Cancellation cancellation, SCPFileTransferProgressDelegate progressDelegate) { string fileName = Path.GetFileName(filePath); ulong transmitted = 0; if (progressDelegate != null) progressDelegate(filePath, fileName, SCPFileTransferStatus.Open, (ulong)entry.FileSize, transmitted); FileStream fileStream; try { fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read); } catch (Exception e) { SendError(stream, "failed to create a file"); throw new SCPClientException("Failed to create a file: " + filePath, e); } stream.Write(ZERO); using (fileStream) { byte[] buff = new byte[FILE_TRANSFER_BLOCK_SIZE]; long remain = entry.FileSize; try { while (remain > 0) { if (cancellation != null && cancellation.IsRequested) { if (progressDelegate != null) progressDelegate(filePath, fileName, SCPFileTransferStatus.CompletedAbort, (ulong)entry.FileSize, transmitted); return false; // cancel } int maxLength = (int)Math.Min((long)buff.Length, remain); int readLength = stream.Read(buff, maxLength, _protocolTimeout); fileStream.Write(buff, 0, readLength); remain -= readLength; transmitted += (ulong)readLength; if (progressDelegate != null) progressDelegate(filePath, fileName, SCPFileTransferStatus.Transmitting, (ulong)entry.FileSize, transmitted); } } catch (Exception e) { SendError(stream, "failed to write to a file"); throw new SCPClientException("Failed to write to a file: " + filePath, e); } } if (modTime != null) { try { File.SetLastWriteTimeUtc(filePath, modTime.MTime); File.SetLastAccessTimeUtc(filePath, modTime.ATime); } catch (Exception e) { SendError(stream, "failed to modify time of a file"); throw new SCPClientException("Failed to modify time of a file: " + filePath, e); } } CheckResponse(stream); stream.Write(ZERO); if (progressDelegate != null) progressDelegate(filePath, fileName, SCPFileTransferStatus.CompletedSuccess, (ulong)entry.FileSize, transmitted); return true; } private Regex _regexEntry = new Regex("^([CD])([0-7]+) +([0-9]+) +(.+)$"); private Regex _regexModTime = new Regex("^T([0-9]+) +([0-9]+) +([0-9]+) +([0-9]+)$"); private SCPEntry ParseEntry(byte[] lineData) { string line = _encoding.GetString(lineData, 0, lineData.Length - 1); Match m = _regexEntry.Match(line); if (!m.Success) throw new SCPClientException("Unknown entry: " + line); bool isDirectory = (m.Groups[1].Value == "D"); int permissions = 0; foreach (char c in m.Groups[2].Value.ToCharArray()) { permissions = (permissions << 3) | ((int)c - (int)'0'); } long fileSize = Int64.Parse(m.Groups[3].Value); string name = m.Groups[4].Value; return new SCPEntry(isDirectory, permissions, fileSize, name); } private SCPModTime ParseModTime(byte[] lineData) { string line = _encoding.GetString(lineData, 0, lineData.Length - 1); Match m = _regexModTime.Match(line); if (!m.Success) throw new SCPClientException("Unknown format: " + line); long mtimeSec = Int64.Parse(m.Groups[1].Value); long mtimeUSec = Int64.Parse(m.Groups[2].Value); long atimeSec = Int64.Parse(m.Groups[3].Value); long atimeUSec = Int64.Parse(m.Groups[4].Value); DateTime mtime = new DateTime(EPOCH.Ticks + mtimeSec * 10000000L + mtimeUSec * 10); DateTime atime = new DateTime(EPOCH.Ticks + atimeSec * 10000000L + atimeUSec * 10); return new SCPModTime(mtime, atime); } private void SendError(SCPChannelStream stream, string message) { message = "Poderosa: " + message.Replace('\n', ' '); byte[] messageBytes = _encoding.GetBytes(message); byte[] data = new byte[messageBytes.Length + 2]; data[0] = 1; Buffer.BlockCopy(messageBytes, 0, data, 1, messageBytes.Length); data[messageBytes.Length + 1] = LF; stream.Write(data); } #endregion #region Other private methods /// <summary> /// Read a byte and check the status code. /// </summary> /// <param name="stream">Channel stream</param> /// <exception cref="SCPClientException">Response was a warning or an error.</exception> private void CheckResponse(SCPChannelStream stream) { byte response = stream.ReadByte(_protocolTimeout); if (response == 0) { // OK return; } if (response == 1 || response == 2) { // Warning or Error // followed by a message which is terminated by LF byte[] messageData = stream.ReadUntil(LF, _protocolTimeout); string message = _encoding.GetString(messageData, 0, messageData.Length - 1); throw new SCPClientException(message); } throw new SCPClientException("Invalid response"); } private string GetPermissionsText(bool isDirectory) { int perm = isDirectory ? _defaultDirectoryPermissions : _defaultFilePermissions; return new StringBuilder() .Append("01234567"[(perm >> 9) & 0x7]) .Append("01234567"[(perm >> 6) & 0x7]) .Append("01234567"[(perm >> 3) & 0x7]) .Append("01234567"[perm & 0x7]) .ToString(); } private string EscapeUnixPath(string path) { return Regex.Replace(path, @"[\\\][{}()<>|'"" ]", @"\$0"); } private bool IsAscii(string s) { for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c < '\u0020' || c > '\u007e') return false; } return true; } #endregion } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel { using System; using System.ComponentModel; using System.Configuration; using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Configuration; using System.Xml; public class BasicHttpBinding : HttpBindingBase { WSMessageEncoding messageEncoding = BasicHttpBindingDefaults.MessageEncoding; BasicHttpSecurity basicHttpSecurity; public BasicHttpBinding() : this(BasicHttpSecurityMode.None) { } public BasicHttpBinding(string configurationName) : base() { this.Initialize(); this.ApplyConfiguration(configurationName); } public BasicHttpBinding(BasicHttpSecurityMode securityMode) : base() { this.Initialize(); this.basicHttpSecurity.Mode = securityMode; } BasicHttpBinding(BasicHttpSecurity security) : base() { this.Initialize(); this.basicHttpSecurity = security; } [DefaultValue(WSMessageEncoding.Text)] public WSMessageEncoding MessageEncoding { get { return messageEncoding; } set { messageEncoding = value; } } public BasicHttpSecurity Security { get { return this.basicHttpSecurity; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } this.basicHttpSecurity = value; } } [Obsolete(HttpChannelUtilities.ObsoleteDescriptionStrings.PropertyObsoleteUseAllowCookies, false)] [EditorBrowsable(EditorBrowsableState.Never)] public bool EnableHttpCookieContainer { get { return this.AllowCookies; } set { this.AllowCookies = value; } } internal override BasicHttpSecurity BasicHttpSecurity { get { return this.basicHttpSecurity; } } // check that properties of the HttpTransportBindingElement and // MessageEncodingBindingElement not exposed as properties on BasicHttpBinding // match default values of the binding elements bool IsBindingElementsMatch(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding) { if (this.MessageEncoding == WSMessageEncoding.Text) { if (!this.TextMessageEncodingBindingElement.IsMatch(encoding)) return false; } else if (this.MessageEncoding == WSMessageEncoding.Mtom) { if (!this.MtomMessageEncodingBindingElement.IsMatch(encoding)) return false; } if (!this.GetTransport().IsMatch(transport)) return false; return true; } internal override EnvelopeVersion GetEnvelopeVersion() { return EnvelopeVersion.Soap11; } internal override void InitializeFrom(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding) { base.InitializeFrom(transport, encoding); // BasicHttpBinding only supports Text and Mtom encoding if (encoding is TextMessageEncodingBindingElement) { this.MessageEncoding = WSMessageEncoding.Text; } else if (encoding is MtomMessageEncodingBindingElement) { messageEncoding = WSMessageEncoding.Mtom; } } void ApplyConfiguration(string configurationName) { BasicHttpBindingCollectionElement section = BasicHttpBindingCollectionElement.GetBindingCollectionElement(); BasicHttpBindingElement element = section.Bindings[configurationName]; if (element == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException( SR.GetString(SR.ConfigInvalidBindingConfigurationName, configurationName, ConfigurationStrings.BasicHttpBindingCollectionElementName))); } else { element.ApplyConfiguration(this); } } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingParameterCollection parameters) { if ((this.BasicHttpSecurity.Mode == BasicHttpSecurityMode.Transport || this.BasicHttpSecurity.Mode == BasicHttpSecurityMode.TransportCredentialOnly) && this.BasicHttpSecurity.Transport.ClientCredentialType == HttpClientCredentialType.InheritedFromHost) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.HttpClientCredentialTypeInvalid, this.BasicHttpSecurity.Transport.ClientCredentialType))); } return base.BuildChannelFactory<TChannel>(parameters); } public override BindingElementCollection CreateBindingElements() { this.CheckSettings(); // return collection of BindingElements BindingElementCollection bindingElements = new BindingElementCollection(); // order of BindingElements is important // add security (*optional) SecurityBindingElement wsSecurity = this.BasicHttpSecurity.CreateMessageSecurity(); if (wsSecurity != null) { bindingElements.Add(wsSecurity); } // add encoding (text or mtom) WSMessageEncodingHelper.SyncUpEncodingBindingElementProperties(this.TextMessageEncodingBindingElement, this.MtomMessageEncodingBindingElement); if (this.MessageEncoding == WSMessageEncoding.Text) bindingElements.Add(this.TextMessageEncodingBindingElement); else if (this.MessageEncoding == WSMessageEncoding.Mtom) bindingElements.Add(this.MtomMessageEncodingBindingElement); // add transport (http or https) bindingElements.Add(this.GetTransport()); return bindingElements.Clone(); } internal static bool TryCreate(BindingElementCollection elements, out Binding binding) { binding = null; if (elements.Count > 3) return false; SecurityBindingElement securityElement = null; MessageEncodingBindingElement encoding = null; HttpTransportBindingElement transport = null; foreach (BindingElement element in elements) { if (element is SecurityBindingElement) securityElement = element as SecurityBindingElement; else if (element is TransportBindingElement) transport = element as HttpTransportBindingElement; else if (element is MessageEncodingBindingElement) encoding = element as MessageEncodingBindingElement; else return false; } HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement; if ( ( securityElement != null ) && ( httpsTransport != null ) && ( httpsTransport.RequireClientCertificate != TransportDefaults.RequireClientCertificate ) ) { return false; } // process transport binding element UnifiedSecurityMode mode; HttpTransportSecurity transportSecurity = new HttpTransportSecurity(); if (!GetSecurityModeFromTransport(transport, transportSecurity, out mode)) return false; if (encoding == null) return false; // BasicHttpBinding only supports Soap11 if (!encoding.CheckEncodingVersion(EnvelopeVersion.Soap11)) return false; BasicHttpSecurity security; if (!TryCreateSecurity(securityElement, mode, transportSecurity, out security)) return false; BasicHttpBinding basicHttpBinding = new BasicHttpBinding(security); basicHttpBinding.InitializeFrom(transport, encoding); // make sure all our defaults match if (!basicHttpBinding.IsBindingElementsMatch(transport, encoding)) return false; binding = basicHttpBinding; return true; } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeSecurity() { return this.Security.InternalShouldSerialize(); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeEnableHttpCookieContainer() { return false; } void Initialize() { this.basicHttpSecurity = new BasicHttpSecurity(); } } }
namespace Shopify.Tests { using System.Collections.Generic; using NUnit.Framework; using Shopify.Unity; using Shopify.Unity.GraphQL; using System.Text.RegularExpressions; using Shopify.Unity.SDK; [TestFixture] public class TestShopify { [SetUp] public void Setup() { #if (SHOPIFY_TEST) ShopifyBuy.Reset(); #endif } [Test] public void TestInit() { Assert.IsNull(ShopifyBuy.Client()); Assert.IsNull(ShopifyBuy.Client("domain.com")); ShopifyBuy.Init("AccessToken", "domain.com"); Assert.IsNotNull(ShopifyBuy.Client()); Assert.IsNotNull(ShopifyBuy.Client("domain.com")); Assert.AreEqual(ShopifyBuy.Client(), ShopifyBuy.Client("domain.com")); Assert.AreEqual("domain.com", ShopifyBuy.Client().Domain); Assert.AreEqual("AccessToken", ShopifyBuy.Client().AccessToken); } [Test] public void TestUpdateLocale() { ShopifyBuy.Init("AccessToken", "domain.com"); Assert.IsNull(ShopifyBuy.Client().Locale); ShopifyBuy.Client("domain.com").UpdateLocale("fr"); Assert.AreEqual("fr", ShopifyBuy.Client("domain.com").Locale); } [Test] public void CannotInitTwiceUsingDomain() { ShopifyBuy.Init("AccessToken", "domain2.com"); ShopifyClient client1 = ShopifyBuy.Client("domain2.com"); ShopifyBuy.Init("AccessToken", "domain2.com"); ShopifyClient client2 = ShopifyBuy.Client("domain2.com"); Assert.IsNotNull(client1); Assert.AreSame(client1, client2); } [Test] public void CannotInitTwiceUsingLoader() { ShopifyBuy.Init(new MockLoader()); ShopifyClient client1 = ShopifyBuy.Client("graphql.myshopify.com"); ShopifyBuy.Init(new MockLoader()); ShopifyClient client2 = ShopifyBuy.Client("graphql.myshopify.com"); Assert.IsNotNull(client1); Assert.AreSame(client1, client2); } [Test] public void TestGenericQuery() { ShopifyBuy.Init(new MockLoader()); QueryRoot response = null; ShopifyBuy.Client().Query( (q) => q.shop(s => s .name() ), (data, error) => { response = data; Assert.IsNull(error); } ); Assert.AreEqual("this is the test shop yo", response.shop().name()); } [Test] public void TestGenericMutation() { ShopifyBuy.Init(new MockLoader()); Mutation response = null; ShopifyBuy.Client().Mutation( (q) => q.customerAccessTokenCreate((a) => a .customerAccessToken(at => at .accessToken() ), input: new CustomerAccessTokenCreateInput("some@email.com", "password") ), (data, error) => { response = data; Assert.IsNull(error); } ); Assert.AreEqual("i am a token", response.customerAccessTokenCreate().customerAccessToken().accessToken()); } [Test] public void TestProducts() { List<Product> products = null; ShopifyBuy.Init(new MockLoader()); ShopifyBuy.Client().products(callback: (p, error, after) => { products = p; Assert.IsNull(error); Assert.AreEqual((DefaultQueries.MaxProductPageSize - 1).ToString(), after); }); Assert.AreEqual(DefaultQueries.MaxProductPageSize, products.Count); Assert.AreEqual("Product0", products[0].title()); Assert.AreEqual("Product1", products[1].title()); Assert.AreEqual(1, products[0].images().edges().Count, "First product has one image"); Assert.AreEqual(1, products[0].variants().edges().Count, "First product has one variant"); Assert.AreEqual(1, products[0].collections().edges().Count, "First product has one collection"); Assert.AreEqual(2 * MockLoader.PageSize, products[1].images().edges().Count, "Second product has 2 pages of images"); Assert.AreEqual(1, products[1].variants().edges().Count, "Second product has 1 variant"); Assert.AreEqual(1, products[1].collections().edges().Count, "Second product has one collection"); Assert.AreEqual(3 * MockLoader.PageSize, products[2].images().edges().Count, "Third page has 3 pages of images"); Assert.AreEqual(2 * MockLoader.PageSize, products[2].variants().edges().Count, "Third page has 2 pages of variants"); Assert.AreEqual(1, products[1].collections().edges().Count, "Third product has one collection"); } [Test] public void TestProductsFirst() { List<Product> products = null; ShopifyBuy.Init(new MockLoader()); ShopifyBuy.Client().products(callback: (p, error, after) => { products = p; Assert.IsNull(error); Assert.AreEqual((DefaultQueries.MaxProductPageSize - 1).ToString(), after); }, first: DefaultQueries.MaxProductPageSize); Assert.AreEqual(DefaultQueries.MaxProductPageSize, products.Count); } [Test] public void TestCollections() { List<Collection> collections = null; ShopifyBuy.Init(new MockLoader()); ShopifyBuy.Client().collections(callback: (c, error, after) => { collections = c; Assert.IsNull(error); Assert.AreEqual((DefaultQueries.MaxCollectionsPageSize - 1).ToString(), after); }); Assert.AreEqual(DefaultQueries.MaxCollectionsPageSize, collections.Count); Assert.AreEqual("I am collection 0", collections[0].title()); Assert.AreEqual("I am collection 1", collections[1].title()); Assert.AreEqual(2 * MockLoader.PageSize, collections[0].products().edges().Count, "First collection has products"); Assert.AreEqual(1, collections[1].products().edges().Count, "Second collection has one product"); } [Test] public void TestCollectionsFirst() { List<Collection> collections = null; ShopifyBuy.Init(new MockLoader()); ShopifyBuy.Client().collections(callback: (c, error, after) => { collections = c; Assert.IsNull(error); Assert.AreEqual((DefaultQueries.MaxCollectionsPageSize - 1).ToString(), after); }, first: DefaultQueries.MaxCollectionsPageSize); Assert.AreEqual(DefaultQueries.MaxCollectionsPageSize, collections.Count); } [Test] public void TestProductsAfter() { List<Product> products = null; ShopifyBuy.Init(new MockLoader()); ShopifyBuy.Client().products(callback: (p, error, after) => { products = p; Assert.IsNull(error); Assert.AreEqual((DefaultQueries.MaxProductPageSize * 2 - 1).ToString(), after); }, first: DefaultQueries.MaxProductPageSize, after: (DefaultQueries.MaxProductPageSize - 1).ToString()); Assert.AreEqual(DefaultQueries.MaxProductPageSize, products.Count); Assert.AreEqual(DefaultQueries.MaxProductPageSize.ToString(), products[0].id()); Assert.AreEqual((DefaultQueries.MaxProductPageSize * 2 - 1).ToString(), products[products.Count - 1].id()); } [Test] public void TestGraphQLError() { ShopifyBuy.Init(new MockLoader()); // when after is set to 3 MockLoader will return a graphql error ShopifyBuy.Client().products(callback: (p, error, after) => { Assert.IsNull(p); Assert.IsNotNull(error); Assert.IsNull(after); Assert.AreEqual("[\"GraphQL error from mock loader\"]", error.Description); }, first: 250, after: "666"); } [Test] public void TestHttpError() { ShopifyBuy.Init(new MockLoader()); // when after is set to 404 MockLoader loader will return an httpError ShopifyBuy.Client().products(callback: (p, error, after) => { Assert.IsNull(p); Assert.IsNotNull(error); Assert.IsNull(after); Assert.AreEqual("404 from mock loader", error.Description); }, first: 250, after: "404"); } [Test] public void TestHasVersionNumber() { Regex version = new Regex(@"\d+\.\d+\.\d+"); Assert.IsTrue(version.IsMatch(VersionInformation.VERSION)); } [Test] public void TestHasVersionNumberWithPublishDestination() { Regex version = new Regex(@"^\d+\.\d+\.\d+(-github|-asset-store)$"); Assert.IsTrue(version.IsMatch(VersionInformation.VERSION)); } [Test] public void TestProductsByIds() { ShopifyBuy.Init(new MockLoader()); List<Product> products = null; List<string> ids = new List<string>(); ids.Add("productId333"); ids.Add("productId444"); ShopifyBuy.Client().products((p, error) => { products = p; Assert.IsNull(error); }, ids); Assert.AreEqual(2, products.Count); Assert.AreEqual("productId333", products[0].id()); Assert.AreEqual("productId444", products[1].id()); Assert.AreEqual(1, products[0].images().edges().Count); } } }
// Date.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System.Globalization; using System.Runtime.CompilerServices; namespace System { /// <summary> /// Equivalent to the Date type in Javascript, but emulates value-type semantics by removing all mutators. /// </summary> [IgnoreNamespace] [Imported(ObeysTypeSystem = true)] [ScriptName("Date")] public struct DateTime : IComparable<DateTime>, IEquatable<DateTime>, IFormattable { /// <summary> /// Creates a new instance of Date initialized from the specified number of milliseconds. /// </summary> /// <param name="milliseconds">Milliseconds since January 1st, 1970.</param> [AlternateSignature] public DateTime(long milliseconds) { } /// <summary> /// Creates a new instance of Date initialized from parsing the specified date. /// </summary> /// <param name="date"></param> [AlternateSignature] public DateTime(string date) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (1 through 12)</param> /// <param name="day">The day of the month (1 through # of days in the specified month)</param> [InlineCode("new {$System.DateTime}({year}, {month} - 1, {day})")] public DateTime(int year, int month, int day) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (1 through 12)</param> /// <param name="day">The day of the month (1 through # of days in the specified month)</param> /// <param name="hours">The hours (0 through 23)</param> [InlineCode("new {$System.DateTime}({year}, {month} - 1, {day}, {hours})")] public DateTime(int year, int month, int day, int hours) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (1 through 12)</param> /// <param name="day">The day of the month (1 through # of days in the specified month)</param> /// <param name="hours">The hours (0 through 23)</param> /// <param name="minutes">The minutes (0 through 59)</param> [InlineCode("new {$System.DateTime}({year}, {month} - 1, {day}, {hours}, {minutes})")] public DateTime(int year, int month, int day, int hours, int minutes) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (1 through 12)</param> /// <param name="day">The day of the month (1 through # of days in the specified month)</param> /// <param name="hours">The hours (0 through 23)</param> /// <param name="minutes">The minutes (0 through 59)</param> /// <param name="seconds">The seconds (0 through 59)</param> [InlineCode("new {$System.DateTime}({year}, {month} - 1, {day}, {hours}, {minutes}, {seconds})")] public DateTime(int year, int month, int day, int hours, int minutes, int seconds) { } /// <summary> /// Creates a new instance of Date. /// </summary> /// <param name="year">The full year.</param> /// <param name="month">The month (1 through 12)</param> /// <param name="day">The day of the month (1 through # of days in the specified month)</param> /// <param name="hours">The hours (0 through 23)</param> /// <param name="minutes">The minutes (0 through 59)</param> /// <param name="seconds">The seconds (0 through 59)</param> /// <param name="milliseconds">The milliseconds (0 through 999)</param> [InlineCode("new {$System.DateTime}({year}, {month} - 1, {day}, {hours}, {minutes}, {seconds}, {milliseconds})")] public DateTime(int year, int month, int day, int hours, int minutes, int seconds, int milliseconds) { } /// <summary> /// Returns the current date and time. /// </summary> public static DateTime Now { [InlineCode("new Date()")] get { return default(DateTime); } } /// <summary> /// Returns the current date and time according to UTC /// </summary> public static DateTime UtcNow { [InlineCode("{$System.Script}.utcNow()")] get { return default(DateTime); } } /// <summary> /// Gets the current date. /// </summary> /// <returns> /// An object that is set to today's date, with the time component set to 00:00:00. /// </returns> public static DateTime Today { [InlineCode("{$System.Script}.today()")] get { return default(DateTime); } } [InlineCode("{$System.Script}.formatDate({this}, {format})")] public string Format(string format) { return null; } [InlineCode("{$System.Script}.formatDate({this}, {format})")] public string ToString(string format) { return null; } public int GetDate() { return 0; } public int GetDay() { return 0; } public int GetFullYear() { return 0; } public int GetHours() { return 0; } public int GetMilliseconds() { return 0; } public int GetMinutes() { return 0; } [InlineCode("{this}.getMonth() + 1")] public int GetMonth() { return 0; } public int GetSeconds() { return 0; } public long GetTime() { return 0; } public int GetTimezoneOffset() { return 0; } [ScriptName("getUTCDate")] public int GetUtcDate() { return 0; } [ScriptName("getUTCDay")] public int GetUtcDay() { return 0; } [ScriptName("getUTCFullYear")] public int GetUtcFullYear() { return 0; } [ScriptName("getUTCHours")] public int GetUtcHours() { return 0; } [ScriptName("getUTCMilliseconds")] public int GetUtcMilliseconds() { return 0; } [ScriptName("getUTCMinutes")] public int GetUtcMinutes() { return 0; } [InlineCode("{this}.getUTCMonth() + 1")] public int GetUtcMonth() { return 0; } [ScriptName("getUTCSeconds")] public int GetUtcSeconds() { return 0; } [InlineCode("{$System.Script}.localeFormatDate({this}, {format})")] public string LocaleFormat(string format) { return null; } [InlineCode("new Date(Date.parse({value}))")] public static DateTime Parse(string value) { return default(DateTime); } [InlineCode("{$System.Script}.parseExactDate({value}, {format})")] public static DateTime? ParseExact(string value, string format) { return null; } [InlineCode("{$System.Script}.parseExactDate({value}, {format}, {provider})")] public static DateTime? ParseExact(string value, string format, IFormatProvider provider) { return null; } [InlineCode("{$System.Script}.parseExactDateUTC({value}, {format})")] public static DateTime? ParseExactUtc(string value, string format) { return null; } [InlineCode("{$System.Script}.parseExactDateUTC({value}, {format}, {provider})")] public static DateTime? ParseExactUtc(string value, string format, IFormatProvider provider) { return null; } public string ToDateString() { return null; } public string ToLocaleDateString() { return null; } public string ToLocaleTimeString() { return null; } public string ToTimeString() { return null; } [ScriptName("toUTCString")] public string ToUtcString() { return null; } public long ValueOf() { return 0; } [InlineCode("new Date(Date.UTC({year}, {month} - 1, {day}))")] public static DateTime FromUtc(int year, int month, int day) { return default(DateTime); } [InlineCode("new Date(Date.UTC({year}, {month} - 1, {day}, {hours}))")] public static DateTime FromUtc(int year, int month, int day, int hours) { return default(DateTime); } [InlineCode("new Date(Date.UTC({year}, {month} - 1, {day}, {hours}, {minutes}))")] public static DateTime FromUtc(int year, int month, int day, int hours, int minutes) { return default(DateTime); } [InlineCode("new Date(Date.UTC({year}, {month} - 1, {day}, {hours}, {minutes}, {seconds}))")] public static DateTime FromUtc(int year, int month, int day, int hours, int minutes, int seconds) { return default(DateTime); } [InlineCode("new Date(Date.UTC({year}, {month} - 1, {day}, {hours}, {minutes}, {seconds}, {milliseconds}))")] public static DateTime FromUtc(int year, int month, int day, int hours, int minutes, int seconds, int milliseconds) { return default(DateTime); } [InlineCode("Date.UTC({year}, {month} - 1, {day})")] public static int Utc(int year, int month, int day) { return 0; } [InlineCode("Date.UTC({year}, {month} - 1, {day}, {hours})")] public static int Utc(int year, int month, int day, int hours) { return 0; } [InlineCode("Date.UTC({year}, {month} - 1, {day}, {hours}, {minutes})")] public static int Utc(int year, int month, int day, int hours, int minutes) { return 0; } [InlineCode("Date.UTC({year}, {month} - 1, {day}, {hours}, {minutes}, {seconds})")] public static int Utc(int year, int month, int day, int hours, int minutes, int seconds) { return 0; } [InlineCode("Date.UTC({year}, {month} - 1, {day}, {hours}, {minutes}, {seconds}, {milliseconds})")] public static int Utc(int year, int month, int day, int hours, int minutes, int seconds, int milliseconds) { return 0; } // NOTE: There is no + operator since in JavaScript that returns the // concatenation of the date strings, which is pretty much useless. /// <summary> /// Returns the difference in milliseconds between two dates. /// </summary> [IntrinsicOperator] public static int operator -(DateTime a, DateTime b) { return 0; } [InlineCode("new {$System.TimeSpan}(({this} - {value}) * 10000)")] public TimeSpan Subtract(DateTime value) { return default(TimeSpan); } [InlineCode("{$System.Script}.staticEquals({a}, {b})")] public static bool AreEqual(DateTime? a, DateTime? b) { return false; } [InlineCode("!{$System.Script}.staticEquals({a}, {b})")] public static bool AreNotEqual(DateTime? a, DateTime? b) { return false; } [InlineCode("{$System.Script}.staticEquals({a}, {b})")] public static bool operator==(DateTime a, DateTime b) { return false; } [InlineCode("{$System.Script}.staticEquals({a}, {b})")] public static bool operator==(DateTime? a, DateTime b) { return false; } [InlineCode("{$System.Script}.staticEquals({a}, {b})")] public static bool operator==(DateTime a, DateTime? b) { return false; } [InlineCode("{$System.Script}.staticEquals({a}, {b})")] public static bool operator==(DateTime? a, DateTime? b) { return false; } [InlineCode("!{$System.Script}.staticEquals({a}, {b})")] public static bool operator!=(DateTime a, DateTime b) { return false; } [InlineCode("!{$System.Script}.staticEquals({a}, {b})")] public static bool operator!=(DateTime? a, DateTime b) { return false; } [InlineCode("!{$System.Script}.staticEquals({a}, {b})")] public static bool operator!=(DateTime a, DateTime? b) { return false; } [InlineCode("!{$System.Script}.staticEquals({a}, {b})")] public static bool operator!=(DateTime? a, DateTime? b) { return false; } /// <summary> /// Compares two dates /// </summary> [IntrinsicOperator] public static bool operator <(DateTime a, DateTime b) { return false; } /// <summary> /// Compares two dates /// </summary> [IntrinsicOperator] public static bool operator >(DateTime a, DateTime b) { return false; } /// <summary> /// Compares two dates /// </summary> [IntrinsicOperator] public static bool operator <=(DateTime a, DateTime b) { return false; } /// <summary> /// Compares two dates /// </summary> [IntrinsicOperator] public static bool operator >=(DateTime a, DateTime b) { return false; } /// <summary> /// Converts a DateTime to a JsDate. Returns a copy of the immutable datetime. /// </summary> [InlineCode("new Date({dt}.valueOf())")] public static explicit operator DateTime(JsDate dt) { return default(DateTime); } /// <summary> /// Converts a JsDate to a DateTime. Returns a copy of the mutable datetime. /// </summary> [InlineCode("new Date({dt}.valueOf())")] public static explicit operator JsDate(DateTime dt) { return null; } /// <summary> /// Gets the date component of this instance. /// </summary> /// <returns> /// A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00). /// </returns> public DateTime Date { [InlineCode("new Date({this}.getFullYear(), {this}.getMonth(), {this}.getDate())")] get { return default(DateTime); } } /// <summary> /// Gets the day of the month represented by this instance. /// </summary> /// <returns> /// The day component, expressed as a value between 1 and 31. /// </returns> /// <filterpriority>1</filterpriority> public int Day { [ScriptName("getDate")] get { return 0; } } /// <summary> /// Gets the day of the week represented by this instance. /// </summary> /// <returns> /// An enumerated constant that indicates the day of the week of this <see cref="T:System.DateTime"/> value. /// </returns> public DayOfWeek DayOfWeek { [ScriptName("getDay")] get { return 0; } } /// <summary> /// Gets the day of the year represented by this instance. /// </summary> /// <returns> /// The day of the year, expressed as a value between 1 and 366. /// </returns> public int DayOfYear { [InlineCode("Math.ceil(({this} - new Date({this}.getFullYear(), 0, 1)) / 86400000)")] get { return 0; } } /// <summary> /// Gets the hour component of the date represented by this instance. /// </summary> /// <returns> /// The hour component, expressed as a value between 0 and 23. /// </returns> public int Hour { [ScriptName("getHours")] get { return 0; } } /// <summary> /// Gets the milliseconds component of the date represented by this instance. /// </summary> /// <returns> /// The milliseconds component, expressed as a value between 0 and 999. /// </returns> public int Millisecond { [ScriptName("getMilliseconds")] get { return 0; } } /// <summary> /// Gets the minute component of the date represented by this instance. /// </summary> /// <returns> /// The minute component, expressed as a value between 0 and 59. /// </returns> public int Minute { [ScriptName("getMinutes")] get { return 0; } } /// <summary> /// Gets the month component of the date represented by this instance. /// </summary> /// <returns> /// The month component, expressed as a value between 1 and 12. /// </returns> public int Month { [InlineCode("{this}.getMonth() + 1")] get { return 0; } } /// <summary> /// Gets the seconds component of the date represented by this instance. /// </summary> /// <returns> /// The seconds component, expressed as a value between 0 and 59. /// </returns> public int Second { [ScriptName("getSeconds")] get { return 0; } } /// <summary> /// Gets the year component of the date represented by this instance. /// </summary> /// <returns> /// The year, between 1 and 9999. /// </returns> public int Year { [ScriptName("getFullYear")] get { return 0; } } /// <summary> /// Returns a new <see cref="T:System.DateTime"/> that adds the specified number of days to the value of this instance. /// </summary> /// <returns> /// An object whose value is the sum of the date and time represented by this instance and the number of days represented by <paramref name="value"/>. /// </returns> /// <param name="value">A number of whole and fractional days. The <paramref name="value"/> parameter can be negative or positive. </param> [InlineCode("new Date({this}.valueOf() + Math.round({value} * 86400000))")] public DateTime AddDays(double value) { return default(DateTime); } /// <summary> /// Returns a new <see cref="T:System.DateTime"/> that adds the specified number of hours to the value of this instance. /// </summary> /// <returns> /// An object whose value is the sum of the date and time represented by this instance and the number of hours represented by <paramref name="value"/>. /// </returns> /// <param name="value">A number of whole and fractional hours. The <paramref name="value"/> parameter can be negative or positive. </param> [InlineCode("new Date({this}.valueOf() + Math.round({value} * 3600000))")] public DateTime AddHours(double value) { return default(DateTime); } /// <summary> /// Returns a new <see cref="T:System.DateTime"/> that adds the specified number of milliseconds to the value of this instance. /// </summary> /// <returns> /// An object whose value is the sum of the date and time represented by this instance and the number of milliseconds represented by <paramref name="value"/>. /// </returns> /// <param name="value">A number of whole and fractional milliseconds. The <paramref name="value"/> parameter can be negative or positive. Note that this value is rounded to the nearest integer.</param> [InlineCode("new Date({this}.valueOf() + Math.round({value}))")] public DateTime AddMilliseconds(double value) { return default(DateTime); } /// <summary> /// Returns a new <see cref="T:System.DateTime"/> that adds the specified number of minutes to the value of this instance. /// </summary> /// <returns> /// An object whose value is the sum of the date and time represented by this instance and the number of minutes represented by <paramref name="value"/>. /// </returns> /// <param name="value">A number of whole and fractional minutes. The <paramref name="value"/> parameter can be negative or positive. </param> [InlineCode("new Date({this}.valueOf() + Math.round({value} * 60000))")] public DateTime AddMinutes(double value) { return default(DateTime); } /// <summary> /// Returns a new <see cref="T:System.DateTime"/> that adds the specified number of months to the value of this instance. /// </summary> /// <returns> /// An object whose value is the sum of the date and time represented by this instance and <paramref name="months"/>. /// </returns> /// <param name="months">A number of months. The <paramref name="months"/> parameter can be negative or positive. </param> [InlineCode("new Date({this}.getFullYear(), {this}.getMonth() + {months}, {this}.getDate(), {this}.getHours(), {this}.getMinutes(), {this}.getSeconds(), {this}.getMilliseconds())")] public DateTime AddMonths(int months) { return default(DateTime); } /// <summary> /// Returns a new <see cref="T:System.DateTime"/> that adds the specified number of seconds to the value of this instance. /// </summary> /// <returns> /// An object whose value is the sum of the date and time represented by this instance and the number of seconds represented by <paramref name="value"/>. /// </returns> /// <param name="value">A number of whole and fractional seconds. The <paramref name="value"/> parameter can be negative or positive. </param> [InlineCode("new Date({this}.valueOf() + Math.round({value} * 1000))")] public DateTime AddSeconds(double value) { return default(DateTime); } /// <summary> /// Returns a new <see cref="T:System.DateTime"/> that adds the specified number of years to the value of this instance. /// </summary> /// <returns> /// An object whose value is the sum of the date and time represented by this instance and the number of years represented by <paramref name="value"/>. /// </returns> /// <param name="value">A number of years. The <paramref name="value"/> parameter can be negative or positive. </param> [InlineCode("new Date({this}.getFullYear() + {value}, {this}.getMonth(), {this}.getDate(), {this}.getHours(), {this}.getMinutes(), {this}.getSeconds(), {this}.getMilliseconds())")] public DateTime AddYears(int value) { return default(DateTime); } /// <summary> /// Returns the number of days in the specified month and year. /// </summary> /// <returns> /// The number of days in <paramref name="month"/> for the specified <paramref name="year"/>.For example, if <paramref name="month"/> equals 2 for February, the return value is 28 or 29 depending upon whether <paramref name="year"/> is a leap year. /// </returns> /// <param name="year">The year. </param><param name="month">The month (a number ranging from 1 to 12). </param> [InlineCode("new Date({year}, {month}, -1).getDate() + 1")] public static int DaysInMonth(int year, int month) { return 0; } /// <summary> /// Returns an indication whether the specified year is a leap year. /// </summary> /// <returns> /// true if <paramref name="year"/> is a leap year; otherwise, false. /// </returns> /// <param name="year">A 4-digit year. </param> [InlineCode("new Date({year}, 2, -1).getDate() === 28")] public static bool IsLeapYear(int year) { return false; } [InlineCode("{$System.Script}.compare({this}, {other})")] public int CompareTo(DateTime other) { return 0; } /// <summary> /// Compares two instances of <see cref="T:System.DateTime"/> and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. /// </summary> /// <returns> /// A signed number indicating the relative values of <paramref name="t1"/> and <paramref name="t2"/>.Value Type Condition Less than zero <paramref name="t1"/> is earlier than <paramref name="t2"/>. Zero <paramref name="t1"/> is the same as <paramref name="t2"/>. Greater than zero <paramref name="t1"/> is later than <paramref name="t2"/>. /// </returns> /// <param name="t1">The first object to compare. </param><param name="t2">The second object to compare. </param> [InlineCode("{$System.Script}.compare({t1}, {t2})")] public static int Compare(DateTime t1, DateTime t2) { return 0; } [InlineCode("{$System.Script}.equalsT({this}, {other})")] public bool Equals(DateTime other) { return false; } /// <summary> /// Returns a value indicating whether two <see cref="T:System.DateTime"/> instances have the same date and time value. /// </summary> /// <returns> /// true if the two values are equal; otherwise, false. /// </returns> /// <param name="t1">The first object to compare. </param><param name="t2">The second object to compare. </param> [InlineCode("{$System.Script}.equalsT({t1}, {t2})")] public static bool Equals(DateTime t1, DateTime t2) { return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysisFramework; using Internal.IL; using Internal.IL.Stubs; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Debug = System.Diagnostics.Debug; namespace ILCompiler { public abstract class Compilation : ICompilation { protected readonly DependencyAnalyzerBase<NodeFactory> _dependencyGraph; protected readonly NodeFactory _nodeFactory; protected readonly Logger _logger; private readonly DebugInformationProvider _debugInformationProvider; public NameMangler NameMangler => _nodeFactory.NameMangler; public NodeFactory NodeFactory => _nodeFactory; public CompilerTypeSystemContext TypeSystemContext => NodeFactory.TypeSystemContext; public Logger Logger => _logger; internal PInvokeILProvider PInvokeILProvider { get; } private readonly TypeGetTypeMethodThunkCache _typeGetTypeMethodThunks; private readonly AssemblyGetExecutingAssemblyMethodThunkCache _assemblyGetExecutingAssemblyMethodThunks; private readonly MethodBaseGetCurrentMethodThunkCache _methodBaseGetCurrentMethodThunks; protected Compilation( DependencyAnalyzerBase<NodeFactory> dependencyGraph, NodeFactory nodeFactory, IEnumerable<ICompilationRootProvider> compilationRoots, DebugInformationProvider debugInformationProvider, Logger logger) { _dependencyGraph = dependencyGraph; _nodeFactory = nodeFactory; _logger = logger; _debugInformationProvider = debugInformationProvider; _dependencyGraph.ComputeDependencyRoutine += ComputeDependencyNodeDependencies; NodeFactory.AttachToDependencyGraph(_dependencyGraph); var rootingService = new RootingServiceProvider(dependencyGraph, nodeFactory); foreach (var rootProvider in compilationRoots) rootProvider.AddCompilationRoots(rootingService); MetadataType globalModuleGeneratedType = nodeFactory.CompilationModuleGroup.GeneratedAssembly.GetGlobalModuleType(); _typeGetTypeMethodThunks = new TypeGetTypeMethodThunkCache(globalModuleGeneratedType); _assemblyGetExecutingAssemblyMethodThunks = new AssemblyGetExecutingAssemblyMethodThunkCache(globalModuleGeneratedType); _methodBaseGetCurrentMethodThunks = new MethodBaseGetCurrentMethodThunkCache(); bool? forceLazyPInvokeResolution = null; // TODO: Workaround lazy PInvoke resolution not working with CppCodeGen yet // https://github.com/dotnet/corert/issues/2454 // https://github.com/dotnet/corert/issues/2149 if (nodeFactory.IsCppCodegenTemporaryWorkaround) forceLazyPInvokeResolution = false; PInvokeILProvider = new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyPInvokeResolution), nodeFactory.InteropStubManager.InteropStateManager); _methodILCache = new ILProvider(PInvokeILProvider); } private ILProvider _methodILCache; public MethodIL GetMethodIL(MethodDesc method) { // Flush the cache when it grows too big if (_methodILCache.Count > 1000) _methodILCache = new ILProvider(PInvokeILProvider); return _methodILCache.GetMethodIL(method); } protected abstract void ComputeDependencyNodeDependencies(List<DependencyNodeCore<NodeFactory>> obj); protected abstract void CompileInternal(string outputFile, ObjectDumper dumper); public DelegateCreationInfo GetDelegateCtor(TypeDesc delegateType, MethodDesc target, bool followVirtualDispatch) { return DelegateCreationInfo.Create(delegateType, target, NodeFactory, followVirtualDispatch); } /// <summary> /// Gets an object representing the static data for RVA mapped fields from the PE image. /// </summary> public ObjectNode GetFieldRvaData(FieldDesc field) { if (field.GetType() == typeof(PInvokeLazyFixupField)) { var pInvokeFixup = (PInvokeLazyFixupField)field; PInvokeMetadata metadata = pInvokeFixup.PInvokeMetadata; return NodeFactory.PInvokeMethodFixup(metadata.Module, metadata.Name); } else { // Use the typical field definition in case this is an instantiated generic type field = field.GetTypicalFieldDefinition(); return NodeFactory.ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field), ((EcmaField)field).GetFieldRvaData(), NodeFactory.Target.PointerSize); } } public bool HasLazyStaticConstructor(TypeDesc type) { return TypeSystemContext.HasLazyStaticConstructor(type); } public MethodDebugInformation GetDebugInfo(MethodIL methodIL) { return _debugInformationProvider.GetDebugInfo(methodIL); } /// <summary> /// Resolves a reference to an intrinsic method to a new method that takes it's place in the compilation. /// This is used for intrinsics where the intrinsic expansion depends on the callsite. /// </summary> /// <param name="intrinsicMethod">The intrinsic method called.</param> /// <param name="callsiteMethod">The callsite that calls the intrinsic.</param> /// <returns>The intrinsic implementation to be called for this specific callsite.</returns> public MethodDesc ExpandIntrinsicForCallsite(MethodDesc intrinsicMethod, MethodDesc callsiteMethod) { Debug.Assert(intrinsicMethod.IsIntrinsic); var intrinsicOwningType = intrinsicMethod.OwningType as MetadataType; if (intrinsicOwningType == null) return intrinsicMethod; if (intrinsicOwningType.Module != TypeSystemContext.SystemModule) return intrinsicMethod; if (intrinsicOwningType.Name == "Type" && intrinsicOwningType.Namespace == "System") { if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetType") { ModuleDesc callsiteModule = (callsiteMethod.OwningType as MetadataType)?.Module; if (callsiteModule != null) { Debug.Assert(callsiteModule is IAssemblyDesc, "Multi-module assemblies"); return _typeGetTypeMethodThunks.GetHelper(intrinsicMethod, ((IAssemblyDesc)callsiteModule).GetName().FullName); } } } else if (intrinsicOwningType.Name == "Assembly" && intrinsicOwningType.Namespace == "System.Reflection") { if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetExecutingAssembly") { ModuleDesc callsiteModule = (callsiteMethod.OwningType as MetadataType)?.Module; if (callsiteModule != null) { Debug.Assert(callsiteModule is IAssemblyDesc, "Multi-module assemblies"); return _assemblyGetExecutingAssemblyMethodThunks.GetHelper((IAssemblyDesc)callsiteModule); } } } else if (intrinsicOwningType.Name == "MethodBase" && intrinsicOwningType.Namespace == "System.Reflection") { if (intrinsicMethod.Signature.IsStatic && intrinsicMethod.Name == "GetCurrentMethod") { return _methodBaseGetCurrentMethodThunks.GetHelper(callsiteMethod).InstantiateAsOpen(); } } return intrinsicMethod; } public bool HasFixedSlotVTable(TypeDesc type) { return NodeFactory.VTable(type).HasFixedSlots; } public bool NeedsRuntimeLookup(ReadyToRunHelperId lookupKind, object targetOfLookup) { switch (lookupKind) { case ReadyToRunHelperId.TypeHandle: case ReadyToRunHelperId.NecessaryTypeHandle: case ReadyToRunHelperId.DefaultConstructor: return ((TypeDesc)targetOfLookup).IsRuntimeDeterminedSubtype; case ReadyToRunHelperId.MethodDictionary: case ReadyToRunHelperId.MethodEntry: case ReadyToRunHelperId.VirtualDispatchCell: case ReadyToRunHelperId.MethodHandle: return ((MethodDesc)targetOfLookup).IsRuntimeDeterminedExactMethod; case ReadyToRunHelperId.FieldHandle: return ((FieldDesc)targetOfLookup).OwningType.IsRuntimeDeterminedSubtype; default: throw new NotImplementedException(); } } public ISymbolNode ComputeConstantLookup(ReadyToRunHelperId lookupKind, object targetOfLookup) { switch (lookupKind) { case ReadyToRunHelperId.TypeHandle: return NodeFactory.ConstructedTypeSymbol((TypeDesc)targetOfLookup); case ReadyToRunHelperId.NecessaryTypeHandle: return NodeFactory.NecessaryTypeSymbol((TypeDesc)targetOfLookup); case ReadyToRunHelperId.MethodDictionary: return NodeFactory.MethodGenericDictionary((MethodDesc)targetOfLookup); case ReadyToRunHelperId.MethodEntry: return NodeFactory.FatFunctionPointer((MethodDesc)targetOfLookup); case ReadyToRunHelperId.MethodHandle: return NodeFactory.RuntimeMethodHandle((MethodDesc)targetOfLookup); case ReadyToRunHelperId.FieldHandle: return NodeFactory.RuntimeFieldHandle((FieldDesc)targetOfLookup); case ReadyToRunHelperId.DefaultConstructor: { var type = (TypeDesc)targetOfLookup; MethodDesc ctor = type.GetDefaultConstructor(); if (ctor == null) { MetadataType activatorType = TypeSystemContext.SystemModule.GetKnownType("System", "Activator"); MetadataType classWithMissingCtor = activatorType.GetKnownNestedType("ClassWithMissingConstructor"); ctor = classWithMissingCtor.GetParameterlessConstructor(); } return NodeFactory.CanonicalEntrypoint(ctor); } default: throw new NotImplementedException(); } } public GenericDictionaryLookup ComputeGenericLookup(MethodDesc contextMethod, ReadyToRunHelperId lookupKind, object targetOfLookup) { GenericContextSource contextSource; if (contextMethod.RequiresInstMethodDescArg()) { contextSource = GenericContextSource.MethodParameter; } else if (contextMethod.RequiresInstMethodTableArg()) { contextSource = GenericContextSource.TypeParameter; } else { Debug.Assert(contextMethod.AcquiresInstMethodTableFromThis()); contextSource = GenericContextSource.ThisObject; } // Can we do a fixed lookup? Start by checking if we can get to the dictionary. // Context source having a vtable with fixed slots is a prerequisite. if (contextSource == GenericContextSource.MethodParameter || HasFixedSlotVTable(contextMethod.OwningType)) { DictionaryLayoutNode dictionaryLayout; if (contextSource == GenericContextSource.MethodParameter) dictionaryLayout = _nodeFactory.GenericDictionaryLayout(contextMethod); else dictionaryLayout = _nodeFactory.GenericDictionaryLayout(contextMethod.OwningType); // If the dictionary layout has fixed slots, we can compute the lookup now. Otherwise defer to helper. if (dictionaryLayout.HasFixedSlots) { int pointerSize = _nodeFactory.Target.PointerSize; GenericLookupResult lookup = ReadyToRunGenericHelperNode.GetLookupSignature(_nodeFactory, lookupKind, targetOfLookup); int dictionarySlot = dictionaryLayout.GetSlotForFixedEntry(lookup); if (dictionarySlot != -1) { int dictionaryOffset = dictionarySlot * pointerSize; if (contextSource == GenericContextSource.MethodParameter) { return GenericDictionaryLookup.CreateFixedLookup(contextSource, dictionaryOffset); } else { int vtableSlot = VirtualMethodSlotHelper.GetGenericDictionarySlot(_nodeFactory, contextMethod.OwningType); int vtableOffset = EETypeNode.GetVTableOffset(pointerSize) + vtableSlot * pointerSize; return GenericDictionaryLookup.CreateFixedLookup(contextSource, vtableOffset, dictionaryOffset); } } } } // Fixed lookup not possible - use helper. return GenericDictionaryLookup.CreateHelperLookup(contextSource); } CompilationResults ICompilation.Compile(string outputFile, ObjectDumper dumper) { if (dumper != null) { dumper.Begin(); } // In multi-module builds, set the compilation unit prefix to prevent ambiguous symbols in linked object files NameMangler.CompilationUnitPrefix = _nodeFactory.CompilationModuleGroup.IsSingleFileCompilation ? "" : Path.GetFileNameWithoutExtension(outputFile); CompileInternal(outputFile, dumper); if (dumper != null) { dumper.End(); } return new CompilationResults(_dependencyGraph, _nodeFactory); } private class RootingServiceProvider : IRootingServiceProvider { private DependencyAnalyzerBase<NodeFactory> _graph; private NodeFactory _factory; public RootingServiceProvider(DependencyAnalyzerBase<NodeFactory> graph, NodeFactory factory) { _graph = graph; _factory = factory; } public void AddCompilationRoot(MethodDesc method, string reason, string exportName = null) { IMethodNode methodEntryPoint = _factory.CanonicalEntrypoint(method); _graph.AddRoot(methodEntryPoint, reason); if (exportName != null) _factory.NodeAliases.Add(methodEntryPoint, exportName); } public void AddCompilationRoot(TypeDesc type, string reason) { if (!ConstructedEETypeNode.CreationAllowed(type)) { _graph.AddRoot(_factory.NecessaryTypeSymbol(type), reason); } else { _graph.AddRoot(_factory.ConstructedTypeSymbol(type), reason); } } public void RootThreadStaticBaseForType(TypeDesc type, string reason) { Debug.Assert(!type.IsGenericDefinition); MetadataType metadataType = type as MetadataType; if (metadataType != null && metadataType.ThreadStaticFieldSize.AsInt > 0) { _graph.AddRoot(_factory.TypeThreadStaticIndex(metadataType), reason); // Also explicitly root the non-gc base if we have a lazy cctor if(_factory.TypeSystemContext.HasLazyStaticConstructor(type)) _graph.AddRoot(_factory.TypeNonGCStaticsSymbol(metadataType), reason); } } public void RootGCStaticBaseForType(TypeDesc type, string reason) { Debug.Assert(!type.IsGenericDefinition); MetadataType metadataType = type as MetadataType; if (metadataType != null && metadataType.GCStaticFieldSize.AsInt > 0) { _graph.AddRoot(_factory.TypeGCStaticsSymbol(metadataType), reason); // Also explicitly root the non-gc base if we have a lazy cctor if (_factory.TypeSystemContext.HasLazyStaticConstructor(type)) _graph.AddRoot(_factory.TypeNonGCStaticsSymbol(metadataType), reason); } } public void RootNonGCStaticBaseForType(TypeDesc type, string reason) { Debug.Assert(!type.IsGenericDefinition); MetadataType metadataType = type as MetadataType; if (metadataType != null && (metadataType.NonGCStaticFieldSize.AsInt > 0 || _factory.TypeSystemContext.HasLazyStaticConstructor(type))) { _graph.AddRoot(_factory.TypeNonGCStaticsSymbol(metadataType), reason); } } public void RootVirtualMethodForReflection(MethodDesc method, string reason) { Debug.Assert(method.IsVirtual); if (!_factory.VTable(method.OwningType).HasFixedSlots) _graph.AddRoot(_factory.VirtualMethodUse(method), reason); if (method.IsAbstract) { _graph.AddRoot(_factory.ReflectableMethod(method), reason); } } } } // Interface under which Compilation is exposed externally. public interface ICompilation { CompilationResults Compile(string outputFileName, ObjectDumper dumper); } public class CompilationResults { private readonly DependencyAnalyzerBase<NodeFactory> _graph; private readonly NodeFactory _factory; protected ImmutableArray<DependencyNodeCore<NodeFactory>> MarkedNodes { get { return _graph.MarkedNodeList; } } internal CompilationResults(DependencyAnalyzerBase<NodeFactory> graph, NodeFactory factory) { _graph = graph; _factory = factory; } public void WriteDependencyLog(string fileName) { using (FileStream dgmlOutput = new FileStream(fileName, FileMode.Create)) { DgmlWriter.WriteDependencyGraphToStream(dgmlOutput, _graph, _factory); dgmlOutput.Flush(); } } public IEnumerable<MethodDesc> CompiledMethodBodies { get { foreach (var node in MarkedNodes) { if (node is IMethodBodyNode) yield return ((IMethodBodyNode)node).Method; } } } public IEnumerable<TypeDesc> ConstructedEETypes { get { foreach (var node in MarkedNodes) { if (node is ConstructedEETypeNode || node is CanonicalEETypeNode) { yield return ((IEETypeNode)node).Type; } } } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; #if NETSTANDARD using System.Reflection; #endif using System.Text; #if !NETSTANDARD1_0 using System.Transactions; #endif using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; #if !NETSTANDARD using System.Configuration; using ConfigurationManager = System.Configuration.ConfigurationManager; #endif /// <summary> /// Writes log messages to the database using an ADO.NET provider. /// </summary> /// <remarks> /// - NETSTANDARD cannot load connectionstrings from .config /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/Database-target">Documentation on NLog Wiki</seealso> /// <example> /// <para> /// The configuration is dependent on the database type, because /// there are different methods of specifying connection string, SQL /// command and command parameters. /// </para> /// <para>MS SQL Server using System.Data.SqlClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/MSSQL/NLog.config" height="450" /> /// <para>Oracle using System.Data.OracleClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.Native/NLog.config" height="350" /> /// <para>Oracle using System.Data.OleDBClient:</para> /// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.OleDB/NLog.config" height="350" /> /// <para>To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):</para> /// <code lang="C#" source="examples/targets/Configuration API/Database/MSSQL/Example.cs" height="630" /> /// </example> [Target("Database")] public class DatabaseTarget : Target, IInstallable { private IDbConnection _activeConnection; private string _activeConnectionString; /// <summary> /// Initializes a new instance of the <see cref="DatabaseTarget" /> class. /// </summary> public DatabaseTarget() { InstallDdlCommands = new List<DatabaseCommandInfo>(); UninstallDdlCommands = new List<DatabaseCommandInfo>(); DBProvider = "sqlserver"; DBHost = "."; #if !NETSTANDARD ConnectionStringsSettings = ConfigurationManager.ConnectionStrings; #endif CommandType = CommandType.Text; OptimizeBufferReuse = GetType() == typeof(DatabaseTarget); // Class not sealed, reduce breaking changes } /// <summary> /// Initializes a new instance of the <see cref="DatabaseTarget" /> class. /// </summary> /// <param name="name">Name of the target.</param> public DatabaseTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the name of the database provider. /// </summary> /// <remarks> /// <para> /// The parameter name should be a provider invariant name as registered in machine.config or app.config. Common values are: /// </para> /// <ul> /// <li><c>System.Data.SqlClient</c> - <see href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx">SQL Sever Client</see></li> /// <li><c>System.Data.SqlServerCe.3.5</c> - <see href="https://www.microsoft.com/sqlserver/2005/en/us/compact.aspx">SQL Sever Compact 3.5</see></li> /// <li><c>System.Data.OracleClient</c> - <see href="https://msdn.microsoft.com/en-us/library/system.data.oracleclient.aspx">Oracle Client from Microsoft</see> (deprecated in .NET Framework 4)</li> /// <li><c>Oracle.DataAccess.Client</c> - <see href="https://www.oracle.com/technology/tech/windows/odpnet/index.html">ODP.NET provider from Oracle</see></li> /// <li><c>System.Data.SQLite</c> - <see href="http://sqlite.phxsoftware.com/">System.Data.SQLite driver for SQLite</see></li> /// <li><c>Npgsql</c> - <see href="https://www.npgsql.org/">Npgsql driver for PostgreSQL</see></li> /// <li><c>MySql.Data.MySqlClient</c> - <see href="https://www.mysql.com/downloads/connector/net/">MySQL Connector/Net</see></li> /// </ul> /// <para>(Note that provider invariant names are not supported on .NET Compact Framework).</para> /// <para> /// Alternatively the parameter value can be be a fully qualified name of the provider /// connection type (class implementing <see cref="IDbConnection" />) or one of the following tokens: /// </para> /// <ul> /// <li><c>sqlserver</c>, <c>mssql</c>, <c>microsoft</c> or <c>msde</c> - SQL Server Data Provider</li> /// <li><c>oledb</c> - OLEDB Data Provider</li> /// <li><c>odbc</c> - ODBC Data Provider</li> /// </ul> /// </remarks> /// <docgen category='Connection Options' order='10' /> [RequiredParameter] [DefaultValue("sqlserver")] public string DBProvider { get; set; } #if !NETSTANDARD /// <summary> /// Gets or sets the name of the connection string (as specified in <see href="https://msdn.microsoft.com/en-us/library/bf7sd233.aspx">&lt;connectionStrings&gt; configuration section</see>. /// </summary> /// <docgen category='Connection Options' order='10' /> public string ConnectionStringName { get; set; } #endif /// <summary> /// Gets or sets the connection string. When provided, it overrides the values /// specified in DBHost, DBUserName, DBPassword, DBDatabase. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout ConnectionString { get; set; } /// <summary> /// Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used. /// </summary> /// <docgen category='Installation Options' order='10' /> public Layout InstallConnectionString { get; set; } /// <summary> /// Gets the installation DDL commands. /// </summary> /// <docgen category='Installation Options' order='10' /> [ArrayParameter(typeof(DatabaseCommandInfo), "install-command")] public IList<DatabaseCommandInfo> InstallDdlCommands { get; private set; } /// <summary> /// Gets the uninstallation DDL commands. /// </summary> /// <docgen category='Installation Options' order='10' /> [ArrayParameter(typeof(DatabaseCommandInfo), "uninstall-command")] public IList<DatabaseCommandInfo> UninstallDdlCommands { get; private set; } /// <summary> /// Gets or sets a value indicating whether to keep the /// database connection open between the log events. /// </summary> /// <docgen category='Connection Options' order='10' /> [DefaultValue(false)] public bool KeepConnection { get; set; } /// <summary> /// Obsolete - value will be ignored! The logging code always runs outside of transaction. /// /// Gets or sets a value indicating whether to use database transactions. /// Some data providers require this. /// </summary> /// <docgen category='Connection Options' order='10' /> /// <remarks> /// This option was removed in NLog 4.0 because the logging code always runs outside of transaction. /// This ensures that the log gets written to the database if you rollback the main transaction because of an error and want to log the error. /// </remarks> [Obsolete("Value will be ignored as logging code always executes outside of a transaction. Marked obsolete on NLog 4.0 and it will be removed in NLog 6.")] public bool? UseTransactions { get; set; } /// <summary> /// Gets or sets the database host name. If the ConnectionString is not provided /// this value will be used to construct the "Server=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout DBHost { get; set; } /// <summary> /// Gets or sets the database user name. If the ConnectionString is not provided /// this value will be used to construct the "User ID=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout DBUserName { get; set; } /// <summary> /// Gets or sets the database password. If the ConnectionString is not provided /// this value will be used to construct the "Password=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout DBPassword { get => _dbPassword?.Layout; set => _dbPassword = TransformedLayout.Create(value, EscapeValueForConnectionString, RenderLogEvent); } /// <summary> /// Gets or sets the database name. If the ConnectionString is not provided /// this value will be used to construct the "Database=" part of the /// connection string. /// </summary> /// <docgen category='Connection Options' order='10' /> public Layout DBDatabase { get; set; } /// <summary> /// Gets or sets the text of the SQL command to be run on each log level. /// </summary> /// <remarks> /// Typically this is a SQL INSERT statement or a stored procedure call. /// It should use the database-specific parameters (marked as <c>@parameter</c> /// for SQL server or <c>:parameter</c> for Oracle, other data providers /// have their own notation) and not the layout renderers, /// because the latter is prone to SQL injection attacks. /// The layout renderers should be specified as &lt;parameter /&gt; elements instead. /// </remarks> /// <docgen category='SQL Statement' order='10' /> [RequiredParameter] public Layout CommandText { get; set; } /// <summary> /// Gets or sets the type of the SQL command to be run on each log level. /// </summary> /// <remarks> /// This specifies how the command text is interpreted, as "Text" (default) or as "StoredProcedure". /// When using the value StoredProcedure, the commandText-property would /// normally be the name of the stored procedure. TableDirect method is not supported in this context. /// </remarks> /// <docgen category='SQL Statement' order='11' /> [DefaultValue(CommandType.Text)] public CommandType CommandType { get; set; } /// <summary> /// Gets the collection of parameters. Each item contains a mapping /// between NLog layout and a database named or positional parameter. /// </summary> /// <docgen category='SQL Statement' order='14' /> [ArrayParameter(typeof(DatabaseParameterInfo), "parameter")] public IList<DatabaseParameterInfo> Parameters { get; } = new List<DatabaseParameterInfo>(); /// <summary> /// Gets the collection of properties. Each item contains a mapping /// between NLog layout and a property on the DbConnection instance /// </summary> /// <docgen category='Connection Options' order='10' /> [ArrayParameter(typeof(DatabaseObjectPropertyInfo), "connectionproperty")] public IList<DatabaseObjectPropertyInfo> ConnectionProperties { get; } = new List<DatabaseObjectPropertyInfo>(); /// <summary> /// Gets the collection of properties. Each item contains a mapping /// between NLog layout and a property on the DbCommand instance /// </summary> /// <docgen category='Connection Options' order='10' /> [ArrayParameter(typeof(DatabaseObjectPropertyInfo), "commandproperty")] public IList<DatabaseObjectPropertyInfo> CommandProperties { get; } = new List<DatabaseObjectPropertyInfo>(); /// <summary> /// Configures isolated transaction batch writing. If supported by the database, then it will improve insert performance. /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> public System.Data.IsolationLevel? IsolationLevel { get; set; } #if !NETSTANDARD internal DbProviderFactory ProviderFactory { get; set; } // this is so we can mock the connection string without creating sub-processes internal ConnectionStringSettingsCollection ConnectionStringsSettings { get; set; } #endif internal Type ConnectionType { get; set; } private IPropertyTypeConverter PropertyTypeConverter { get => _propertyTypeConverter ?? (_propertyTypeConverter = ConfigurationItemFactory.Default.PropertyTypeConverter); set => _propertyTypeConverter = value; } private IPropertyTypeConverter _propertyTypeConverter; SortHelpers.KeySelector<AsyncLogEventInfo, string> _buildConnectionStringDelegate; private TransformedLayout _dbPassword; /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { RunInstallCommands(installationContext, InstallDdlCommands); } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { RunInstallCommands(installationContext, UninstallDdlCommands); } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { return null; } internal IDbConnection OpenConnection(string connectionString, LogEventInfo logEventInfo) { IDbConnection connection; #if !NETSTANDARD if (ProviderFactory != null) { connection = ProviderFactory.CreateConnection(); } else #endif { connection = (IDbConnection)Activator.CreateInstance(ConnectionType); } if (connection == null) { throw new NLogRuntimeException("Creation of connection failed"); } connection.ConnectionString = connectionString; if (ConnectionProperties?.Count > 0) { ApplyDatabaseObjectProperties(connection, ConnectionProperties, logEventInfo ?? LogEventInfo.CreateNullEvent()); } connection.Open(); return connection; } private void ApplyDatabaseObjectProperties(object databaseObject, IList<DatabaseObjectPropertyInfo> objectProperties, LogEventInfo logEventInfo) { for (int i = 0; i < objectProperties.Count; ++i) { var propertyInfo = objectProperties[i]; try { var propertyValue = GetDatabaseObjectPropertyValue(logEventInfo, propertyInfo); if (!propertyInfo.SetPropertyValue(databaseObject, propertyValue)) { InternalLogger.Warn("DatabaseTarget(Name={0}): Failed to lookup property {1} on {2}", Name, propertyInfo.Name, databaseObject.GetType()); } } catch (Exception ex) { InternalLogger.Error(ex, "DatabaseTarget(Name={0}): Failed to assign value for property {1} on {2}", Name, propertyInfo.Name, databaseObject.GetType()); if (ExceptionMustBeRethrown(ex)) throw; } } } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "connectionStrings", Justification = "Name of the config file section.")] protected override void InitializeTarget() { base.InitializeTarget(); #pragma warning disable 618 if (UseTransactions.HasValue) #pragma warning restore 618 { InternalLogger.Warn("DatabaseTarget(Name={0}): UseTransactions property is obsolete and will not be used - will be removed in NLog 6", Name); } bool foundProvider = false; string providerName = string.Empty; #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) { // read connection string and provider factory from the configuration file var cs = ConnectionStringsSettings[ConnectionStringName]; if (cs == null) { throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section."); } if (!string.IsNullOrEmpty(cs.ConnectionString?.Trim())) { ConnectionString = SimpleLayout.Escape(cs.ConnectionString.Trim()); } providerName = cs.ProviderName?.Trim() ?? string.Empty; } #endif if (ConnectionString != null) { providerName = InitConnectionString(providerName); } #if !NETSTANDARD if (string.IsNullOrEmpty(providerName)) { providerName = GetProviderNameFromDbProviderFactories(providerName); } if (!string.IsNullOrEmpty(providerName)) { foundProvider = InitProviderFactory(providerName); } #endif if (!foundProvider) { try { SetConnectionType(); if (ConnectionType == null) { InternalLogger.Warn("DatabaseTarget(Name={0}): No ConnectionType created from DBProvider={1}", Name, DBProvider); } } catch (Exception ex) { InternalLogger.Error(ex, "DatabaseTarget(Name={0}): Failed to create ConnectionType from DBProvider={1}", Name, DBProvider); throw; } } } private string InitConnectionString(string providerName) { try { var connectionString = BuildConnectionString(LogEventInfo.CreateNullEvent()); var dbConnectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (dbConnectionStringBuilder.TryGetValue("provider connection string", out var connectionStringValue)) { // Special Entity Framework Connection String if (dbConnectionStringBuilder.TryGetValue("provider", out var providerValue)) { // Provider was overriden by ConnectionString providerName = providerValue.ToString()?.Trim() ?? string.Empty; } // ConnectionString was overriden by ConnectionString :) ConnectionString = SimpleLayout.Escape(connectionStringValue.ToString()); } } catch (Exception ex) { #if !NETSTANDARD if (!string.IsNullOrEmpty(ConnectionStringName)) InternalLogger.Warn(ex, "DatabaseTarget(Name={0}): DbConnectionStringBuilder failed to parse '{1}' ConnectionString", Name, ConnectionStringName); else #endif InternalLogger.Warn(ex, "DatabaseTarget(Name={0}): DbConnectionStringBuilder failed to parse ConnectionString", Name); } return providerName; } #if !NETSTANDARD private bool InitProviderFactory(string providerName) { bool foundProvider; try { ProviderFactory = DbProviderFactories.GetFactory(providerName); foundProvider = true; } catch (Exception ex) { InternalLogger.Error(ex, "DatabaseTarget(Name={0}): DbProviderFactories failed to get factory from ProviderName={1}", Name, providerName); throw; } return foundProvider; } private string GetProviderNameFromDbProviderFactories(string providerName) { string dbProvider = DBProvider?.Trim() ?? string.Empty; if (!string.IsNullOrEmpty(dbProvider)) { foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows) { var invariantname = (string)row["InvariantName"]; if (string.Equals(invariantname, dbProvider, StringComparison.OrdinalIgnoreCase)) { providerName = invariantname; break; } } } return providerName; } #endif /// <summary> /// Set the <see cref="ConnectionType"/> to use it for opening connections to the database. /// </summary> private void SetConnectionType() { switch (DBProvider.ToUpperInvariant()) { case "SQLSERVER": case "MSSQL": case "MICROSOFT": case "MSDE": case "SYSTEM.DATA.SQLCLIENT": { #if NETSTANDARD var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient")); #else var assembly = typeof(IDbConnection).GetAssembly(); #endif ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true); break; } #if !NETSTANDARD case "OLEDB": { var assembly = typeof(IDbConnection).GetAssembly(); ConnectionType = assembly.GetType("System.Data.OleDb.OleDbConnection", true, true); break; } #endif case "ODBC": case "SYSTEM.DATA.ODBC": { #if NETSTANDARD var assembly = Assembly.Load(new AssemblyName("System.Data.Odbc")); #else var assembly = typeof(IDbConnection).GetAssembly(); #endif ConnectionType = assembly.GetType("System.Data.Odbc.OdbcConnection", true, true); break; } default: ConnectionType = Type.GetType(DBProvider, true, true); break; } } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { PropertyTypeConverter = null; base.CloseTarget(); InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of CloseTarget", Name); CloseConnection(); } /// <summary> /// Writes the specified logging event to the database. It creates /// a new database command, prepares parameters for it by calculating /// layouts and executes the command. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { try { WriteLogEventToDatabase(logEvent, BuildConnectionString(logEvent)); } finally { if (!KeepConnection) { InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection (KeepConnection = false).", Name); CloseConnection(); } } } /// <summary> /// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected override void Write(AsyncLogEventInfo[] logEvents) { Write((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { if (_buildConnectionStringDelegate == null) _buildConnectionStringDelegate = (l) => BuildConnectionString(l.LogEvent); var buckets = logEvents.BucketSort(_buildConnectionStringDelegate); foreach (var kvp in buckets) { try { WriteLogEventsToDatabase(kvp.Value, kvp.Key); } finally { if (!KeepConnection) { InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of KeepConnection=false", Name); CloseConnection(); } } } } private void WriteLogEventsToDatabase(IList<AsyncLogEventInfo> logEvents, string connectionString) { if (IsolationLevel.HasValue && logEvents.Count > 1) { WriteLogEventBatchToDatabase(logEvents, connectionString); } else { for (int i = 0; i < logEvents.Count; i++) { try { WriteLogEventToDatabase(logEvents[i].LogEvent, connectionString); logEvents[i].Continuation(null); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } logEvents[i].Continuation(exception); if (ExceptionMustBeRethrown(exception)) { throw; } } } } } private void WriteLogEventBatchToDatabase(IList<AsyncLogEventInfo> logEvents, string connectionString) { try { //Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction. using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { EnsureConnectionOpen(connectionString, logEvents.Count > 0 ? logEvents[0].LogEvent : null); var dbTransaction = _activeConnection.BeginTransaction(IsolationLevel.Value); try { for (int i = 0; i < logEvents.Count; ++i) { ExecuteDbCommandWithParameters(logEvents[i].LogEvent, _activeConnection, dbTransaction); } dbTransaction?.Commit(); for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(null); } dbTransaction?.Dispose(); // Can throw error on dispose, so no using transactionScope.Complete(); //not really needed as there is no transaction at all. } catch { try { if (dbTransaction?.Connection != null) { dbTransaction?.Rollback(); } dbTransaction?.Dispose(); } catch (Exception exception) { InternalLogger.Error(exception, "DatabaseTarget(Name={0}): Error during rollback of batch writing {1} logevents to database.", Name, logEvents.Count); if (exception.MustBeRethrownImmediately()) { throw; } } throw; } } } catch (Exception exception) { InternalLogger.Error(exception, "DatabaseTarget(Name={0}): Error when batch writing {1} logevents to database.", Name, logEvents.Count); if (exception.MustBeRethrownImmediately()) { throw; } for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(exception); } InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of error", Name); CloseConnection(); if (ExceptionMustBeRethrown(exception)) { throw; } } } private void WriteLogEventToDatabase(LogEventInfo logEvent, string connectionString) { try { //Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction. using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { EnsureConnectionOpen(connectionString, logEvent); ExecuteDbCommandWithParameters(logEvent, _activeConnection, null); transactionScope.Complete(); //not really needed as there is no transaction at all. } } catch (Exception exception) { InternalLogger.Error(exception, "DatabaseTarget(Name={0}): Error when writing to database.", Name); if (exception.MustBeRethrownImmediately()) { throw; } InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of error", Name); CloseConnection(); throw; } } /// <summary> /// Write logEvent to database /// </summary> private void ExecuteDbCommandWithParameters(LogEventInfo logEvent, IDbConnection dbConnection, IDbTransaction dbTransaction) { using (IDbCommand command = CreateDbCommand(logEvent, dbConnection)) { if (dbTransaction != null) command.Transaction = dbTransaction; int result = command.ExecuteNonQuery(); InternalLogger.Trace("DatabaseTarget(Name={0}): Finished execution, result = {1}", Name, result); } } internal IDbCommand CreateDbCommand(LogEventInfo logEvent, IDbConnection dbConnection) { var commandText = RenderLogEvent(CommandText, logEvent); InternalLogger.Trace("DatabaseTarget(Name={0}): Executing {1}: {2}", Name, CommandType, commandText); return CreateDbCommandWithParameters(logEvent, dbConnection, CommandType, commandText, Parameters); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")] private IDbCommand CreateDbCommandWithParameters(LogEventInfo logEvent, IDbConnection dbConnection, CommandType commandType, string dbCommandText, IList<DatabaseParameterInfo> databaseParameterInfos) { var dbCommand = dbConnection.CreateCommand(); dbCommand.CommandType = commandType; if (CommandProperties?.Count > 0) { ApplyDatabaseObjectProperties(dbCommand, CommandProperties, logEvent); } dbCommand.CommandText = dbCommandText; for (int i = 0; i < databaseParameterInfos.Count; ++i) { var parameterInfo = databaseParameterInfos[i]; var dbParameter = CreateDatabaseParameter(dbCommand, parameterInfo); var dbParameterValue = GetDatabaseParameterValue(logEvent, parameterInfo); dbParameter.Value = dbParameterValue; dbCommand.Parameters.Add(dbParameter); InternalLogger.Trace(" DatabaseTarget: Parameter: '{0}' = '{1}' ({2})", dbParameter.ParameterName, dbParameter.Value, dbParameter.DbType); } return dbCommand; } /// <summary> /// Build the connectionstring from the properties. /// </summary> /// <remarks> /// Using <see cref="ConnectionString"/> at first, and falls back to the properties <see cref="DBHost"/>, /// <see cref="DBUserName"/>, <see cref="DBPassword"/> and <see cref="DBDatabase"/> /// </remarks> /// <param name="logEvent">Event to render the layout inside the properties.</param> /// <returns></returns> protected string BuildConnectionString(LogEventInfo logEvent) { if (ConnectionString != null) { return RenderLogEvent(ConnectionString, logEvent); } var sb = new StringBuilder(); sb.Append("Server="); sb.Append(RenderLogEvent(DBHost, logEvent)); sb.Append(";"); var dbUserName = RenderLogEvent(DBUserName, logEvent); if (string.IsNullOrEmpty(dbUserName)) { sb.Append("Trusted_Connection=SSPI;"); } else { sb.Append("User id="); sb.Append(dbUserName); sb.Append(";Password="); var password = _dbPassword.Render(logEvent); sb.Append(password); sb.Append(";"); } var dbDatabase = RenderLogEvent(DBDatabase, logEvent); if (!string.IsNullOrEmpty(dbDatabase)) { sb.Append("Database="); sb.Append(dbDatabase); } return sb.ToString(); } /// <summary> /// Escape quotes and semicolons. /// See https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms722656(v=vs.85)#setting-values-that-use-reserved-characters /// </summary> private static string EscapeValueForConnectionString(string value) { const string singleQuote = "'"; if (value.StartsWith(singleQuote) && value.EndsWith(singleQuote)) { // already escaped return value; } const string doubleQuote = "\""; if (value.StartsWith(doubleQuote) && value.EndsWith(doubleQuote)) { // already escaped return value; } var containsSingle = value.Contains(singleQuote); var containsDouble = value.Contains(doubleQuote); if (value.Contains(";") || containsSingle || containsDouble) { if (!containsSingle) { return string.Concat(singleQuote, value, singleQuote); } if (!containsDouble) { return string.Concat(doubleQuote, value, doubleQuote); } // both single and double var escapedValue = value.Replace(doubleQuote, doubleQuote + doubleQuote); return string.Concat(doubleQuote, escapedValue, doubleQuote); } return value; } private void EnsureConnectionOpen(string connectionString, LogEventInfo logEventInfo) { if (_activeConnection != null && _activeConnectionString != connectionString) { InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection because of opening new.", Name); CloseConnection(); } if (_activeConnection != null) { return; } InternalLogger.Trace("DatabaseTarget(Name={0}): Open connection.", Name); _activeConnection = OpenConnection(connectionString, logEventInfo); _activeConnectionString = connectionString; } private void CloseConnection() { _activeConnectionString = null; if (_activeConnection != null) { _activeConnection.Close(); _activeConnection.Dispose(); _activeConnection = null; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")] private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands) { // create log event that will be used to render all layouts LogEventInfo logEvent = installationContext.CreateLogEvent(); try { foreach (var commandInfo in commands) { var connectionString = GetConnectionStringFromCommand(commandInfo, logEvent); // Set ConnectionType if it has not been initialized already if (ConnectionType == null) { SetConnectionType(); } EnsureConnectionOpen(connectionString, logEvent); string commandText = RenderLogEvent(commandInfo.Text, logEvent); installationContext.Trace("DatabaseTarget(Name={0}) - Executing {1} '{2}'", Name, commandInfo.CommandType, commandText); using (IDbCommand command = CreateDbCommandWithParameters(logEvent, _activeConnection, commandInfo.CommandType, commandText, commandInfo.Parameters)) { try { command.ExecuteNonQuery(); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures) { installationContext.Warning(exception.Message); } else { installationContext.Error(exception.Message); throw; } } } } } finally { InternalLogger.Trace("DatabaseTarget(Name={0}): Close connection after install.", Name); CloseConnection(); } } private string GetConnectionStringFromCommand(DatabaseCommandInfo commandInfo, LogEventInfo logEvent) { string connectionString; if (commandInfo.ConnectionString != null) { // if there is connection string specified on the command info, use it connectionString = RenderLogEvent(commandInfo.ConnectionString, logEvent); } else if (InstallConnectionString != null) { // next, try InstallConnectionString connectionString = RenderLogEvent(InstallConnectionString, logEvent); } else { // if it's not defined, fall back to regular connection string connectionString = BuildConnectionString(logEvent); } return connectionString; } /// <summary> /// Create database parameter /// </summary> /// <param name="command">Current command.</param> /// <param name="parameterInfo">Parameter configuration info.</param> protected virtual IDbDataParameter CreateDatabaseParameter(IDbCommand command, DatabaseParameterInfo parameterInfo) { IDbDataParameter dbParameter = command.CreateParameter(); dbParameter.Direction = ParameterDirection.Input; if (parameterInfo.Name != null) { dbParameter.ParameterName = parameterInfo.Name; } if (parameterInfo.Size != 0) { dbParameter.Size = parameterInfo.Size; } if (parameterInfo.Precision != 0) { dbParameter.Precision = parameterInfo.Precision; } if (parameterInfo.Scale != 0) { dbParameter.Scale = parameterInfo.Scale; } try { if (!parameterInfo.SetDbType(dbParameter)) { InternalLogger.Warn(" DatabaseTarget: Parameter: '{0}' - Failed to assign DbType={1}", parameterInfo.Name, parameterInfo.DbType); } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Error(ex, " DatabaseTarget: Parameter: '{0}' - Failed to assign DbType={1}", parameterInfo.Name, parameterInfo.DbType); if (ExceptionMustBeRethrown(ex)) throw; } return dbParameter; } /// <summary> /// Extract parameter value from the logevent /// </summary> /// <param name="logEvent">Current logevent.</param> /// <param name="parameterInfo">Parameter configuration info.</param> protected internal virtual object GetDatabaseParameterValue(LogEventInfo logEvent, DatabaseParameterInfo parameterInfo) { return RenderObjectValue(logEvent, parameterInfo.Name, parameterInfo.Layout, parameterInfo.ParameterType, parameterInfo.Format, parameterInfo.Culture, parameterInfo.AllowDbNull); } private object GetDatabaseObjectPropertyValue(LogEventInfo logEvent, DatabaseObjectPropertyInfo connectionInfo) { return RenderObjectValue(logEvent, connectionInfo.Name, connectionInfo.Layout, connectionInfo.PropertyType, connectionInfo.Format, connectionInfo.Culture, false); } private object RenderObjectValue(LogEventInfo logEvent, string propertyName, Layout valueLayout, Type valueType, string valueFormat, IFormatProvider formatProvider, bool allowDbNull) { if (string.IsNullOrEmpty(valueFormat) && valueType == typeof(string) && !allowDbNull) { return RenderLogEvent(valueLayout, logEvent) ?? string.Empty; } formatProvider = formatProvider ?? logEvent.FormatProvider ?? LoggingConfiguration?.DefaultCultureInfo; try { if (TryRenderObjectRawValue(logEvent, valueLayout, valueType, valueFormat, formatProvider, allowDbNull, out var rawValue)) { return rawValue; } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Warn(ex, " DatabaseTarget: Failed to convert raw value for '{0}' into {1}", propertyName, valueType); if (ExceptionMustBeRethrown(ex)) throw; } try { InternalLogger.Trace(" DatabaseTarget: Attempt to convert layout value for '{0}' into {1}", propertyName, valueType); string parameterValue = RenderLogEvent(valueLayout, logEvent); if (string.IsNullOrEmpty(parameterValue)) { return CreateDefaultValue(valueType, allowDbNull); } return PropertyTypeConverter.Convert(parameterValue, valueType, valueFormat, formatProvider) ?? CreateDefaultValue(valueType, allowDbNull); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; InternalLogger.Warn(ex, " DatabaseTarget: Failed to convert layout value for '{0}' into {1}", propertyName, valueType); if (ExceptionMustBeRethrown(ex)) throw; return CreateDefaultValue(valueType, allowDbNull); } } private bool TryRenderObjectRawValue(LogEventInfo logEvent, Layout valueLayout, Type valueType, string valueFormat, IFormatProvider formatProvider, bool allowDbNull, out object rawValue) { if (valueLayout.TryGetRawValue(logEvent, out rawValue)) { if (ReferenceEquals(rawValue, DBNull.Value)) { return true; } if (rawValue == null) { rawValue = CreateDefaultValue(valueType, allowDbNull); return true; } if (valueType == typeof(string)) { return rawValue is string; } rawValue = PropertyTypeConverter.Convert(rawValue, valueType, valueFormat, formatProvider) ?? CreateDefaultValue(valueType, allowDbNull); return true; } return false; } /// <summary> /// Create Default Value of Type /// </summary> private static object CreateDefaultValue(Type dbParameterType, bool allowDbNull) { if (allowDbNull) return DBNull.Value; else if (dbParameterType == typeof(string)) return string.Empty; else if (dbParameterType.IsValueType()) return Activator.CreateInstance(dbParameterType); else return DBNull.Value; } #if NETSTANDARD1_0 /// <summary> /// Fake transaction /// /// Transactions aren't in .NET Core: https://github.com/dotnet/corefx/issues/2949 /// </summary> private sealed class TransactionScope : IDisposable { private readonly TransactionScopeOption suppress; public TransactionScope(TransactionScopeOption suppress) { this.suppress = suppress; } public void Complete() { } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { } } /// <summary> /// Fake option /// </summary> private enum TransactionScopeOption { Required, RequiresNew, Suppress, } #endif } } #endif
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ZXing.Common; using ZXing.Common.Detector; using ZXing.Common.ReedSolomon; namespace ZXing.Aztec.Internal { /// <summary> /// Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code /// is rotated or skewed, or partially obscured. /// </summary> /// <author>David Olivier</author> public sealed class Detector { private readonly BitMatrix image; private bool compact; private int nbLayers; private int nbDataBlocks; private int nbCenterLayers; private int shift; /// <summary> /// Initializes a new instance of the <see cref="Detector"/> class. /// </summary> /// <param name="image">The image.</param> public Detector(BitMatrix image) { this.image = image; } /// <summary> /// Detects an Aztec Code in an image. /// </summary> /// <returns>encapsulating results of detecting an Aztec Code</returns> public AztecDetectorResult detect() { // 1. Get the center of the aztec matrix Point pCenter = getMatrixCenter(); if (pCenter == null) return null; // 2. Get the corners of the center bull's eye Point[] bullEyeCornerPoints = getBullEyeCornerPoints(pCenter); if (bullEyeCornerPoints == null) return null; // 3. Get the size of the matrix from the bull's eye if (!extractParameters(bullEyeCornerPoints)) return null; // 4. Get the corners of the matrix ResultPoint[] corners = getMatrixCornerPoints(bullEyeCornerPoints); if (corners == null) return null; // 5. Sample the grid BitMatrix bits = sampleGrid(image, corners[shift % 4], corners[(shift + 3) % 4], corners[(shift + 2) % 4], corners[(shift + 1) % 4]); if (bits == null) return null; return new AztecDetectorResult(bits, corners, compact, nbDataBlocks, nbLayers); } /// <summary> /// Extracts the number of data layers and data blocks from the layer around the bull's eye /// </summary> /// <param name="bullEyeCornerPoints">bullEyeCornerPoints the array of bull's eye corners</param> /// <returns></returns> private bool extractParameters(Point[] bullEyeCornerPoints) { int twoCenterLayers = 2 * nbCenterLayers; // Get the bits around the bull's eye bool[] resab = sampleLine(bullEyeCornerPoints[0], bullEyeCornerPoints[1], twoCenterLayers + 1); bool[] resbc = sampleLine(bullEyeCornerPoints[1], bullEyeCornerPoints[2], twoCenterLayers + 1); bool[] rescd = sampleLine(bullEyeCornerPoints[2], bullEyeCornerPoints[3], twoCenterLayers + 1); bool[] resda = sampleLine(bullEyeCornerPoints[3], bullEyeCornerPoints[0], twoCenterLayers + 1); // Determine the orientation of the matrix if (resab[0] && resab[twoCenterLayers]) { shift = 0; } else if (resbc[0] && resbc[twoCenterLayers]) { shift = 1; } else if (rescd[0] && rescd[twoCenterLayers]) { shift = 2; } else if (resda[0] && resda[twoCenterLayers]) { shift = 3; } else { return false; } //d a // //c b // Flatten the bits in a single array bool[] parameterData; bool[] shiftedParameterData; if (compact) { shiftedParameterData = new bool[28]; for (int i = 0; i < 7; i++) { shiftedParameterData[i] = resab[2 + i]; shiftedParameterData[i + 7] = resbc[2 + i]; shiftedParameterData[i + 14] = rescd[2 + i]; shiftedParameterData[i + 21] = resda[2 + i]; } parameterData = new bool[28]; for (int i = 0; i < 28; i++) { parameterData[i] = shiftedParameterData[(i + shift * 7) % 28]; } } else { shiftedParameterData = new bool[40]; for (int i = 0; i < 11; i++) { if (i < 5) { shiftedParameterData[i] = resab[2 + i]; shiftedParameterData[i + 10] = resbc[2 + i]; shiftedParameterData[i + 20] = rescd[2 + i]; shiftedParameterData[i + 30] = resda[2 + i]; } if (i > 5) { shiftedParameterData[i - 1] = resab[2 + i]; shiftedParameterData[i + 10 - 1] = resbc[2 + i]; shiftedParameterData[i + 20 - 1] = rescd[2 + i]; shiftedParameterData[i + 30 - 1] = resda[2 + i]; } } parameterData = new bool[40]; for (int i = 0; i < 40; i++) { parameterData[i] = shiftedParameterData[(i + shift * 10) % 40]; } } // corrects the error using RS algorithm if (!correctParameterData(parameterData, compact)) return false; // gets the parameters from the bit array getParameters(parameterData); return true; } /// <summary> /// Gets the Aztec code corners from the bull's eye corners and the parameters /// </summary> /// <param name="bullEyeCornerPoints">the array of bull's eye corners</param> /// <returns>the array of aztec code corners</returns> private ResultPoint[] getMatrixCornerPoints(Point[] bullEyeCornerPoints) { float ratio = (2*nbLayers + (nbLayers > 4 ? 1 : 0) + (nbLayers - 4)/8) /(2.0f*nbCenterLayers); int dx = bullEyeCornerPoints[0].x - bullEyeCornerPoints[2].x; dx += dx > 0 ? 1 : -1; int dy = bullEyeCornerPoints[0].y - bullEyeCornerPoints[2].y; dy += dy > 0 ? 1 : -1; int targetcx = MathUtils.round(bullEyeCornerPoints[2].x - ratio*dx); int targetcy = MathUtils.round(bullEyeCornerPoints[2].y - ratio*dy); int targetax = MathUtils.round(bullEyeCornerPoints[0].x + ratio*dx); int targetay = MathUtils.round(bullEyeCornerPoints[0].y + ratio*dy); dx = bullEyeCornerPoints[1].x - bullEyeCornerPoints[3].x; dx += dx > 0 ? 1 : -1; dy = bullEyeCornerPoints[1].y - bullEyeCornerPoints[3].y; dy += dy > 0 ? 1 : -1; int targetdx = MathUtils.round(bullEyeCornerPoints[3].x - ratio*dx); int targetdy = MathUtils.round(bullEyeCornerPoints[3].y - ratio*dy); int targetbx = MathUtils.round(bullEyeCornerPoints[1].x + ratio*dx); int targetby = MathUtils.round(bullEyeCornerPoints[1].y + ratio*dy); if (!isValid(targetax, targetay) || !isValid(targetbx, targetby) || !isValid(targetcx, targetcy) || !isValid(targetdx, targetdy)) { return null; } return new[] { new ResultPoint(targetax, targetay), new ResultPoint(targetbx, targetby), new ResultPoint(targetcx, targetcy), new ResultPoint(targetdx, targetdy) }; } /// <summary> /// Corrects the parameter bits using Reed-Solomon algorithm /// </summary> /// <param name="parameterData">paremeter bits</param> /// <param name="compact">compact true if this is a compact Aztec code</param> /// <returns></returns> private static bool correctParameterData(bool[] parameterData, bool compact) { int numCodewords; int numDataCodewords; if (compact) { numCodewords = 7; numDataCodewords = 2; } else { numCodewords = 10; numDataCodewords = 4; } int numECCodewords = numCodewords - numDataCodewords; int[] parameterWords = new int[numCodewords]; const int codewordSize = 4; for (int i = 0; i < numCodewords; i++) { int flag = 1; for (int j = 1; j <= codewordSize; j++) { if (parameterData[codewordSize * i + codewordSize - j]) { parameterWords[i] += flag; } flag <<= 1; } } var rsDecoder = new ReedSolomonDecoder(GenericGF.AZTEC_PARAM); if (!rsDecoder.decode(parameterWords, numECCodewords)) return false; for (int i = 0; i < numDataCodewords; i++) { int flag = 1; for (int j = 1; j <= codewordSize; j++) { parameterData[i * codewordSize + codewordSize - j] = (parameterWords[i] & flag) == flag; flag <<= 1; } } return true; } /// <summary> /// Finds the corners of a bull-eye centered on the passed point /// </summary> /// <param name="pCenter">Center point</param> /// <returns>The corners of the bull-eye</returns> private Point[] getBullEyeCornerPoints(Point pCenter) { Point pina = pCenter; Point pinb = pCenter; Point pinc = pCenter; Point pind = pCenter; bool color = true; for (nbCenterLayers = 1; nbCenterLayers < 9; nbCenterLayers++) { Point pouta = getFirstDifferent(pina, color, 1, -1); Point poutb = getFirstDifferent(pinb, color, 1, 1); Point poutc = getFirstDifferent(pinc, color, -1, 1); Point poutd = getFirstDifferent(pind, color, -1, -1); //d a // //c b if (nbCenterLayers > 2) { float q = distance(poutd, pouta)*nbCenterLayers/(distance(pind, pina)*(nbCenterLayers + 2)); if (q < 0.75 || q > 1.25 || !isWhiteOrBlackRectangle(pouta, poutb, poutc, poutd)) { break; } } pina = pouta; pinb = poutb; pinc = poutc; pind = poutd; color = !color; } if (nbCenterLayers != 5 && nbCenterLayers != 7) { return null; } compact = nbCenterLayers == 5; float ratio = 0.75f*2/(2*nbCenterLayers - 3); int dx = pina.x - pinc.x; int dy = pina.y - pinc.y; int targetcx = MathUtils.round(pinc.x - ratio*dx); int targetcy = MathUtils.round(pinc.y - ratio*dy); int targetax = MathUtils.round(pina.x + ratio*dx); int targetay = MathUtils.round(pina.y + ratio*dy); dx = pinb.x - pind.x; dy = pinb.y - pind.y; int targetdx = MathUtils.round(pind.x - ratio*dx); int targetdy = MathUtils.round(pind.y - ratio*dy); int targetbx = MathUtils.round(pinb.x + ratio*dx); int targetby = MathUtils.round(pinb.y + ratio*dy); if (!isValid(targetax, targetay) || !isValid(targetbx, targetby) || !isValid(targetcx, targetcy) || !isValid(targetdx, targetdy)) { return null; } return new[] { new Point(targetax, targetay), new Point(targetbx, targetby), new Point(targetcx, targetcy), new Point(targetdx, targetdy) }; } /// <summary> /// Finds a candidate center point of an Aztec code from an image /// </summary> /// <returns>the center point</returns> private Point getMatrixCenter() { ResultPoint pointA; ResultPoint pointB; ResultPoint pointC; ResultPoint pointD; int cx; int cy; //Get a white rectangle that can be the border of the matrix in center bull's eye or var whiteDetector = WhiteRectangleDetector.Create(image); if (whiteDetector == null) return null; ResultPoint[] cornerPoints = whiteDetector.detect(); if (cornerPoints != null) { pointA = cornerPoints[0]; pointB = cornerPoints[1]; pointC = cornerPoints[2]; pointD = cornerPoints[3]; } else { // This exception can be in case the initial rectangle is white // In that case, surely in the bull's eye, we try to expand the rectangle. cx = image.Width/2; cy = image.Height/2; pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint(); pointB = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint(); pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint(); pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint(); } //Compute the center of the rectangle cx = MathUtils.round((pointA.X + pointD.X + pointB.X + pointC.X) / 4.0f); cy = MathUtils.round((pointA.Y + pointD.Y + pointB.Y + pointC.Y) / 4.0f); // Redetermine the white rectangle starting from previously computed center. // This will ensure that we end up with a white rectangle in center bull's eye // in order to compute a more accurate center. whiteDetector = WhiteRectangleDetector.Create(image, 15, cx, cy); if (whiteDetector == null) return null; cornerPoints = whiteDetector.detect(); if (cornerPoints != null) { pointA = cornerPoints[0]; pointB = cornerPoints[1]; pointC = cornerPoints[2]; pointD = cornerPoints[3]; } else { // This exception can be in case the initial rectangle is white // In that case we try to expand the rectangle. pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint(); pointB = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint(); pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint(); pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint(); } // Recompute the center of the rectangle cx = MathUtils.round((pointA.X + pointD.X + pointB.X + pointC.X) / 4.0f); cy = MathUtils.round((pointA.Y + pointD.Y + pointB.Y + pointC.Y) / 4.0f); return new Point(cx, cy); } /// <summary> /// Samples an Aztec matrix from an image /// </summary> /// <param name="image">The image.</param> /// <param name="topLeft">The top left.</param> /// <param name="bottomLeft">The bottom left.</param> /// <param name="bottomRight">The bottom right.</param> /// <param name="topRight">The top right.</param> /// <returns></returns> private BitMatrix sampleGrid(BitMatrix image, ResultPoint topLeft, ResultPoint bottomLeft, ResultPoint bottomRight, ResultPoint topRight) { int dimension; if (compact) { dimension = 4 * nbLayers + 11; } else { if (nbLayers <= 4) { dimension = 4 * nbLayers + 15; } else { dimension = 4 * nbLayers + 2 * ((nbLayers - 4) / 8 + 1) + 15; } } GridSampler sampler = GridSampler.Instance; return sampler.sampleGrid(image, dimension, dimension, 0.5f, 0.5f, dimension - 0.5f, 0.5f, dimension - 0.5f, dimension - 0.5f, 0.5f, dimension - 0.5f, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRight.X, bottomRight.Y, bottomLeft.X, bottomLeft.Y); } /// <summary> /// Sets number of layers and number of data blocks from parameter bits /// </summary> /// <param name="parameterData">The parameter data.</param> private void getParameters(bool[] parameterData) { int nbBitsForNbLayers; int nbBitsForNbDatablocks; if (compact) { nbBitsForNbLayers = 2; nbBitsForNbDatablocks = 6; } else { nbBitsForNbLayers = 5; nbBitsForNbDatablocks = 11; } for (int i = 0; i < nbBitsForNbLayers; i++) { nbLayers <<= 1; if (parameterData[i]) { nbLayers++; } } for (int i = nbBitsForNbLayers; i < nbBitsForNbLayers + nbBitsForNbDatablocks; i++) { nbDataBlocks <<= 1; if (parameterData[i]) { nbDataBlocks++; } } nbLayers++; nbDataBlocks++; } /// <summary> /// Samples a line /// </summary> /// <param name="p1">first point</param> /// <param name="p2">second point</param> /// <param name="size">size number of bits</param> /// <returns>the array of bits</returns> private bool[] sampleLine(Point p1, Point p2, int size) { bool[] res = new bool[size]; float d = distance(p1, p2); float moduleSize = d / (size - 1); float dx = moduleSize * (p2.x - p1.x) / d; float dy = moduleSize * (p2.y - p1.y) / d; float px = p1.x; float py = p1.y; for (int i = 0; i < size; i++) { res[i] = image[MathUtils.round(px), MathUtils.round(py)]; px += dx; py += dy; } return res; } /// <summary> /// Determines whether [is white or black rectangle] [the specified p1]. /// </summary> /// <param name="p1">The p1.</param> /// <param name="p2">The p2.</param> /// <param name="p3">The p3.</param> /// <param name="p4">The p4.</param> /// <returns>true if the border of the rectangle passed in parameter is compound of white points only /// or black points only</returns> private bool isWhiteOrBlackRectangle(Point p1, Point p2, Point p3, Point p4) { const int corr = 3; p1 = new Point(p1.x - corr, p1.y + corr); p2 = new Point(p2.x - corr, p2.y - corr); p3 = new Point(p3.x + corr, p3.y - corr); p4 = new Point(p4.x + corr, p4.y + corr); int cInit = getColor(p4, p1); if (cInit == 0) { return false; } int c = getColor(p1, p2); if (c != cInit) { return false; } c = getColor(p2, p3); if (c != cInit) { return false; } c = getColor(p3, p4); return c == cInit; } /// <summary> /// Gets the color of a segment /// </summary> /// <param name="p1">The p1.</param> /// <param name="p2">The p2.</param> /// <returns>1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else</returns> private int getColor(Point p1, Point p2) { float d = distance(p1, p2); float dx = (p2.x - p1.x) / d; float dy = (p2.y - p1.y) / d; int error = 0; float px = p1.x; float py = p1.y; bool colorModel = image[p1.x, p1.y]; for (int i = 0; i < d; i++) { px += dx; py += dy; if (image[MathUtils.round(px), MathUtils.round(py)] != colorModel) { error++; } } float errRatio = error / d; if (errRatio > 0.1f && errRatio < 0.9f) { return 0; } return (errRatio <= 0.1f) == colorModel ? 1 : -1; } /// <summary> /// Gets the coordinate of the first point with a different color in the given direction /// </summary> /// <param name="init">The init.</param> /// <param name="color">if set to <c>true</c> [color].</param> /// <param name="dx">The dx.</param> /// <param name="dy">The dy.</param> /// <returns></returns> private Point getFirstDifferent(Point init, bool color, int dx, int dy) { int x = init.x + dx; int y = init.y + dy; while (isValid(x, y) && image[x, y] == color) { x += dx; y += dy; } x -= dx; y -= dy; while (isValid(x, y) && image[x, y] == color) { x += dx; } x -= dx; while (isValid(x, y) && image[x, y] == color) { y += dy; } y -= dy; return new Point(x, y); } private bool isValid(int x, int y) { return x >= 0 && x < image.Width && y > 0 && y < image.Height; } // L2 distance private static float distance(Point a, Point b) { return MathUtils.distance(a.x, a.y, b.x, b.y); } internal sealed class Point { public int x; public int y; public ResultPoint toResultPoint() { return new ResultPoint(x, y); } internal Point(int x, int y) { this.x = x; this.y = y; } } } }
// Shared.cs // ------------------------------------------------------------------ // // Copyright (c) 2006-2011 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // Last Saved: <2011-August-02 19:41:01> // // ------------------------------------------------------------------ // // This module defines some shared utility classes and methods. // // Created: Tue, 27 Mar 2007 15:30 // using System; using System.IO; using System.Security.Permissions; namespace Ionic.Zip { /// <summary> /// Collects general purpose utility methods. /// </summary> internal static class SharedUtilities { /// private null constructor //private SharedUtilities() { } // workitem 8423 public static Int64 GetFileLength(string fileName) { if (!File.Exists(fileName)) throw new System.IO.FileNotFoundException(fileName); long fileLength = 0L; FileShare fs = FileShare.ReadWrite; #if !NETCF // FileShare.Delete is not defined for the Compact Framework fs |= FileShare.Delete; #endif using (var s = File.Open(fileName, FileMode.Open, FileAccess.Read, fs)) { fileLength = s.Length; } return fileLength; } [System.Diagnostics.Conditional("NETCF")] public static void Workaround_Ladybug318918(Stream s) { // This is a workaround for this issue: // https://connect.microsoft.com/VisualStudio/feedback/details/318918 // It's required only on NETCF. s.Flush(); } #if LEGACY /// <summary> /// Round the given DateTime value to an even second value. /// </summary> /// /// <remarks> /// <para> /// Round up in the case of an odd second value. The rounding does not consider /// fractional seconds. /// </para> /// <para> /// This is useful because the Zip spec allows storage of time only to the nearest /// even second. So if you want to compare the time of an entry in the archive with /// it's actual time in the filesystem, you need to round the actual filesystem /// time, or use a 2-second threshold for the comparison. /// </para> /// <para> /// This is most nautrally an extension method for the DateTime class but this /// library is built for .NET 2.0, not for .NET 3.5; This means extension methods /// are a no-no. /// </para> /// </remarks> /// <param name="source">The DateTime value to round</param> /// <returns>The ruonded DateTime value</returns> public static DateTime RoundToEvenSecond(DateTime source) { // round to nearest second: if ((source.Second % 2) == 1) source += new TimeSpan(0, 0, 1); DateTime dtRounded = new DateTime(source.Year, source.Month, source.Day, source.Hour, source.Minute, source.Second); //if (source.Millisecond >= 500) dtRounded = dtRounded.AddSeconds(1); return dtRounded; } #endif #if YOU_LIKE_REDUNDANT_CODE internal static string NormalizePath(string path) { // remove leading single dot slash if (path.StartsWith(".\\")) path = path.Substring(2); // remove intervening dot-slash path = path.Replace("\\.\\", "\\"); // remove double dot when preceded by a directory name var re = new System.Text.RegularExpressions.Regex(@"^(.*\\)?([^\\\.]+\\\.\.\\)(.+)$"); path = re.Replace(path, "$1$3"); return path; } #endif private static System.Text.RegularExpressions.Regex doubleDotRegex1 = new System.Text.RegularExpressions.Regex(@"^(.*/)?([^/\\.]+/\\.\\./)(.+)$"); private static string SimplifyFwdSlashPath(string path) { if (path.StartsWith("./")) path = path.Substring(2); path = path.Replace("/./", "/"); // Replace foo/anything/../bar with foo/bar path = doubleDotRegex1.Replace(path, "$1$3"); return path; } /// <summary> /// Utility routine for transforming path names from filesystem format (on Windows that means backslashes) to /// a format suitable for use within zipfiles. This means trimming the volume letter and colon (if any) And /// swapping backslashes for forward slashes. /// </summary> /// <param name="pathName">source path.</param> /// <returns>transformed path</returns> public static string NormalizePathForUseInZipFile(string pathName) { // boundary case if (String.IsNullOrEmpty(pathName)) return pathName; // trim volume if necessary if ((pathName.Length >= 2) && ((pathName[1] == ':') && (pathName[2] == '\\'))) pathName = pathName.Substring(3); // swap slashes pathName = pathName.Replace('\\', '/'); // trim all leading slashes while (pathName.StartsWith("/")) pathName = pathName.Substring(1); return SimplifyFwdSlashPath(pathName); } static System.Text.Encoding ibm437 = System.Text.Encoding.GetEncoding("IBM437"); static System.Text.Encoding utf8 = System.Text.Encoding.GetEncoding("UTF-8"); internal static byte[] StringToByteArray(string value, System.Text.Encoding encoding) { byte[] a = encoding.GetBytes(value); return a; } internal static byte[] StringToByteArray(string value) { return StringToByteArray(value, ibm437); } //internal static byte[] Utf8StringToByteArray(string value) //{ // return StringToByteArray(value, utf8); //} //internal static string StringFromBuffer(byte[] buf, int maxlength) //{ // return StringFromBuffer(buf, maxlength, ibm437); //} internal static string Utf8StringFromBuffer(byte[] buf) { return StringFromBuffer(buf, utf8); } internal static string StringFromBuffer(byte[] buf, System.Text.Encoding encoding) { // this form of the GetString() method is required for .NET CF compatibility string s = encoding.GetString(buf, 0, buf.Length); return s; } internal static int ReadSignature(System.IO.Stream s) { int x = 0; try { x = _ReadFourBytes(s, "n/a"); } catch (BadReadException) { } return x; } internal static int ReadEntrySignature(System.IO.Stream s) { // handle the case of ill-formatted zip archives - includes a data descriptor // when none is expected. int x = 0; try { x = _ReadFourBytes(s, "n/a"); if (x == ZipConstants.ZipEntryDataDescriptorSignature) { // advance past data descriptor - 12 bytes if not zip64 s.Seek(12, SeekOrigin.Current); // workitem 10178 Workaround_Ladybug318918(s); x = _ReadFourBytes(s, "n/a"); if (x != ZipConstants.ZipEntrySignature) { // Maybe zip64 was in use for the prior entry. // Therefore, skip another 8 bytes. s.Seek(8, SeekOrigin.Current); // workitem 10178 Workaround_Ladybug318918(s); x = _ReadFourBytes(s, "n/a"); if (x != ZipConstants.ZipEntrySignature) { // seek back to the first spot s.Seek(-24, SeekOrigin.Current); // workitem 10178 Workaround_Ladybug318918(s); x = _ReadFourBytes(s, "n/a"); } } } } catch (BadReadException) { } return x; } internal static int ReadInt(System.IO.Stream s) { return _ReadFourBytes(s, "Could not read block - no data! (position 0x{0:X8})"); } private static int _ReadFourBytes(System.IO.Stream s, string message) { int n = 0; byte[] block = new byte[4]; #if NETCF // workitem 9181 // Reading here in NETCF sometimes reads "backwards". Seems to happen for // larger files. Not sure why. Maybe an error in caching. If the data is: // // 00100210: 9efa 0f00 7072 6f6a 6563 742e 6963 7750 ....project.icwP // 00100220: 4b05 0600 0000 0006 0006 0091 0100 008e K............... // 00100230: 0010 0000 00 ..... // // ...and the stream Position is 10021F, then a Read of 4 bytes is returning // 50776369, instead of 06054b50. This seems to happen the 2nd time Read() // is called from that Position.. // // submitted to connect.microsoft.com // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=318918#tabs // for (int i = 0; i < block.Length; i++) { n+= s.Read(block, i, 1); } #else n = s.Read(block, 0, block.Length); #endif if (n != block.Length) throw new BadReadException(String.Format(message, s.Position)); int data = unchecked((((block[3] * 256 + block[2]) * 256) + block[1]) * 256 + block[0]); return data; } /// <summary> /// Finds a signature in the zip stream. This is useful for finding /// the end of a zip entry, for example, or the beginning of the next ZipEntry. /// </summary> /// /// <remarks> /// <para> /// Scans through 64k at a time. /// </para> /// /// <para> /// If the method fails to find the requested signature, the stream Position /// after completion of this method is unchanged. If the method succeeds in /// finding the requested signature, the stream position after completion is /// direct AFTER the signature found in the stream. /// </para> /// </remarks> /// /// <param name="stream">The stream to search</param> /// <param name="SignatureToFind">The 4-byte signature to find</param> /// <returns>The number of bytes read</returns> internal static long FindSignature(System.IO.Stream stream, int SignatureToFind) { long startingPosition = stream.Position; int BATCH_SIZE = 65536; // 8192; byte[] targetBytes = new byte[4]; targetBytes[0] = (byte)(SignatureToFind >> 24); targetBytes[1] = (byte)((SignatureToFind & 0x00FF0000) >> 16); targetBytes[2] = (byte)((SignatureToFind & 0x0000FF00) >> 8); targetBytes[3] = (byte)(SignatureToFind & 0x000000FF); byte[] batch = new byte[BATCH_SIZE]; int n = 0; bool success = false; do { n = stream.Read(batch, 0, batch.Length); if (n != 0) { for (int i = 0; i < n; i++) { if (batch[i] == targetBytes[3]) { long curPosition = stream.Position; stream.Seek(i - n, System.IO.SeekOrigin.Current); // workitem 10178 Workaround_Ladybug318918(stream); // workitem 7711 int sig = ReadSignature(stream); success = (sig == SignatureToFind); if (!success) { stream.Seek(curPosition, System.IO.SeekOrigin.Begin); // workitem 10178 Workaround_Ladybug318918(stream); } else break; // out of for loop } } } else break; if (success) break; } while (true); if (!success) { stream.Seek(startingPosition, System.IO.SeekOrigin.Begin); // workitem 10178 Workaround_Ladybug318918(stream); return -1; // or throw? } // subtract 4 for the signature. long bytesRead = (stream.Position - startingPosition) - 4; return bytesRead; } // If I have a time in the .NET environment, and I want to use it for // SetWastWriteTime() etc, then I need to adjust it for Win32. internal static DateTime AdjustTime_Reverse(DateTime time) { if (time.Kind == DateTimeKind.Utc) return time; DateTime adjusted = time; if (DateTime.Now.IsDaylightSavingTime() && !time.IsDaylightSavingTime()) adjusted = time - new System.TimeSpan(1, 0, 0); else if (!DateTime.Now.IsDaylightSavingTime() && time.IsDaylightSavingTime()) adjusted = time + new System.TimeSpan(1, 0, 0); return adjusted; } #if NECESSARY // If I read a time from a file with GetLastWriteTime() (etc), I need // to adjust it for display in the .NET environment. internal static DateTime AdjustTime_Forward(DateTime time) { if (time.Kind == DateTimeKind.Utc) return time; DateTime adjusted = time; if (DateTime.Now.IsDaylightSavingTime() && !time.IsDaylightSavingTime()) adjusted = time + new System.TimeSpan(1, 0, 0); else if (!DateTime.Now.IsDaylightSavingTime() && time.IsDaylightSavingTime()) adjusted = time - new System.TimeSpan(1, 0, 0); return adjusted; } #endif internal static DateTime PackedToDateTime(Int32 packedDateTime) { // workitem 7074 & workitem 7170 if (packedDateTime == 0xFFFF || packedDateTime == 0) return new System.DateTime(1995, 1, 1, 0, 0, 0, 0); // return a fixed date when none is supplied. Int16 packedTime = unchecked((Int16)(packedDateTime & 0x0000ffff)); Int16 packedDate = unchecked((Int16)((packedDateTime & 0xffff0000) >> 16)); int year = 1980 + ((packedDate & 0xFE00) >> 9); int month = (packedDate & 0x01E0) >> 5; int day = packedDate & 0x001F; int hour = (packedTime & 0xF800) >> 11; int minute = (packedTime & 0x07E0) >> 5; //int second = packedTime & 0x001F; int second = (packedTime & 0x001F) * 2; // validation and error checking. // this is not foolproof but will catch most errors. if (second >= 60) { minute++; second = 0; } if (minute >= 60) { hour++; minute = 0; } if (hour >= 24) { day++; hour = 0; } DateTime d = System.DateTime.Now; bool success = false; try { d = new System.DateTime(year, month, day, hour, minute, second, 0); success = true; } catch (System.ArgumentOutOfRangeException) { if (year == 1980 && (month == 0 || day == 0)) { try { d = new System.DateTime(1980, 1, 1, hour, minute, second, 0); success = true; } catch (System.ArgumentOutOfRangeException) { try { d = new System.DateTime(1980, 1, 1, 0, 0, 0, 0); success = true; } catch (System.ArgumentOutOfRangeException) { } } } // workitem 8814 // my god, I can't believe how many different ways applications // can mess up a simple date format. else { try { while (year < 1980) year++; while (year > 2030) year--; while (month < 1) month++; while (month > 12) month--; while (day < 1) day++; while (day > 28) day--; while (minute < 0) minute++; while (minute > 59) minute--; while (second < 0) second++; while (second > 59) second--; d = new System.DateTime(year, month, day, hour, minute, second, 0); success = true; } catch (System.ArgumentOutOfRangeException) { } } } if (!success) { string msg = String.Format("y({0}) m({1}) d({2}) h({3}) m({4}) s({5})", year, month, day, hour, minute, second); throw new ZipException(String.Format("Bad date/time format in the zip file. ({0})", msg)); } // workitem 6191 //d = AdjustTime_Reverse(d); d = DateTime.SpecifyKind(d, DateTimeKind.Local); return d; } internal static Int32 DateTimeToPacked(DateTime time) { // The time is passed in here only for purposes of writing LastModified to the // zip archive. It should always be LocalTime, but we convert anyway. And, // since the time is being written out, it needs to be adjusted. time = time.ToLocalTime(); // workitem 7966 //time = AdjustTime_Forward(time); // see http://www.vsft.com/hal/dostime.htm for the format UInt16 packedDate = (UInt16)((time.Day & 0x0000001F) | ((time.Month << 5) & 0x000001E0) | (((time.Year - 1980) << 9) & 0x0000FE00)); UInt16 packedTime = (UInt16)((time.Second / 2 & 0x0000001F) | ((time.Minute << 5) & 0x000007E0) | ((time.Hour << 11) & 0x0000F800)); Int32 result = (Int32)(((UInt32)(packedDate << 16)) | packedTime); return result; } /// <summary> /// Create a pseudo-random filename, suitable for use as a temporary /// file, and open it. /// </summary> /// <remarks> /// <para> /// The System.IO.Path.GetRandomFileName() method is not available on /// the Compact Framework, so this library provides its own substitute /// on NETCF. /// </para> /// <para> /// This method produces a filename of the form /// DotNetZip-xxxxxxxx.tmp, where xxxxxxxx is replaced by randomly /// chosen characters, and creates that file. /// </para> /// </remarks> public static void CreateAndOpenUniqueTempFile(string dir, out Stream fs, out string filename) { // workitem 9763 // http://dotnet.org.za/markn/archive/2006/04/15/51594.aspx // try 3 times: for (int i = 0; i < 3; i++) { try { filename = Path.Combine(dir, InternalGetTempFileName()); fs = new FileStream(filename, FileMode.CreateNew); return; } catch (IOException) { if (i == 2) throw; } } throw new IOException(); } #if NETCF || SILVERLIGHT public static string InternalGetTempFileName() { return "DotNetZip-" + GenerateRandomStringImpl(8,0) + ".tmp"; } internal static string GenerateRandomStringImpl(int length, int delta) { bool WantMixedCase = (delta == 0); System.Random rnd = new System.Random(); string result = ""; char[] a = new char[length]; for (int i = 0; i < length; i++) { // delta == 65 means uppercase // delta == 97 means lowercase if (WantMixedCase) delta = (rnd.Next(2) == 0) ? 65 : 97; a[i] = (char)(rnd.Next(26) + delta); } result = new System.String(a); return result; } #else public static string InternalGetTempFileName() { return "DotNetZip-" + Path.GetRandomFileName().Substring(0, 8) + ".tmp"; } #endif /// <summary> /// Workitem 7889: handle ERROR_LOCK_VIOLATION during read /// </summary> /// <remarks> /// This could be gracefully handled with an extension attribute, but /// This assembly is built for .NET 2.0, so I cannot use them. /// </remarks> internal static int ReadWithRetry(System.IO.Stream s, byte[] buffer, int offset, int count, string FileName) { int n = 0; bool done = false; #if !NETCF && !SILVERLIGHT int retries = 0; #endif do { try { n = s.Read(buffer, offset, count); done = true; } #if NETCF || SILVERLIGHT catch (System.IO.IOException) { throw; } #else catch (System.IO.IOException ioexc1) { // Check if we can call GetHRForException, // which makes unmanaged code calls. var p = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); if (p.IsUnrestricted()) { uint hresult = _HRForException(ioexc1); if (hresult != 0x80070021) // ERROR_LOCK_VIOLATION throw new System.IO.IOException(String.Format("Cannot read file {0}", FileName), ioexc1); retries++; if (retries > 10) throw new System.IO.IOException(String.Format("Cannot read file {0}, at offset 0x{1:X8} after 10 retries", FileName, offset), ioexc1); // max time waited on last retry = 250 + 10*550 = 5.75s // aggregate time waited after 10 retries: 250 + 55*550 = 30.5s System.Threading.Thread.Sleep(250 + retries * 550); } else { // The permission.Demand() failed. Therefore, we cannot call // GetHRForException, and cannot do the subtle handling of // ERROR_LOCK_VIOLATION. Just bail. throw; } } #endif } while (!done); return n; } #if !NETCF // workitem 8009 // // This method must remain separate. // // Marshal.GetHRForException() is needed to do special exception handling for // the read. But, that method requires UnmanagedCode permissions, and is marked // with LinkDemand for UnmanagedCode. In an ASP.NET medium trust environment, // where UnmanagedCode is restricted, will generate a SecurityException at the // time of JIT of the method that calls a method that is marked with LinkDemand // for UnmanagedCode. The SecurityException, if it is restricted, will occur // when this method is JITed. // // The Marshal.GetHRForException() is factored out of ReadWithRetry in order to // avoid the SecurityException at JIT compile time. Because _HRForException is // called only when the UnmanagedCode is allowed. This means .NET never // JIT-compiles this method when UnmanagedCode is disallowed, and thus never // generates the JIT-compile time exception. // #endif private static uint _HRForException(System.Exception ex1) { return unchecked((uint)System.Runtime.InteropServices.Marshal.GetHRForException(ex1)); } } /// <summary> /// A decorator stream. It wraps another stream, and performs bookkeeping /// to keep track of the stream Position. /// </summary> /// <remarks> /// <para> /// In some cases, it is not possible to get the Position of a stream, let's /// say, on a write-only output stream like ASP.NET's /// <c>Response.OutputStream</c>, or on a different write-only stream /// provided as the destination for the zip by the application. In this /// case, programmers can use this counting stream to count the bytes read /// or written. /// </para> /// <para> /// Consider the scenario of an application that saves a self-extracting /// archive (SFX), that uses a custom SFX stub. /// </para> /// <para> /// Saving to a filesystem file, the application would open the /// filesystem file (getting a <c>FileStream</c>), save the custom sfx stub /// into it, and then call <c>ZipFile.Save()</c>, specifying the same /// FileStream. <c>ZipFile.Save()</c> does the right thing for the zipentry /// offsets, by inquiring the Position of the <c>FileStream</c> before writing /// any data, and then adding that initial offset into any ZipEntry /// offsets in the zip directory. Everything works fine. /// </para> /// <para> /// Now suppose the application is an ASPNET application and it saves /// directly to <c>Response.OutputStream</c>. It's not possible for DotNetZip to /// inquire the <c>Position</c>, so the offsets for the SFX will be wrong. /// </para> /// <para> /// The workaround is for the application to use this class to wrap /// <c>HttpResponse.OutputStream</c>, then write the SFX stub and the ZipFile /// into that wrapper stream. Because <c>ZipFile.Save()</c> can inquire the /// <c>Position</c>, it will then do the right thing with the offsets. /// </para> /// </remarks> internal class CountingStream : System.IO.Stream { // workitem 12374: this class is now public private System.IO.Stream _s; private Int64 _bytesWritten; private Int64 _bytesRead; private Int64 _initialOffset; /// <summary> /// The constructor. /// </summary> /// <param name="stream">The underlying stream</param> public CountingStream(System.IO.Stream stream) : base() { _s = stream; try { _initialOffset = _s.Position; } catch { _initialOffset = 0L; } } /// <summary> /// Gets the wrapped stream. /// </summary> public Stream WrappedStream { get { return _s; } } /// <summary> /// The count of bytes written out to the stream. /// </summary> public Int64 BytesWritten { get { return _bytesWritten; } } /// <summary> /// the count of bytes that have been read from the stream. /// </summary> public Int64 BytesRead { get { return _bytesRead; } } /// <summary> /// Adjust the byte count on the stream. /// </summary> /// /// <param name='delta'> /// the number of bytes to subtract from the count. /// </param> /// /// <remarks> /// <para> /// Subtract delta from the count of bytes written to the stream. /// This is necessary when seeking back, and writing additional data, /// as happens in some cases when saving Zip files. /// </para> /// </remarks> public void Adjust(Int64 delta) { _bytesWritten -= delta; if (_bytesWritten < 0) throw new InvalidOperationException(); if (_s as CountingStream != null) ((CountingStream)_s).Adjust(delta); } /// <summary> /// The read method. /// </summary> /// <param name="buffer">The buffer to hold the data read from the stream.</param> /// <param name="offset">the offset within the buffer to copy the first byte read.</param> /// <param name="count">the number of bytes to read.</param> /// <returns>the number of bytes read, after decryption and decompression.</returns> public override int Read(byte[] buffer, int offset, int count) { int n = _s.Read(buffer, offset, count); _bytesRead += n; return n; } /// <summary> /// Write data into the stream. /// </summary> /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (count == 0) return; _s.Write(buffer, offset, count); _bytesWritten += count; } /// <summary> /// Whether the stream can be read. /// </summary> public override bool CanRead { get { return _s.CanRead; } } /// <summary> /// Whether it is possible to call Seek() on the stream. /// </summary> public override bool CanSeek { get { return _s.CanSeek; } } /// <summary> /// Whether it is possible to call Write() on the stream. /// </summary> public override bool CanWrite { get { return _s.CanWrite; } } /// <summary> /// Flushes the underlying stream. /// </summary> public override void Flush() { _s.Flush(); } /// <summary> /// The length of the underlying stream. /// </summary> public override long Length { get { return _s.Length; } // bytesWritten?? } /// <summary> /// Returns the sum of number of bytes written, plus the initial /// offset before writing. /// </summary> public long ComputedPosition { get { return _initialOffset + _bytesWritten; } } /// <summary> /// The Position of the stream. /// </summary> public override long Position { get { return _s.Position; } set { _s.Seek(value, System.IO.SeekOrigin.Begin); // workitem 10178 Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(_s); } } /// <summary> /// Seek in the stream. /// </summary> /// <param name="offset">the offset point to seek to</param> /// <param name="origin">the reference point from which to seek</param> /// <returns>The new position</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { return _s.Seek(offset, origin); } /// <summary> /// Set the length of the underlying stream. Be careful with this! /// </summary> /// /// <param name='value'>the length to set on the underlying stream.</param> public override void SetLength(long value) { _s.SetLength(value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { public class MemoryMappedFileTests_CreateOrOpen : MemoryMappedFilesTestBase { /// <summary> /// Tests invalid arguments to the CreateOrOpen mapName parameter. /// </summary> [Fact] public void InvalidArguments_MapName() { // null is an invalid map name with CreateOrOpen (it's valid with CreateNew and CreateFromFile) AssertExtensions.Throws<ArgumentNullException>("mapName", () => MemoryMappedFile.CreateOrOpen(null, 4096)); AssertExtensions.Throws<ArgumentNullException>("mapName", () => MemoryMappedFile.CreateOrOpen(null, 4096, MemoryMappedFileAccess.ReadWrite)); AssertExtensions.Throws<ArgumentNullException>("mapName", () => MemoryMappedFile.CreateOrOpen(null, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); // Empty string is always an invalid map name Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateOrOpen(string.Empty, 4096)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateOrOpen(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateOrOpen(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Test to verify that map names are left unsupported on Unix. /// </summary> [PlatformSpecific(TestPlatforms.AnyUnix)] // Map names not supported on Unix [Theory] [MemberData(nameof(CreateValidMapNames))] public void MapNamesNotSupported_Unix(string mapName) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateOrOpen(mapName, 4096)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateOrOpen(mapName, 4096, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateOrOpen(mapName, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateOrOpen capacity parameter. /// </summary> [Theory] [InlineData(0)] // can't create a new map with a default capacity [InlineData(-1)] // negative capacities don't make sense public void InvalidArguments_Capacity(long capacity) { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), capacity)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), capacity, MemoryMappedFileAccess.ReadWrite)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateOrOpen capacity parameter. /// </summary> [Fact] public void InvalidArguments_Capacity_TooLarge() { // On 32-bit, values larger than uint.MaxValue aren't allowed if (IntPtr.Size == 4) { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 1 + (long)uint.MaxValue)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } } /// <summary> /// Tests invalid arguments to the CreateOrOpen access parameter. /// </summary> [Theory] [InlineData((MemoryMappedFileAccess)(-1))] [InlineData((MemoryMappedFileAccess)(42))] public void InvalidArgument_Access(MemoryMappedFileAccess access) { AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, access)); AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, access, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateOrOpen options parameter. /// </summary> [Theory] [InlineData((MemoryMappedFileOptions)(-1))] [InlineData((MemoryMappedFileOptions)(42))] public void InvalidArgument_Options(MemoryMappedFileOptions options) { AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, options, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateOrOpen inheritability parameter. /// </summary> [Theory] [InlineData((HandleInheritability)(-1))] [InlineData((HandleInheritability)(42))] public void InvalidArgument_Inheritability(HandleInheritability inheritability) { AssertExtensions.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, inheritability)); } /// <summary> /// Test various combinations of arguments to CreateOrOpen, validating the created maps each time they're created, /// focusing on accesses that don't involve execute permissions. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Map names not supported on Unix [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinations), new string[] { "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite }, new MemoryMappedFileOptions[] { MemoryMappedFileOptions.None, MemoryMappedFileOptions.DelayAllocatePages }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable })] public void ValidArgumentCombinations_NonExecute( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { // Map doesn't exist using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Map does exist (CreateNew) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf2, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf2, capacity, access, inheritability); } // Map does exist (CreateFromFile) using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity)) { ValidateMemoryMappedFile(mmf2, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } } /// <summary> /// Test various combinations of arguments to CreateOrOpen, validating the created maps each time they're created, /// focusing on accesses that involve execute permissions. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Map names not supported on Unix [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinations), new string[] { "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute }, new MemoryMappedFileOptions[] { MemoryMappedFileOptions.None, MemoryMappedFileOptions.DelayAllocatePages }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable })] public void ValidArgumentCombinations_Execute( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { // Map doesn't exist using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Map does exist (CreateNew) using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf2, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf2, capacity, access, inheritability); } // (Avoid testing with CreateFromFile when using execute permissions.) } /// <summary> /// Provides input data to the ValidArgumentCombinations 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</param> /// <param name="options">The options to yield.</param> /// <param name="inheritabilities">The inheritabilities to yield.</param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinations( string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, MemoryMappedFileOptions[] options, HandleInheritability[] inheritabilities) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { foreach (MemoryMappedFileOptions option in options) { foreach (HandleInheritability inheritability in inheritabilities) { string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mapName, capacity, access, option, inheritability }; } } } } } } /// <summary> /// Test to validate behavior with MemoryMappedFileAccess.Write. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Map names not supported on Unix [Fact] public void OpenWrite() { // Write-only access fails when the map doesn't exist AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write)); AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, MemoryMappedFileOptions.None, HandleInheritability.None)); // Write-only access works when the map does exist const int Capacity = 4096; string name = CreateUniqueMapName(); using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(name, Capacity)) using (MemoryMappedFile opened = MemoryMappedFile.CreateOrOpen(name, Capacity, MemoryMappedFileAccess.Write)) { ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Write); } } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Map names not supported on Unix [Fact] public void TooLargeCapacity() { if (IntPtr.Size == 4) { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 1 + (long)uint.MaxValue)); } else { Assert.Throws<IOException>(() => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), long.MaxValue)); } } /// <summary> /// Test that the capacity of a view matches the original capacity, not that specified when opening the new map, /// and that the original capacity doesn't change from opening another map with a different capacity. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Map names not supported on Unix [Fact] public void OpenedCapacityMatchesOriginal() { string name = CreateUniqueMapName(); using (MemoryMappedFile original = MemoryMappedFile.CreateNew(name, 10000)) { // Get the capacity of a view before we open any copies long capacity; using (MemoryMappedViewAccessor originalAcc = original.CreateViewAccessor()) { capacity = originalAcc.Capacity; } // Open additional maps using (MemoryMappedFile opened1 = MemoryMappedFile.CreateOrOpen(name, 1)) // smaller capacity using (MemoryMappedFile opened2 = MemoryMappedFile.CreateOrOpen(name, 20000)) // larger capacity { // Verify that the original's capacity hasn't changed using (MemoryMappedViewAccessor originalAcc = original.CreateViewAccessor()) { Assert.Equal(capacity, originalAcc.Capacity); } // Verify that each map's capacity is the same as the original even though // different values were provided foreach (MemoryMappedFile opened in new[] { opened1, opened2 }) { using (MemoryMappedViewAccessor acc = opened.CreateViewAccessor()) { Assert.Equal(capacity, acc.Capacity); } } } } } [PlatformSpecific(TestPlatforms.Windows)] // Map names not supported on Unix [Fact] public void OpenedAccessibilityLimitedToOriginal() { const int Capacity = 4096; string name = CreateUniqueMapName(); // Open the original as Read but the copy as ReadWrite using (MemoryMappedFile original = MemoryMappedFile.CreateNew(name, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedFile opened = MemoryMappedFile.CreateOrOpen(name, Capacity, MemoryMappedFileAccess.ReadWrite)) { // Even though we passed ReadWrite to CreateOrOpen, trying to open a view accessor with ReadWrite should fail Assert.Throws<IOException>(() => opened.CreateViewAccessor()); Assert.Throws<IOException>(() => opened.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.ReadWrite)); // But Read should succeed opened.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read).Dispose(); } } [PlatformSpecific(TestPlatforms.Windows)] // Map names not supported on Unix [Fact] public void OpenedAccessibilityLimitedBeyondOriginal() { const int Capacity = 4096; string name = CreateUniqueMapName(); // Open the original as ReadWrite but the copy as Read using (MemoryMappedFile original = MemoryMappedFile.CreateNew(name, Capacity, MemoryMappedFileAccess.ReadWrite)) using (MemoryMappedFile opened = MemoryMappedFile.CreateOrOpen(name, Capacity, MemoryMappedFileAccess.Read)) { // Even though we passed ReadWrite to CreateNew, trying to open a view accessor with ReadWrite should fail Assert.Throws<UnauthorizedAccessException>(() => opened.CreateViewAccessor()); Assert.Throws<UnauthorizedAccessException>(() => opened.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.ReadWrite)); // But Read should succeed opened.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read).Dispose(); } } } }
using System.Collections.Generic; using System.Diagnostics; using System.IO; using System; using System.Threading; using AppUpdate.Common; using AppUpdate.FeedReaders; using AppUpdate.Sources; using AppUpdate.Tasks; using AppUpdate.Utils; namespace AppUpdate { /// <summary> /// An UpdateManager class is a singleton class handling the update process from start to end for a consumer application /// </summary> public sealed class UpdateManager { #region Singleton Stuff /// <summary> /// Defaut ctor /// </summary> private UpdateManager() { IsWorking = false; State = UpdateProcessState.NotChecked; UpdatesToApply = new List<IUpdateTask>(); ApplicationPath = Process.GetCurrentProcess().MainModule.FileName; UpdateFeedReader = new NauXmlFeedReader(); Logger = new Logger(); Config = new NauConfigurations { TempFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()), UpdateProcessName = "NAppUpdateProcess", UpdateExecutableName = "foo.exe", // Naming it updater.exe seem to trigger the UAC, and we don't want that }; // Need to do this manually here because the BackupFolder property is protected using the static instance, which we are // in the middle of creating string backupPath = Path.Combine(Path.GetDirectoryName(ApplicationPath) ?? string.Empty, "Backup" + DateTime.Now.Ticks); backupPath = backupPath.TrimEnd(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); Config._backupFolder = Path.IsPathRooted(backupPath) ? backupPath : Path.Combine(Config.TempFolder, backupPath); } static UpdateManager() { } /// <summary> /// The singleton update manager instance to used by consumer applications /// </summary> public static UpdateManager Instance { get { return instance; } } private static readonly UpdateManager instance = new UpdateManager(); // ReSharper disable NotAccessedField.Local private static Mutex _shutdownMutex; // ReSharper restore NotAccessedField.Local #endregion /// <summary> /// State of the update process /// </summary> [Serializable] public enum UpdateProcessState { NotChecked, Checked, Prepared, AfterRestart, AppliedSuccessfully, RollbackRequired, } internal readonly string ApplicationPath; public NauConfigurations Config { get; set; } internal string BaseUrl { get; set; } internal IList<IUpdateTask> UpdatesToApply { get; private set; } public int UpdatesAvailable { get { return UpdatesToApply == null ? 0 : UpdatesToApply.Count; } } public UpdateProcessState State { get; private set; } public IUpdateSource UpdateSource { get; set; } public IUpdateFeedReader UpdateFeedReader { get; set; } public Logger Logger { get; private set; } public IEnumerable<IUpdateTask> Tasks { get { return UpdatesToApply; } } internal volatile bool ShouldStop; public bool IsWorking { get { return _isWorking; } private set { _isWorking = value; } } private volatile bool _isWorking; #region Progress reporting public event ReportProgressDelegate ReportProgress; private void TaskProgressCallback(UpdateProgressInfo currentStatus, IUpdateTask task) { if (ReportProgress == null) return; currentStatus.TaskDescription = task.Description; currentStatus.TaskId = UpdatesToApply.IndexOf(task) + 1; //This was an assumed int, which meant we never reached 100% with an odd number of tasks float taskPerc = 100F / UpdatesToApply.Count; currentStatus.Percentage = (int)Math.Round((currentStatus.Percentage * taskPerc / 100) + (currentStatus.TaskId - 1) * taskPerc); ReportProgress(currentStatus); } #endregion #region Step 1 - Check for updates /// <summary> /// Check for update synchronously, using the default update source /// </summary> public void CheckForUpdates() { CheckForUpdates(UpdateSource); } /// <summary> /// Check for updates synchronouly /// </summary> /// <param name="source">Updates source to use</param> public void CheckForUpdates(IUpdateSource source) { if (IsWorking) throw new InvalidOperationException("Another update process is already in progress"); using (WorkScope.New(isWorking => IsWorking = isWorking)) { if (UpdateFeedReader == null) throw new ArgumentException("An update feed reader is required; please set one before checking for updates"); if (source == null) throw new ArgumentException("An update source was not specified"); if (State != UpdateProcessState.NotChecked) throw new InvalidOperationException("Already checked for updates; to reset the current state call CleanUp()"); lock (UpdatesToApply) { UpdatesToApply.Clear(); var tasks = UpdateFeedReader.Read(source.GetUpdatesFeed()); foreach (var t in tasks) { if (ShouldStop) throw new UserAbortException(); if (t.UpdateConditions == null || t.UpdateConditions.IsMet(t)) // Only execute if all conditions are met UpdatesToApply.Add(t); } } State = UpdateProcessState.Checked; } } /// <summary> /// Check for updates asynchronously /// </summary> /// <param name="source">Update source to use</param> /// <param name="callback">Callback function to call when done; can be null</param> /// <param name="state">Allows the caller to preserve state; can be null</param> public IAsyncResult BeginCheckForUpdates(IUpdateSource source, AsyncCallback callback, Object state) { // Create IAsyncResult object identifying the // asynchronous operation var ar = new UpdateProcessAsyncResult(callback, state); // Use a thread pool thread to perform the operation ThreadPool.QueueUserWorkItem(o => { try { // Perform the operation; if sucessful set the result CheckForUpdates(source ?? UpdateSource); ar.SetAsCompleted(null, false); } catch (Exception e) { // If operation fails, set the exception ar.SetAsCompleted(e, false); } }, ar); return ar; // Return the IAsyncResult to the caller } /// <summary> /// Check for updates asynchronously /// </summary> /// <param name="callback">Callback function to call when done; can be null</param> /// <param name="state">Allows the caller to preserve state; can be null</param> public IAsyncResult BeginCheckForUpdates(AsyncCallback callback, Object state) { return BeginCheckForUpdates(UpdateSource, callback, state); } /// <summary> /// Block until previously-called CheckForUpdates complete /// </summary> /// <param name="asyncResult"></param> public void EndCheckForUpdates(IAsyncResult asyncResult) { // Wait for operation to complete, then return or throw exception var ar = (UpdateProcessAsyncResult)asyncResult; ar.EndInvoke(); } #endregion #region Step 2 - Prepare to execute update tasks /// <summary> /// Prepare updates synchronously /// </summary> public void PrepareUpdates() { if (IsWorking) throw new InvalidOperationException("Another update process is already in progress"); using (WorkScope.New(isWorking => IsWorking = isWorking)) { lock (UpdatesToApply) { if (State != UpdateProcessState.Checked) throw new InvalidOperationException("Invalid state when calling PrepareUpdates(): " + State); if (UpdatesToApply.Count == 0) throw new InvalidOperationException("No updates to prepare"); if (!Directory.Exists(Config.TempFolder)) { Logger.Log("Creating Temp directory {0}", Config.TempFolder); Directory.CreateDirectory(Config.TempFolder); } else { Logger.Log("Using existing Temp directory {0}", Config.TempFolder); } foreach (var task in UpdatesToApply) { if (ShouldStop) throw new UserAbortException(); var t = task; task.ProgressDelegate += status => TaskProgressCallback(status, t); try { task.Prepare(UpdateSource); } catch (Exception ex) { task.ExecutionStatus = TaskExecutionStatus.FailedToPrepare; Logger.Log(ex); throw new UpdateProcessFailedException("Failed to prepare task: " + task.Description, ex); } task.ExecutionStatus = TaskExecutionStatus.Prepared; } State = UpdateProcessState.Prepared; } } } /// <summary> /// Prepare updates asynchronously /// </summary> /// <param name="callback">Callback function to call when done; can be null</param> /// <param name="state">Allows the caller to preserve state; can be null</param> public IAsyncResult BeginPrepareUpdates(AsyncCallback callback, Object state) { // Create IAsyncResult object identifying the // asynchronous operation var ar = new UpdateProcessAsyncResult(callback, state); // Use a thread pool thread to perform the operation ThreadPool.QueueUserWorkItem(o => { try { // Perform the operation; if sucessful set the result PrepareUpdates(); ar.SetAsCompleted(null, false); } catch (Exception e) { // If operation fails, set the exception ar.SetAsCompleted(e, false); } }, ar); return ar; // Return the IAsyncResult to the caller } /// <summary> /// Block until previously-called PrepareUpdates complete /// </summary> /// <param name="asyncResult"></param> public void EndPrepareUpdates(IAsyncResult asyncResult) { // Wait for operation to complete, then return or throw exception var ar = (UpdateProcessAsyncResult)asyncResult; ar.EndInvoke(); } #endregion #region Step 3 - Apply updates /// <summary> /// Starts the updater executable and sends update data to it, and relaunch the caller application as soon as its done /// </summary> /// <returns>True if successful (unless a restart was required</returns> public void ApplyUpdates() { ApplyUpdates(true); } /// <summary> /// Starts the updater executable and sends update data to it /// </summary> /// <param name="relaunchApplication">true if relaunching the caller application is required; false otherwise</param> /// <returns>True if successful (unless a restart was required</returns> public void ApplyUpdates(bool relaunchApplication) { ApplyUpdates(relaunchApplication, false, false); } /// <summary> /// Starts the updater executable and sends update data to it /// </summary> /// <param name="relaunchApplication">true if relaunching the caller application is required; false otherwise</param> /// <param name="updaterDoLogging">true if the updater writes to a log file; false otherwise</param> /// <param name="updaterShowConsole">true if the updater shows the console window; false otherwise</param> /// <returns>True if successful (unless a restart was required</returns> public void ApplyUpdates(bool relaunchApplication, bool updaterDoLogging, bool updaterShowConsole) { if (IsWorking) throw new InvalidOperationException("Another update process is already in progress"); lock (UpdatesToApply) { using (WorkScope.New(isWorking => IsWorking = isWorking)) { bool revertToDefaultBackupPath = true; // Set current directory the the application directory // this prevents the updater from writing to e.g. c:\windows\system32 // if the process is started by autorun on windows logon. // ReSharper disable AssignNullToNotNullAttribute Environment.CurrentDirectory = Path.GetDirectoryName(ApplicationPath); // ReSharper restore AssignNullToNotNullAttribute // Make sure the current backup folder is accessible for writing from this process string backupParentPath = Path.GetDirectoryName(Config.BackupFolder) ?? string.Empty; if (Directory.Exists(backupParentPath) && PermissionsCheck.HaveWritePermissionsForFolder(backupParentPath)) { // Remove old backup folder, in case this same folder was used previously, // and it wasn't removed for some reason try { if (Directory.Exists(Config.BackupFolder)) FileSystem.DeleteDirectory(Config.BackupFolder); revertToDefaultBackupPath = false; } catch (UnauthorizedAccessException) { } // Attempt to (re-)create the backup folder try { Directory.CreateDirectory(Config.BackupFolder); if (!PermissionsCheck.HaveWritePermissionsForFolder(Config.BackupFolder)) revertToDefaultBackupPath = true; } catch (UnauthorizedAccessException) { // We're having permissions issues with this folder, so we'll attempt // using a backup in a default location revertToDefaultBackupPath = true; } } if (revertToDefaultBackupPath) { Config._backupFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Config.UpdateProcessName + "UpdateBackups" + DateTime.UtcNow.Ticks); try { Directory.CreateDirectory(Config.BackupFolder); } catch (UnauthorizedAccessException ex) { // We can't backup, so we abort throw new UpdateProcessFailedException("Could not create backup folder " + Config.BackupFolder, ex); } } bool runPrivileged = false, hasColdUpdates = false; State = UpdateProcessState.RollbackRequired; foreach (var task in UpdatesToApply) { IUpdateTask t = task; task.ProgressDelegate += status => TaskProgressCallback(status, t); try { // Execute the task task.ExecutionStatus = task.Execute(false); } catch (Exception ex) { task.ExecutionStatus = TaskExecutionStatus.Failed; // mark the failing task before rethrowing throw new UpdateProcessFailedException("Update task execution failed: " + task.Description, ex); } if (task.ExecutionStatus == TaskExecutionStatus.RequiresAppRestart || task.ExecutionStatus == TaskExecutionStatus.RequiresPrivilegedAppRestart) { // Record that we have cold updates to run, and if required to run any of them privileged runPrivileged = runPrivileged || task.ExecutionStatus == TaskExecutionStatus.RequiresPrivilegedAppRestart; hasColdUpdates = true; continue; } // We are being quite explicit here - only Successful return values are considered // to be Ok (cold updates are already handled above) if (task.ExecutionStatus != TaskExecutionStatus.Successful) throw new UpdateProcessFailedException("Update task execution failed: " + task.Description); } // If an application restart is required if (hasColdUpdates) { var dto = new NauIpc.NauDto { Configs = Instance.Config, Tasks = Instance.UpdatesToApply, AppPath = ApplicationPath, WorkingDirectory = Environment.CurrentDirectory, RelaunchApplication = relaunchApplication, LogItems = Logger.LogItems, }; NauIpc.ExtractUpdaterFromResource(Config.TempFolder, Instance.Config.UpdateExecutableName); var info = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = Path.Combine(Config.TempFolder, Instance.Config.UpdateExecutableName), Arguments = string.Format(@"""{0}"" {1} {2}", Config.UpdateProcessName, updaterShowConsole ? "-showConsole" : string.Empty, updaterDoLogging ? "-log" : string.Empty), }; if (!updaterShowConsole) { info.WindowStyle = ProcessWindowStyle.Hidden; info.CreateNoWindow = true; } // If we can't write to the destination folder, then lets try elevating priviledges. if (runPrivileged || !PermissionsCheck.HaveWritePermissionsForFolder(Environment.CurrentDirectory)) { info.Verb = "runas"; } bool createdNew; _shutdownMutex = new Mutex(true, Config.UpdateProcessName + "Mutex", out createdNew); try { NauIpc.LaunchProcessAndSendDto(dto, info, Config.UpdateProcessName); } catch (Exception ex) { throw new UpdateProcessFailedException("Could not launch cold update process", ex); } Environment.Exit(0); } State = UpdateProcessState.AppliedSuccessfully; UpdatesToApply.Clear(); } } } #endregion public void ReinstateIfRestarted() { lock (UpdatesToApply) { var dto = NauIpc.ReadDto(Config.UpdateProcessName) as NauIpc.NauDto; if (dto == null) return; Config = dto.Configs; UpdatesToApply = dto.Tasks; Logger = new Logger(dto.LogItems); State = UpdateProcessState.AfterRestart; } } /// <summary> /// Rollback executed updates in case of an update failure /// </summary> public void RollbackUpdates() { if (IsWorking) return; lock (UpdatesToApply) { foreach (var task in UpdatesToApply) { task.Rollback(); } State = UpdateProcessState.NotChecked; } } /// <summary> /// Abort update process, cancelling whatever background process currently taking place without waiting for it to complete /// </summary> public void Abort() { Abort(false); } /// <summary> /// Abort update process, cancelling whatever background process currently taking place /// </summary> /// <param name="waitForTermination">If true, blocks the calling thread until the current process terminates</param> public void Abort(bool waitForTermination) { ShouldStop = true; } /// <summary> /// Delete the temp folder as a whole and fail silently /// </summary> public void CleanUp() { Abort(true); lock (UpdatesToApply) { UpdatesToApply.Clear(); State = UpdateProcessState.NotChecked; try { if (Directory.Exists(Config.TempFolder)) FileSystem.DeleteDirectory(Config.TempFolder); } catch { } try { if (Directory.Exists(Config.BackupFolder)) FileSystem.DeleteDirectory(Config.BackupFolder); } catch { } ShouldStop = false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Windows.Data; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// This is the view model for CodeStyle options page. /// </summary> /// <remarks> /// The codestyle options page is defined in <see cref="CodeStylePage"/> /// </remarks> internal class StyleViewModel : AbstractOptionPreviewViewModel { internal override bool ShouldPersistOption(OptionKey key) { return key.Option.Feature == CSharpCodeStyleOptions.FeatureName || key.Option.Feature == CodeStyleOptions.PerLanguageCodeStyleOption || key.Option.Feature == CodeAnalysis.Editing.GenerationOptions.FeatureName; } #region "Preview Text" private static readonly string s_fieldDeclarationPreviewTrue = @" class C{ int capacity; void Method() { //[ this.capacity = 0; //] } }"; private static readonly string s_fieldDeclarationPreviewFalse = @" class C{ int capacity; void Method() { //[ capacity = 0; //] } }"; private static readonly string s_propertyDeclarationPreviewTrue = @" class C{ public int Id { get; set; } void Method() { //[ this.Id = 0; //] } }"; private static readonly string s_propertyDeclarationPreviewFalse = @" class C{ public int Id { get; set; } void Method() { //[ Id = 0; //] } }"; private static readonly string s_eventDeclarationPreviewTrue = @" using System; class C{ event EventHandler Elapsed; void Handler(object sender, EventArgs args) { //[ this.Elapsed += Handler; //] } }"; private static readonly string s_eventDeclarationPreviewFalse = @" using System; class C{ event EventHandler Elapsed; void Handler(object sender, EventArgs args) { //[ Elapsed += Handler; //] } }"; private static readonly string s_methodDeclarationPreviewTrue = @" using System; class C{ void Display() { //[ this.Display(); //] } }"; private static readonly string s_methodDeclarationPreviewFalse = @" using System; class C{ void Display() { //[ Display(); //] } }"; private static readonly string s_intrinsicPreviewDeclarationTrue = @" class Program { //[ private int _member; static void M(int argument) { int local; } //] }"; private static readonly string s_intrinsicPreviewDeclarationFalse = @" using System; class Program { //[ private Int32 _member; static void M(Int32 argument) { Int32 local; } //] }"; private static readonly string s_intrinsicPreviewMemberAccessTrue = @" class Program { //[ static void M() { var local = int.MaxValue; } //] }"; private static readonly string s_intrinsicPreviewMemberAccessFalse = @" using System; class Program { //[ static void M() { var local = Int32.MaxValue; } //] }"; private static readonly string s_varForIntrinsicsPreviewFalse = @" using System; class C{ void Method() { //[ int x = 5; // built-in types //] } }"; private static readonly string s_varForIntrinsicsPreviewTrue = @" using System; class C{ void Method() { //[ var x = 5; // built-in types //] } }"; private static readonly string s_varWhereApparentPreviewFalse = @" using System; class C{ void Method() { //[ C cobj = new C(); // type is apparent from assignment expression //] } }"; private static readonly string s_varWhereApparentPreviewTrue = @" using System; class C{ void Method() { //[ var cobj = new C(); // type is apparent from assignment expression //] } }"; private static readonly string s_varWherePossiblePreviewFalse = @" using System; class C{ void Init() { //[ Action f = this.Init(); // everywhere else. //] } }"; private static readonly string s_varWherePossiblePreviewTrue = @" using System; class C{ void Init() { //[ var f = this.Init(); // everywhere else. //] } }"; #endregion internal StyleViewModel(OptionSet optionSet, IServiceProvider serviceProvider) : base(optionSet, serviceProvider, LanguageNames.CSharp) { var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(CodeStyleItems); collectionView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AbstractCodeStyleOptionViewModel.GroupName))); var qualifyGroupTitle = CSharpVSResources.this_preferences_colon; var predefinedTypesGroupTitle = CSharpVSResources.predefined_type_preferences_colon; var varGroupTitle = CSharpVSResources.var_preferences_colon; var qualifyMemberAccessPreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Prefer_this, isChecked: true), new CodeStylePreference(CSharpVSResources.Do_not_prefer_this, isChecked: false), }; var predefinedTypesPreferences = new List<CodeStylePreference> { new CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked: true), new CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked: false), }; var typeStylePreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Prefer_var, isChecked: true), new CodeStylePreference(CSharpVSResources.Prefer_explicit_type, isChecked: false), }; CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionSet, predefinedTypesGroupTitle, predefinedTypesPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionSet, predefinedTypesGroupTitle, predefinedTypesPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, CSharpVSResources.For_built_in_types, s_varForIntrinsicsPreviewTrue, s_varForIntrinsicsPreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, CSharpVSResources.When_variable_type_is_apparent, s_varWhereApparentPreviewTrue, s_varWhereApparentPreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, CSharpVSResources.Elsewhere, s_varWherePossiblePreviewTrue, s_varWherePossiblePreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Construction; using Microsoft.Build.Framework; using Microsoft.Build.Shared; namespace Microsoft.Build.BackEnd.SdkResolution { internal class SdkResolverLoader { #if FEATURE_ASSEMBLYLOADCONTEXT private readonly CoreClrAssemblyLoader _loader = new CoreClrAssemblyLoader(); #endif private readonly string IncludeDefaultResolver = Environment.GetEnvironmentVariable("MSBUILDINCLUDEDEFAULTSDKRESOLVER"); // Test hook for loading SDK Resolvers from additional folders. Support runtime-specific test hook environment variables, // as an SDK resolver built for .NET Framework probably won't work on .NET Core, and vice versa. private readonly string AdditionalResolversFolder = Environment.GetEnvironmentVariable( #if NETFRAMEWORK "MSBUILDADDITIONALSDKRESOLVERSFOLDER_NETFRAMEWORK" #elif NET "MSBUILDADDITIONALSDKRESOLVERSFOLDER_NET" #endif ) ?? Environment.GetEnvironmentVariable("MSBUILDADDITIONALSDKRESOLVERSFOLDER"); internal virtual IList<SdkResolver> LoadResolvers(LoggingContext loggingContext, ElementLocation location) { var resolvers = !String.Equals(IncludeDefaultResolver, "false", StringComparison.OrdinalIgnoreCase) ? new List<SdkResolver> {new DefaultSdkResolver()} : new List<SdkResolver>(); var potentialResolvers = FindPotentialSdkResolvers( Path.Combine(BuildEnvironmentHelper.Instance.MSBuildToolsDirectory32, "SdkResolvers"), location); if (potentialResolvers.Count == 0) { return resolvers; } foreach (var potentialResolver in potentialResolvers) { LoadResolvers(potentialResolver, loggingContext, location, resolvers); } return resolvers.OrderBy(t => t.Priority).ToList(); } /// <summary> /// Find all files that are to be considered SDK Resolvers. Pattern will match /// Root\SdkResolver\(ResolverName)\(ResolverName).dll. /// </summary> /// <param name="rootFolder"></param> /// <param name="location"></param> /// <returns></returns> internal virtual IList<string> FindPotentialSdkResolvers(string rootFolder, ElementLocation location) { var assembliesList = new List<string>(); if ((string.IsNullOrEmpty(rootFolder) || !FileUtilities.DirectoryExistsNoThrow(rootFolder)) && AdditionalResolversFolder == null) { return assembliesList; } DirectoryInfo[] subfolders = GetSubfolders(rootFolder, AdditionalResolversFolder); foreach (var subfolder in subfolders) { var assembly = Path.Combine(subfolder.FullName, $"{subfolder.Name}.dll"); var manifest = Path.Combine(subfolder.FullName, $"{subfolder.Name}.xml"); var assemblyAdded = TryAddAssembly(assembly, assembliesList); if (!assemblyAdded) { assemblyAdded = TryAddAssemblyFromManifest(manifest, subfolder.FullName, assembliesList, location); } if (!assemblyAdded) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), "SdkResolverNoDllOrManifest", subfolder.FullName); } } return assembliesList; } private DirectoryInfo[] GetSubfolders(string rootFolder, string additionalResolversFolder) { DirectoryInfo[] subfolders = null; if (!string.IsNullOrEmpty(rootFolder) && FileUtilities.DirectoryExistsNoThrow(rootFolder)) { subfolders = new DirectoryInfo(rootFolder).GetDirectories(); } if (additionalResolversFolder != null) { var resolversDirInfo = new DirectoryInfo(additionalResolversFolder); if (resolversDirInfo.Exists) { HashSet<DirectoryInfo> overrideFolders = resolversDirInfo.GetDirectories().ToHashSet(new DirInfoNameComparer()); if (subfolders != null) { overrideFolders.UnionWith(subfolders); } return overrideFolders.ToArray(); } } return subfolders; } private class DirInfoNameComparer : IEqualityComparer<DirectoryInfo> { public bool Equals(DirectoryInfo first, DirectoryInfo second) { return string.Equals(first.Name, second.Name, StringComparison.OrdinalIgnoreCase); } public int GetHashCode(DirectoryInfo value) { return value.Name.GetHashCode(); } } private bool TryAddAssemblyFromManifest(string pathToManifest, string manifestFolder, List<string> assembliesList, ElementLocation location) { if (!string.IsNullOrEmpty(pathToManifest) && !FileUtilities.FileExistsNoThrow(pathToManifest)) return false; string path = null; try { // <SdkResolver> // <Path>...</Path> // </SdkResolver> var manifest = SdkResolverManifest.Load(pathToManifest); if (manifest == null || string.IsNullOrEmpty(manifest.Path)) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), "SdkResolverDllInManifestMissing", pathToManifest, string.Empty); } path = FileUtilities.FixFilePath(manifest.Path); } catch (XmlException e) { // Note: Not logging e.ToString() as most of the information is not useful, the Message will contain what is wrong with the XML file. ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), e, "SdkResolverManifestInvalid", pathToManifest, e.Message); } if (!Path.IsPathRooted(path)) { path = Path.Combine(manifestFolder, path); path = Path.GetFullPath(path); } if (!TryAddAssembly(path, assembliesList)) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), "SdkResolverDllInManifestMissing", pathToManifest, path); } return true; } private bool TryAddAssembly(string assemblyPath, List<string> assembliesList) { if (string.IsNullOrEmpty(assemblyPath) || !FileUtilities.FileExistsNoThrow(assemblyPath)) return false; assembliesList.Add(assemblyPath); return true; } protected virtual IEnumerable<Type> GetResolverTypes(Assembly assembly) { return assembly.ExportedTypes .Select(type => new {type, info = type.GetTypeInfo()}) .Where(t => t.info.IsClass && t.info.IsPublic && !t.info.IsAbstract && typeof(SdkResolver).IsAssignableFrom(t.type)) .Select(t => t.type); } protected virtual Assembly LoadResolverAssembly(string resolverPath, LoggingContext loggingContext, ElementLocation location) { #if !FEATURE_ASSEMBLYLOADCONTEXT return Assembly.LoadFrom(resolverPath); #else return _loader.LoadFromPath(resolverPath); #endif } protected virtual void LoadResolvers(string resolverPath, LoggingContext loggingContext, ElementLocation location, List<SdkResolver> resolvers) { Assembly assembly; try { assembly = LoadResolverAssembly(resolverPath, loggingContext, location); } catch (Exception e) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), e, "CouldNotLoadSdkResolverAssembly", resolverPath, e.Message); return; } foreach (Type type in GetResolverTypes(assembly)) { try { resolvers.Add((SdkResolver)Activator.CreateInstance(type)); } catch (TargetInvocationException e) { // .NET wraps the original exception inside of a TargetInvocationException which masks the original message // Attempt to get the inner exception in this case, but fall back to the top exception message string message = e.InnerException?.Message ?? e.Message; ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), e.InnerException ?? e, "CouldNotLoadSdkResolver", type.Name, message); } catch (Exception e) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), e, "CouldNotLoadSdkResolver", type.Name, e.Message); } } } } }
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using System; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using UIKit; namespace ArcGISRuntime.Samples.CutGeometry { [Register("CutGeometry")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Cut geometry", category: "Geometry", description: "Cut a geometry along a polyline.", instructions: "Tap the \"Cut\" button to cut the polygon with the polyline and see the resulting parts (shaded in different colors).", tags: new[] { "cut", "geometry", "split" })] public class CutGeometry : UIViewController { // Hold references to UI controls. private MapView _myMapView; private UIBarButtonItem _cutGeometryButton; // Graphics overlay to display the graphics. private GraphicsOverlay _graphicsOverlay; // Graphic that represents the polygon of Lake Superior. private Graphic _lakeSuperiorPolygonGraphic; // Graphic that represents the Canada and USA border (polyline) of Lake Superior. private Graphic _countryBorderPolylineGraphic; public CutGeometry() { Title = "Cut geometry"; } private void Initialize() { // Create and show a map with a topographic basemap. _myMapView.Map = new Map(BasemapStyle.ArcGISTopographic); // Create a graphics overlay to hold the various graphics. _graphicsOverlay = new GraphicsOverlay(); // Add the created graphics overlay to the MapView. _myMapView.GraphicsOverlays.Add(_graphicsOverlay); // Create a simple line symbol for the outline of the Lake Superior graphic. SimpleLineSymbol lakeSuperiorSimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 4); // Create the color that will be used for the fill the Lake Superior graphic. It will be a semi-transparent, blue color. System.Drawing.Color lakeSuperiorFillColor = System.Drawing.Color.FromArgb(34, 0, 0, 255); // Create the simple fill symbol for the Lake Superior graphic - comprised of a fill style, fill color and outline. SimpleFillSymbol lakeSuperiorSimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, lakeSuperiorFillColor, lakeSuperiorSimpleLineSymbol); // Create the graphic for Lake Superior - comprised of a polygon shape and fill symbol. _lakeSuperiorPolygonGraphic = new Graphic(CreateLakeSuperiorPolygon(), lakeSuperiorSimpleFillSymbol); // Add the Lake Superior graphic to the graphics overlay collection. _graphicsOverlay.Graphics.Add(_lakeSuperiorPolygonGraphic); // Create a simple line symbol for the Canada and USA border (polyline) of Lake Superior. SimpleLineSymbol countryBorderSimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dot, System.Drawing.Color.Red, 5); // Create the graphic for Canada and USA border (polyline) of Lake Superior - comprised of a polyline shape and line symbol. _countryBorderPolylineGraphic = new Graphic(CreateBorder(), countryBorderSimpleLineSymbol); // Add the Canada and USA border graphic to the graphics overlay collection. _graphicsOverlay.Graphics.Add(_countryBorderPolylineGraphic); // Set the initial visual extent of the map view to that of Lake Superior. _myMapView.SetViewpointGeometryAsync(_lakeSuperiorPolygonGraphic.Geometry); } private void CutButton_TouchUpInside(object sender, EventArgs e) { try { // Cut the polygon geometry with the polyline, expect two geometries. Geometry[] cutGeometries = GeometryEngine.Cut(_lakeSuperiorPolygonGraphic.Geometry, (Polyline) _countryBorderPolylineGraphic.Geometry); // Create a simple line symbol for the outline of the Canada side of Lake Superior. SimpleLineSymbol canadaSideSimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Null, System.Drawing.Color.Blue, 0); // Create the simple fill symbol for the Canada side of Lake Superior graphic - comprised of a fill style, fill color and outline. SimpleFillSymbol canadaSideSimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, System.Drawing.Color.Green, canadaSideSimpleLineSymbol); // Create the graphic for the Canada side of Lake Superior - comprised of a polygon shape and fill symbol. Graphic canadaSideGraphic = new Graphic(cutGeometries[0], canadaSideSimpleFillSymbol); // Add the Canada side of the Lake Superior graphic to the graphics overlay collection. _graphicsOverlay.Graphics.Add(canadaSideGraphic); // Create a simple line symbol for the outline of the USA side of Lake Superior. SimpleLineSymbol usaSideSimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Null, System.Drawing.Color.Blue, 0); // Create the simple fill symbol for the USA side of Lake Superior graphic - comprised of a fill style, fill color and outline. SimpleFillSymbol usaSideSimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, System.Drawing.Color.Yellow, usaSideSimpleLineSymbol); // Create the graphic for the USA side of Lake Superior - comprised of a polygon shape and fill symbol. Graphic usaSideGraphic = new Graphic(cutGeometries[1], usaSideSimpleFillSymbol); // Add the USA side of the Lake Superior graphic to the graphics overlay collection. _graphicsOverlay.Graphics.Add(usaSideGraphic); // Disable the button after has been used. ((UIBarButtonItem) sender).Enabled = false; } catch (Exception ex) { // Display an error message if there is a problem generating cut operation. UIAlertController alertController = UIAlertController.Create("Geometry Engine Failed!", ex.Message, UIAlertControllerStyle.Alert); alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alertController, true, null); } } private Polyline CreateBorder() { // Create a point collection that represents the Canada and USA border (polyline) of Lake Superior. Use the same spatial reference as the underlying base map. PointCollection borderCountryPointCollection = new PointCollection(SpatialReferences.WebMercator) { // Add all of the border map points to the point collection. new MapPoint(-9981328.687124, 6111053.281447), new MapPoint(-9946518.044066, 6102350.620682), new MapPoint(-9872545.427566, 6152390.920079), new MapPoint(-9838822.617103, 6157830.083057), new MapPoint(-9446115.050097, 5927209.572793), new MapPoint(-9430885.393759, 5876081.440801), new MapPoint(-9415655.737420, 5860851.784463) }; // Return a polyline geometry from the point collection. return new Polyline(borderCountryPointCollection); } private Polygon CreateLakeSuperiorPolygon() { // Create a point collection that represents Lake Superior (polygon). Use the same spatial reference as the underlying base map. PointCollection lakeSuperiorPointCollection = new PointCollection(SpatialReferences.WebMercator) { // Add all of the lake Superior boundary map points to the point collection. new MapPoint(-10254374.668616, 5908345.076380), new MapPoint(-10178382.525314, 5971402.386779), new MapPoint(-10118558.923141, 6034459.697178), new MapPoint(-9993252.729399, 6093474.872295), new MapPoint(-9882498.222673, 6209888.368416), new MapPoint(-9821057.766387, 6274562.532928), new MapPoint(-9690092.583250, 6241417.023616), new MapPoint(-9605207.742329, 6206654.660191), new MapPoint(-9564786.389509, 6108834.986367), new MapPoint(-9449989.747500, 6095091.726408), new MapPoint(-9462116.153346, 6044160.821855), new MapPoint(-9417652.665244, 5985145.646738), new MapPoint(-9438671.768711, 5946341.148031), new MapPoint(-9398250.415891, 5922088.336339), new MapPoint(-9419269.519357, 5855797.317714), new MapPoint(-9467775.142741, 5858222.598884), new MapPoint(-9462924.580403, 5902686.086985), new MapPoint(-9598740.325877, 5884092.264688), new MapPoint(-9643203.813979, 5845287.765981), new MapPoint(-9739406.633691, 5879241.702350), new MapPoint(-9783061.694736, 5922896.763395), new MapPoint(-9844502.151022, 5936640.023354), new MapPoint(-9773360.570059, 6019099.583107), new MapPoint(-9883306.649729, 5968977.105610), new MapPoint(-9957681.938918, 5912387.211662), new MapPoint(-10055501.612742, 5871965.858842), new MapPoint(-10116942.069028, 5884092.264688), new MapPoint(-10111283.079633, 5933406.315128), new MapPoint(-10214761.742852, 5888134.399970), new MapPoint(-10254374.668616, 5901877.659929) }; // Return a polyline geometry from the point collection. return new Polygon(lakeSuperiorPointCollection); } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor}; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; _cutGeometryButton = new UIBarButtonItem(); _cutGeometryButton.Title = "Cut geometry"; UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _cutGeometryButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace) }; // Add the views. View.AddSubviews(_myMapView, toolbar); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _cutGeometryButton.Clicked += CutButton_TouchUpInside; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _cutGeometryButton.Clicked -= CutButton_TouchUpInside; } } }
using System; using System.Collections.Generic; namespace LibGit2Sharp { /// <summary> /// A Repository is the primary interface into a git repository /// </summary> public interface IRepository : IDisposable { /// <summary> /// Shortcut to return the branch pointed to by HEAD /// </summary> Branch Head { get; } /// <summary> /// Provides access to the configuration settings for this repository. /// </summary> Configuration Config { get; } /// <summary> /// Gets the index. /// </summary> Index Index { get; } /// <summary> /// Lookup and enumerate references in the repository. /// </summary> ReferenceCollection Refs { get; } /// <summary> /// Lookup and enumerate commits in the repository. /// Iterating this collection directly starts walking from the HEAD. /// </summary> IQueryableCommitLog Commits { get; } /// <summary> /// Lookup and enumerate branches in the repository. /// </summary> BranchCollection Branches { get; } /// <summary> /// Lookup and enumerate tags in the repository. /// </summary> TagCollection Tags { get; } /// <summary> /// Provides high level information about this repository. /// </summary> RepositoryInformation Info { get; } /// <summary> /// Provides access to diffing functionalities to show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk. /// </summary> Diff Diff { get; } /// <summary> /// Gets the database. /// </summary> ObjectDatabase ObjectDatabase { get; } /// <summary> /// Lookup notes in the repository. /// </summary> NoteCollection Notes { get; } /// <summary> /// Submodules in the repository. /// </summary> SubmoduleCollection Submodules { get; } /// <summary> /// Checkout the specified tree. /// </summary> /// <param name="tree">The <see cref="Tree"/> to checkout.</param> /// <param name="paths">The paths to checkout.</param> /// <param name="opts">Collection of parameters controlling checkout behavior.</param> void Checkout(Tree tree, IEnumerable<string> paths, CheckoutOptions opts); /// <summary> /// Updates specifed paths in the index and working directory with the versions from the specified branch, reference, or SHA. /// <para> /// This method does not switch branches or update the current repository HEAD. /// </para> /// </summary> /// <param name = "committishOrBranchSpec">A revparse spec for the commit or branch to checkout paths from.</param> /// <param name="paths">The paths to checkout.</param> /// <param name="checkoutOptions">Collection of parameters controlling checkout behavior.</param> void CheckoutPaths(string committishOrBranchSpec, IEnumerable<string> paths, CheckoutOptions checkoutOptions); /// <summary> /// Try to lookup an object by its <see cref="ObjectId"/>. If no matching object is found, null will be returned. /// </summary> /// <param name="id">The id to lookup.</param> /// <returns>The <see cref="GitObject"/> or null if it was not found.</returns> GitObject Lookup(ObjectId id); /// <summary> /// Try to lookup an object by its sha or a reference canonical name. If no matching object is found, null will be returned. /// </summary> /// <param name="objectish">A revparse spec for the object to lookup.</param> /// <returns>The <see cref="GitObject"/> or null if it was not found.</returns> GitObject Lookup(string objectish); /// <summary> /// Try to lookup an object by its <see cref="ObjectId"/> and <see cref="ObjectType"/>. If no matching object is found, null will be returned. /// </summary> /// <param name="id">The id to lookup.</param> /// <param name="type">The kind of GitObject being looked up</param> /// <returns>The <see cref="GitObject"/> or null if it was not found.</returns> GitObject Lookup(ObjectId id, ObjectType type); /// <summary> /// Try to lookup an object by its sha or a reference canonical name and <see cref="ObjectType"/>. If no matching object is found, null will be returned. /// </summary> /// <param name="objectish">A revparse spec for the object to lookup.</param> /// <param name="type">The kind of <see cref="GitObject"/> being looked up</param> /// <returns>The <see cref="GitObject"/> or null if it was not found.</returns> GitObject Lookup(string objectish, ObjectType type); /// <summary> /// Stores the content of the <see cref="Repository.Index"/> as a new <see cref="LibGit2Sharp.Commit"/> into the repository. /// The tip of the <see cref="Repository.Head"/> will be used as the parent of this new Commit. /// Once the commit is created, the <see cref="Repository.Head"/> will move forward to point at it. /// </summary> /// <param name="message">The description of why a change was made to the repository.</param> /// <param name="author">The <see cref="Signature"/> of who made the change.</param> /// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param> /// <param name="options">The <see cref="CommitOptions"/> that specify the commit behavior.</param> /// <returns>The generated <see cref="LibGit2Sharp.Commit"/>.</returns> Commit Commit(string message, Signature author, Signature committer, CommitOptions options); /// <summary> /// Sets the current <see cref="Head"/> to the specified commit and optionally resets the <see cref="Index"/> and /// the content of the working tree to match. /// </summary> /// <param name="resetMode">Flavor of reset operation to perform.</param> /// <param name="commit">The target commit object.</param> void Reset(ResetMode resetMode, Commit commit); /// <summary> /// Sets <see cref="Head"/> to the specified commit and optionally resets the <see cref="Index"/> and /// the content of the working tree to match. /// </summary> /// <param name="resetMode">Flavor of reset operation to perform.</param> /// <param name="commit">The target commit object.</param> /// <param name="options">Collection of parameters controlling checkout behavior.</param> void Reset(ResetMode resetMode, Commit commit, CheckoutOptions options); /// <summary> /// Clean the working tree by removing files that are not under version control. /// </summary> void RemoveUntrackedFiles(); /// <summary> /// Revert the specified commit. /// </summary> /// <param name="commit">The <see cref="Commit"/> to revert.</param> /// <param name="reverter">The <see cref="Signature"/> of who is performing the reverte.</param> /// <param name="options"><see cref="RevertOptions"/> controlling revert behavior.</param> /// <returns>The result of the revert.</returns> RevertResult Revert(Commit commit, Signature reverter, RevertOptions options); /// <summary> /// Merge changes from commit into the branch pointed at by HEAD.. /// </summary> /// <param name="commit">The commit to merge into the branch pointed at by HEAD.</param> /// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param> /// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> MergeResult Merge(Commit commit, Signature merger, MergeOptions options); /// <summary> /// Merges changes from branch into the branch pointed at by HEAD.. /// </summary> /// <param name="branch">The branch to merge into the branch pointed at by HEAD.</param> /// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param> /// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> MergeResult Merge(Branch branch, Signature merger, MergeOptions options); /// <summary> /// Merges changes from the commit into the branch pointed at by HEAD. /// </summary> /// <param name="committish">The commit to merge into branch pointed at by HEAD.</param> /// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param> /// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> MergeResult Merge(string committish, Signature merger, MergeOptions options); /// <summary> /// Access to Rebase functionality. /// </summary> Rebase Rebase { get; } /// <summary> /// Merge the reference that was recently fetched. This will merge /// the branch on the fetched remote that corresponded to the /// current local branch when we did the fetch. This is the /// second step in performing a pull operation (after having /// performed said fetch). /// </summary> /// <param name="merger">The <see cref="Signature"/> of who is performing the merge.</param> /// <param name="options">Specifies optional parameters controlling merge behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> MergeResult MergeFetchedRefs(Signature merger, MergeOptions options); /// <summary> /// Cherry picks changes from the commit into the branch pointed at by HEAD. /// </summary> /// <param name="commit">The commit to cherry pick into branch pointed at by HEAD.</param> /// <param name="committer">The <see cref="Signature"/> of who is performing the cherry pick.</param> /// <param name="options">Specifies optional parameters controlling cherry pick behavior; if null, the defaults are used.</param> /// <returns>The <see cref="MergeResult"/> of the merge.</returns> CherryPickResult CherryPick(Commit commit, Signature committer, CherryPickOptions options); /// <summary> /// Manipulate the currently ignored files. /// </summary> Ignore Ignore { get; } /// <summary> /// Provides access to network functionality for a repository. /// </summary> Network Network { get; } ///<summary> /// Lookup and enumerate stashes in the repository. ///</summary> StashCollection Stashes { get; } /// <summary> /// Find where each line of a file originated. /// </summary> /// <param name="path">Path of the file to blame.</param> /// <param name="options">Specifies optional parameters; if null, the defaults are used.</param> /// <returns>The blame for the file.</returns> BlameHunkCollection Blame(string path, BlameOptions options); /// <summary> /// Retrieves the state of a file in the working directory, comparing it against the staging area and the latest commit. /// </summary> /// <param name="filePath">The relative path within the working directory to the file.</param> /// <returns>A <see cref="FileStatus"/> representing the state of the <paramref name="filePath"/> parameter.</returns> FileStatus RetrieveStatus(string filePath); /// <summary> /// Retrieves the state of all files in the working directory, comparing them against the staging area and the latest commit. /// </summary> /// <param name="options">If set, the options that control the status investigation.</param> /// <returns>A <see cref="RepositoryStatus"/> holding the state of all the files.</returns> RepositoryStatus RetrieveStatus(StatusOptions options); /// <summary> /// Finds the most recent annotated tag that is reachable from a commit. /// <para> /// If the tag points to the commit, then only the tag is shown. Otherwise, /// it suffixes the tag name with the number of additional commits on top /// of the tagged object and the abbreviated object name of the most recent commit. /// </para> /// <para> /// Optionally, the <paramref name="options"/> parameter allow to tweak the /// search strategy (considering lightweith tags, or even branches as reference points) /// and the formatting of the returned identifier. /// </para> /// </summary> /// <param name="commit">The commit to be described.</param> /// <param name="options">Determines how the commit will be described.</param> /// <returns>A descriptive identifier for the commit based on the nearest annotated tag.</returns> string Describe(Commit commit, DescribeOptions options); /// <summary> /// Parse an extended SHA-1 expression and retrieve the object and the reference /// mentioned in the revision (if any). /// </summary> /// <param name="revision">An extended SHA-1 expression for the object to look up</param> /// <param name="reference">The reference mentioned in the revision (if any)</param> /// <param name="obj">The object which the revision resolves to</param> void RevParse(string revision, out Reference reference, out GitObject obj); } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Data; using Xunit; namespace Avalonia.Base.UnitTests { public class AvaloniaObjectTests_SetValue { [Fact] public void ClearValue_Clears_Value() { Class1 target = new Class1(); target.SetValue(Class1.FooProperty, "newvalue"); target.ClearValue(Class1.FooProperty); Assert.Equal("foodefault", target.GetValue(Class1.FooProperty)); } [Fact] public void SetValue_Sets_Value() { Class1 target = new Class1(); target.SetValue(Class1.FooProperty, "newvalue"); Assert.Equal("newvalue", target.GetValue(Class1.FooProperty)); } [Fact] public void SetValue_Sets_Attached_Value() { Class2 target = new Class2(); target.SetValue(AttachedOwner.AttachedProperty, "newvalue"); Assert.Equal("newvalue", target.GetValue(AttachedOwner.AttachedProperty)); } [Fact] public void SetValue_Raises_PropertyChanged() { Class1 target = new Class1(); bool raised = false; target.PropertyChanged += (s, e) => { raised = s == target && e.Property == Class1.FooProperty && (string)e.OldValue == "foodefault" && (string)e.NewValue == "newvalue"; }; target.SetValue(Class1.FooProperty, "newvalue"); Assert.True(raised); } [Fact] public void SetValue_Doesnt_Raise_PropertyChanged_If_Value_Not_Changed() { Class1 target = new Class1(); bool raised = false; target.SetValue(Class1.FooProperty, "bar"); target.PropertyChanged += (s, e) => { raised = true; }; target.SetValue(Class1.FooProperty, "bar"); Assert.False(raised); } [Fact] public void SetValue_Doesnt_Raise_PropertyChanged_If_Value_Not_Changed_From_Default() { Class1 target = new Class1(); bool raised = false; target.PropertyChanged += (s, e) => { raised = true; }; target.SetValue(Class1.FooProperty, "foodefault"); Assert.False(raised); } [Fact] public void SetValue_Allows_Setting_Unregistered_Property() { Class1 target = new Class1(); Assert.False(AvaloniaPropertyRegistry.Instance.IsRegistered(target, Class2.BarProperty)); target.SetValue(Class2.BarProperty, "bar"); Assert.Equal("bar", target.GetValue(Class2.BarProperty)); } [Fact] public void SetValue_Allows_Setting_Unregistered_Attached_Property() { Class1 target = new Class1(); Assert.False(AvaloniaPropertyRegistry.Instance.IsRegistered(target, AttachedOwner.AttachedProperty)); target.SetValue(AttachedOwner.AttachedProperty, "bar"); Assert.Equal("bar", target.GetValue(AttachedOwner.AttachedProperty)); } [Fact] public void SetValue_Throws_Exception_For_Invalid_Value_Type() { Class1 target = new Class1(); Assert.Throws<ArgumentException>(() => { target.SetValue(Class1.FooProperty, 123); }); } [Fact] public void SetValue_Of_Integer_On_Double_Property_Works() { Class2 target = new Class2(); target.SetValue((AvaloniaProperty)Class2.FlobProperty, 4); var value = target.GetValue(Class2.FlobProperty); Assert.IsType<double>(value); Assert.Equal(4, value); } [Fact] public void SetValue_Respects_Implicit_Conversions() { Class2 target = new Class2(); target.SetValue((AvaloniaProperty)Class2.FlobProperty, new ImplictDouble(4)); var value = target.GetValue(Class2.FlobProperty); Assert.IsType<double>(value); Assert.Equal(4, value); } [Fact] public void SetValue_Can_Convert_To_Nullable() { Class2 target = new Class2(); target.SetValue((AvaloniaProperty)Class2.FredProperty, 4.0); var value = target.GetValue(Class2.FredProperty); Assert.IsType<double>(value); Assert.Equal(4, value); } [Fact] public void SetValue_Respects_Priority() { Class1 target = new Class1(); target.SetValue(Class1.FooProperty, "one", BindingPriority.TemplatedParent); Assert.Equal("one", target.GetValue(Class1.FooProperty)); target.SetValue(Class1.FooProperty, "two", BindingPriority.Style); Assert.Equal("one", target.GetValue(Class1.FooProperty)); target.SetValue(Class1.FooProperty, "three", BindingPriority.StyleTrigger); Assert.Equal("three", target.GetValue(Class1.FooProperty)); } [Fact] public void Setting_UnsetValue_Reverts_To_Default_Value() { Class1 target = new Class1(); target.SetValue(Class1.FooProperty, "newvalue"); target.SetValue(Class1.FooProperty, AvaloniaProperty.UnsetValue); Assert.Equal("foodefault", target.GetValue(Class1.FooProperty)); } private class Class1 : AvaloniaObject { public static readonly StyledProperty<string> FooProperty = AvaloniaProperty.Register<Class1, string>("Foo", "foodefault"); } private class Class2 : Class1 { public static readonly StyledProperty<string> BarProperty = AvaloniaProperty.Register<Class2, string>("Bar", "bardefault"); public static readonly StyledProperty<double> FlobProperty = AvaloniaProperty.Register<Class2, double>("Flob"); public static readonly StyledProperty<double?> FredProperty = AvaloniaProperty.Register<Class2, double?>("Fred"); public Class1 Parent { get { return (Class1)InheritanceParent; } set { InheritanceParent = value; } } } private class AttachedOwner { public static readonly AttachedProperty<string> AttachedProperty = AvaloniaProperty.RegisterAttached<AttachedOwner, Class2, string>("Attached"); } private class ImplictDouble { public ImplictDouble(double value) { Value = value; } public double Value { get; } public static implicit operator double (ImplictDouble v) { return v.Value; } } } }
using NUnit.Framework; namespace UnityEngine { [TestFixture] [Category("Extensions")] public class ColorExtensions_Tests { #region Test Case Sources #pragma warning disable 0414 static object[] HexStringCasesNoAlpha = { new object[] {1,0,0,1,false,"#FF0000"}, new object[] {1,1,1,1,false,"#FFFFFF"}, new object[] {0,0,0,1,false,"#000000"}, new object[] {100,100,100,1,false,"#FFFFFF"}, new object[] {-100,-100,-100,1,false,"#000000"}, }; static object[] HexStringCasesAlphas = { new object[] {1,0,0,1,true,"#FF0000FF"}, new object[] {1,1,1,1,true,"#FFFFFFFF"}, new object[] {0,0,0,0,true,"#00000000"}, new object[] {100,100,100,100,true,"#FFFFFFFF"}, new object[] {-100,-100,-100,-100,true, "#00000000" } }; static object[] MakeColorHexStringCases = { new object[] {"#FF0000FF", Color.red}, new object[] {"#FFFFFFFF", Color.white}, new object[] {"#00000000", new Color(0,0,0,0)}, new object[] {"#00000080", new Color(0,0,0,128f/255f)} }; static object[] RGBStringCases = { new object[] {"1,0,0", Color.red}, new object[] {"1,1,1", Color.white}, new object[] {"0,0,0", Color.black}, new object[] {"100,100,100", Color.white}, new object[] {"-100,-100,-100", Color.black}, }; static object[] RGBAStringCases = { new object[] {"1,0,0,1", Color.red}, new object[] {"1,1,1,1", Color.white}, new object[] {"0,0,0,1", Color.black}, new object[] {"0,0,0,0.5", new Color(0,0,0,0.5f)}, new object[] {"100,100,100,100", Color.white}, new object[] {"-100,-100,-100,-100", new Color(0,0,0,0)}, new object[] {"0.5,0.5,0.5,0.5", new Color(0.5f,0.5f,0.5f,0.5f)} }; static object[] BadRGBStrings = { new object[] { "a,b,c"}, new object[] { "a,b,c,d"}, new object[] { ",,,"}, new object[] { ",,,,"}, new object[] { ","}, new object[] { ",,,abcd"}, new object[] { "abcd,,,"}, }; static object[] ClampCases = { new object[] { Color.white, Color.white}, new object[] { new Color(0,0,0,0), new Color(0,0,0,0)}, new object[] { new Color(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue), Color.white}, new object[] { new Color(float.MinValue, float.MinValue, float.MinValue, float.MinValue), new Color(0,0,0,0)}, new object[] { new Color(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity), Color.white}, new object[] { new Color(float.NaN, float.NaN, float.NegativeInfinity, float.NegativeInfinity), new Color(0,0,0,0)}, }; static object[] MakeHSBColorCases = { new object[] { Color.black, Vector3.zero}, new object[] { Color.white, new Vector3(0, 0, 1)}, new object[] { Color.red, new Vector3(0, 1, 1)}, new object[] { new Color(0, 1, 1), new Vector3(0, 1, 1)}, new object[] { new Color(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue), new Vector3(0, 0, 1)}, new object[] { new Color(float.MinValue, float.MinValue, float.MinValue, float.MinValue), Vector3.zero}, }; #pragma warning restore #endregion #region HexString methods [Test, TestCaseSource("HexStringCasesNoAlpha"), TestCaseSource("HexStringCasesAlphas")] public void HexString_Test_Color32_IncludeAlpha(float r, float g, float b, float a, bool includeAlpha, string expected) { Color32 color = new Color(r, g, b, a); string actual = ColorExtensions.HexString(color, includeAlpha); Assert.AreEqual(expected, actual); } [Test, TestCaseSource("HexStringCasesNoAlpha"), TestCaseSource("HexStringCasesAlphas")] public void HexString_Test_Color_IncludeAlpha(float r, float g, float b, float a, bool includeAlpha, string expected) { Color color = new Color(r, g, b, a); string actual = ColorExtensions.HexString(color, includeAlpha); Assert.AreEqual(expected, actual); } [Test, TestCaseSource("HexStringCasesNoAlpha")] public void HexString_Test_Color_NoAlpha(float r, float g, float b, float a, bool includeAlpha, string expected) { Color color = new Color(r, g, b, a); string actual = ColorExtensions.HexString(color); Assert.AreEqual(expected, actual); } [Test, TestCaseSource("MakeColorHexStringCases")] public void MakeColor_Test_HexString_Normal_Usage(string hexString, Color expected) { Color actual = ColorExtensions.MakeColor(hexString); Assert.AreEqual(expected, actual); } #endregion #region MakeColor(string aStr) [Test] public void MakeColor_Test_Null_Param() { Color expected = Color.magenta; Color actual = ColorExtensions.MakeColor(null); Assert.AreEqual(expected, actual); } [Test] public void MakeColor_Test_Empty_Param() { Color expected = Color.magenta; Color actual = ColorExtensions.MakeColor(""); Assert.AreEqual(expected, actual); } [Test] public void MakeColor_Test_Fail_Hex_Parse() { string badHex = "#XXXXXX"; Color expected = Color.magenta; // Supress debug log error message during unit tests ColorExtensions.debugLogMessagesOn = false; Color actual = ColorExtensions.MakeColor(badHex); Assert.AreEqual(expected, actual); } [Test, TestCaseSource("RGBStringCases")] public void MakeColor_Test_RBGString_Normal_Usage(string rgb, Color expected) { Color actual = ColorExtensions.MakeColor(rgb); Assert.AreEqual(expected, actual); } [Test, TestCaseSource("RGBAStringCases")] public void MakeColor_Test_RBGAString_Normal_Usage(string rgb, Color expected) { Color actual = ColorExtensions.MakeColor(rgb); Assert.AreEqual(expected, actual); } [Test, TestCaseSource("BadRGBStrings")] public void MakeColor_Test_Fail_RGB_Parse(string badRgbString) { Color expected = Color.magenta; ColorExtensions.debugLogMessagesOn = false; Color actual = ColorExtensions.MakeColor(badRgbString); Assert.AreEqual(expected, actual); } #endregion #region color.Clamp() [Test, TestCaseSource("ClampCases")] public void Clamp_Test(Color color, Color expected) { Color actual = color.Clamp(); Assert.AreEqual(expected, actual); } #endregion #region MakeHSB(Color c) // Values do not conform to HSB standards /* [Test, TestCaseSource("MakeHSBColorCases")] public void MakeHSB(Color c, Vector3 expected) { Vector3 actual = ColorExtensions.MakeHSB(c); if (actual != expected) Assert.Fail("expected: {0}\nactual:{1}", expected, actual); } */ #endregion } }
namespace Lettuce { partial class UnhandledExceptionForm { /// <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.pictureBox1 = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.button5 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this.labelRecover = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.Image = global::Lettuce.Properties.Resources._1337914149_Tomato64; this.pictureBox1.Location = new System.Drawing.Point(12, 12); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(64, 64); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(82, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(165, 20); this.label1.TabIndex = 1; this.label1.Text = "Unhandled Exception!"; // // label2 // this.label2.Location = new System.Drawing.Point(83, 32); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(305, 44); this.label2.TabIndex = 2; this.label2.Text = "An unhandled exception (basically, an error) has occured. This makes the develop" + "ers really sad, and we\'d appriciate it if you told us about it so we could fix i" + "t."; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(12, 79); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(110, 13); this.label3.TabIndex = 3; this.label3.Text = "Technical Details:"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(12, 95); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(385, 78); this.textBox1.TabIndex = 4; // // button1 // this.button1.Location = new System.Drawing.Point(12, 205); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(122, 23); this.button1.TabIndex = 5; this.button1.Text = "Copy Details"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(140, 176); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(122, 23); this.button2.TabIndex = 6; this.button2.Text = "Email Devs"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Location = new System.Drawing.Point(12, 176); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(122, 23); this.button3.TabIndex = 7; this.button3.Text = "Create GitHub Issue"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 // this.button4.Location = new System.Drawing.Point(140, 205); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(122, 23); this.button4.TabIndex = 8; this.button4.Text = "Consolatory Hug"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // button5 // this.button5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button5.Location = new System.Drawing.Point(268, 176); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(129, 23); this.button5.TabIndex = 9; this.button5.Text = "Close Lettuce"; this.button5.UseVisualStyleBackColor = true; this.button5.Click += new System.EventHandler(this.button5_Click); // // button6 // this.button6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button6.Location = new System.Drawing.Point(268, 205); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(129, 23); this.button6.TabIndex = 10; this.button6.Text = "Attempt to Carry On"; this.button6.UseVisualStyleBackColor = true; this.button6.Click += new System.EventHandler(this.button6_Click); // // labelRecover // this.labelRecover.AutoSize = true; this.labelRecover.Location = new System.Drawing.Point(210, 79); this.labelRecover.Name = "labelRecover"; this.labelRecover.Size = new System.Drawing.Size(187, 13); this.labelRecover.TabIndex = 11; this.labelRecover.Text = "Lettuce cannot recover from this error."; this.labelRecover.Visible = false; // // UnhandledExceptionForm // this.AcceptButton = this.button5; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(407, 236); this.Controls.Add(this.labelRecover); this.Controls.Add(this.button6); this.Controls.Add(this.button5); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.pictureBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "UnhandledExceptionForm"; this.Text = "Unhandled Exception"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button6; private System.Windows.Forms.Label labelRecover; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server { public delegate void OnIRCClientReadyDelegate(IRCClientView cv); public class IRCClientView : IClientAPI, IClientCore { public event OnIRCClientReadyDelegate OnIRCReady; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly TcpClient m_client; private readonly Scene m_scene; private UUID m_agentID = UUID.Random(); public ISceneAgent SceneAgent { get; set; } public int PingTimeMS { get { return 0; } } private string m_username; private string m_nick; private bool m_hasNick = false; private bool m_hasUser = false; private bool m_connected = true; public List<uint> SelectedObjects {get; private set;} public IRCClientView(TcpClient client, Scene scene) { m_client = client; m_scene = scene; WorkManager.StartThread(InternalLoop, "IRCClientView", ThreadPriority.Normal, false, true); } private void SendServerCommand(string command) { SendCommand(":opensimircd " + command); } private void SendCommand(string command) { m_log.Info("[IRCd] Sending >>> " + command); byte[] buf = Util.UTF8.GetBytes(command + "\r\n"); m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null); } private void SendComplete(IAsyncResult result) { m_log.Info("[IRCd] Send Complete."); } private string IrcRegionName { // I know &Channel is more technically correct, but people are used to seeing #Channel // Dont shoot me! get { return "#" + m_scene.RegionInfo.RegionName.Replace(" ", "-"); } } private void InternalLoop() { try { string strbuf = String.Empty; while (m_connected && m_client.Connected) { byte[] buf = new byte[8]; // RFC1459 defines max message size as 512. int count = m_client.GetStream().Read(buf, 0, buf.Length); string line = Util.UTF8.GetString(buf, 0, count); strbuf += line; string message = ExtractMessage(strbuf); if (message != null) { // Remove from buffer strbuf = strbuf.Remove(0, message.Length); m_log.Info("[IRCd] Recieving <<< " + message); message = message.Trim(); // Extract command sequence string command = ExtractCommand(message); ProcessInMessage(message, command); } else { //m_log.Info("[IRCd] Recieved data, but not enough to make a message. BufLen is " + strbuf.Length + // "[" + strbuf + "]"); if (strbuf.Length == 0) { m_connected = false; m_log.Info("[IRCd] Buffer zero, closing..."); if (OnDisconnectUser != null) OnDisconnectUser(); } } Thread.Sleep(0); Watchdog.UpdateThread(); } } catch (IOException) { if (OnDisconnectUser != null) OnDisconnectUser(); m_log.Warn("[IRCd] Disconnected client."); } catch (SocketException) { if (OnDisconnectUser != null) OnDisconnectUser(); m_log.Warn("[IRCd] Disconnected client."); } Watchdog.RemoveThread(); } private void ProcessInMessage(string message, string command) { m_log.Info("[IRCd] Processing [MSG:" + message + "] [COM:" + command + "]"); if (command != null) { switch (command) { case "ADMIN": case "AWAY": case "CONNECT": case "DIE": case "ERROR": case "INFO": case "INVITE": case "ISON": case "KICK": case "KILL": case "LINKS": case "LUSERS": case "OPER": case "PART": case "REHASH": case "SERVICE": case "SERVLIST": case "SERVER": case "SQUERY": case "SQUIT": case "STATS": case "SUMMON": case "TIME": case "TRACE": case "VERSION": case "WALLOPS": case "WHOIS": case "WHOWAS": SendServerCommand("421 " + command + " :Command unimplemented"); break; // Connection Commands case "PASS": break; // Ignore for now. I want to implement authentication later however. case "JOIN": IRC_SendReplyJoin(); break; case "MODE": IRC_SendReplyModeChannel(); break; case "USER": IRC_ProcessUser(message); IRC_Ready(); break; case "USERHOST": string[] userhostArgs = ExtractParameters(message); if (userhostArgs[0] == ":" + m_nick) { SendServerCommand("302 :" + m_nick + "=+" + m_nick + "@" + ((IPEndPoint) m_client.Client.RemoteEndPoint).Address); } break; case "NICK": IRC_ProcessNick(message); IRC_Ready(); break; case "TOPIC": IRC_SendReplyTopic(); break; case "USERS": IRC_SendReplyUsers(); break; case "LIST": break; // TODO case "MOTD": IRC_SendMOTD(); break; case "NOTICE": // TODO break; case "WHO": // TODO IRC_SendNamesReply(); IRC_SendWhoReply(); break; case "PING": IRC_ProcessPing(message); break; // Special case, ignore this completely. case "PONG": break; case "QUIT": if (OnDisconnectUser != null) OnDisconnectUser(); break; case "NAMES": IRC_SendNamesReply(); break; case "PRIVMSG": IRC_ProcessPrivmsg(message); break; default: SendServerCommand("421 " + command + " :Unknown command"); break; } } } private void IRC_Ready() { if (m_hasUser && m_hasNick) { SendServerCommand("001 " + m_nick + " :Welcome to OpenSimulator IRCd"); SendServerCommand("002 " + m_nick + " :Running OpenSimVersion"); SendServerCommand("003 " + m_nick + " :This server was created over 9000 years ago"); SendServerCommand("004 " + m_nick + " :opensimirc r1 aoOirw abeiIklmnoOpqrstv"); SendServerCommand("251 " + m_nick + " :There are 0 users and 0 services on 1 servers"); SendServerCommand("252 " + m_nick + " 0 :operators online"); SendServerCommand("253 " + m_nick + " 0 :unknown connections"); SendServerCommand("254 " + m_nick + " 1 :channels formed"); SendServerCommand("255 " + m_nick + " :I have 1 users, 0 services and 1 servers"); SendCommand(":" + m_nick + " MODE " + m_nick + " :+i"); SendCommand(":" + m_nick + " JOIN :" + IrcRegionName); // Rename to 'Real Name' SendCommand(":" + m_nick + " NICK :" + m_username.Replace(" ", "")); m_nick = m_username.Replace(" ", ""); IRC_SendReplyJoin(); IRC_SendChannelPrivmsg("System", "Welcome to OpenSimulator."); IRC_SendChannelPrivmsg("System", "You are in a maze of twisty little passages, all alike."); IRC_SendChannelPrivmsg("System", "It is pitch black. You are likely to be eaten by a grue."); if (OnIRCReady != null) OnIRCReady(this); } } private void IRC_SendReplyJoin() { IRC_SendReplyTopic(); IRC_SendNamesReply(); } private void IRC_SendReplyModeChannel() { SendServerCommand("324 " + m_nick + " " + IrcRegionName + " +n"); //SendCommand(":" + IrcRegionName + " MODE +n"); } private void IRC_ProcessUser(string message) { string[] userArgs = ExtractParameters(message); // TODO: unused: string username = userArgs[0]; // TODO: unused: string hostname = userArgs[1]; // TODO: unused: string servername = userArgs[2]; string realname = userArgs[3].Replace(":", ""); m_username = realname; m_hasUser = true; } private void IRC_ProcessNick(string message) { string[] nickArgs = ExtractParameters(message); string nickname = nickArgs[0].Replace(":",""); m_nick = nickname; m_hasNick = true; } private void IRC_ProcessPing(string message) { string[] pingArgs = ExtractParameters(message); string pingHost = pingArgs[0]; SendCommand("PONG " + pingHost); } private void IRC_ProcessPrivmsg(string message) { string[] privmsgArgs = ExtractParameters(message); if (privmsgArgs[0] == IrcRegionName) { if (OnChatFromClient != null) { OSChatMessage msg = new OSChatMessage(); msg.Sender = this; msg.Channel = 0; msg.From = this.Name; msg.Message = privmsgArgs[1].Replace(":", ""); msg.Position = Vector3.Zero; msg.Scene = m_scene; msg.SenderObject = null; msg.SenderUUID = this.AgentId; msg.Type = ChatTypeEnum.Say; OnChatFromClient(this, msg); } } else { // Handle as an IM, later. } } private void IRC_SendNamesReply() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); foreach (EntityBase user in users) { SendServerCommand("353 " + m_nick + " = " + IrcRegionName + " :" + user.Name.Replace(" ", "")); } SendServerCommand("366 " + IrcRegionName + " :End of /NAMES list"); } private void IRC_SendWhoReply() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); foreach (EntityBase user in users) { /*SendServerCommand(String.Format("352 {0} {1} {2} {3} {4} {5} :0 {6}", IrcRegionName, user.Name.Replace(" ", ""), "nohost.com", "opensimircd", user.Name.Replace(" ", ""), 'H', user.Name));*/ SendServerCommand("352 " + m_nick + " " + IrcRegionName + " n=" + user.Name.Replace(" ", "") + " fakehost.com " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name); //SendServerCommand("352 " + IrcRegionName + " " + user.Name.Replace(" ", "") + " nohost.com irc.opensimulator " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name); } SendServerCommand("315 " + m_nick + " " + IrcRegionName + " :End of /WHO list"); } private void IRC_SendMOTD() { SendServerCommand("375 :- OpenSimulator Message of the day -"); SendServerCommand("372 :- Hiya!"); SendServerCommand("376 :End of /MOTD command"); } private void IRC_SendReplyTopic() { SendServerCommand("332 " + IrcRegionName + " :OpenSimulator IRC Server"); } private void IRC_SendReplyUsers() { EntityBase[] users = m_scene.Entities.GetAllByType<ScenePresence>(); SendServerCommand("392 :UserID Terminal Host"); if (users.Length == 0) { SendServerCommand("395 :Nobody logged in"); return; } foreach (EntityBase user in users) { char[] nom = new char[8]; char[] term = "terminal_".ToCharArray(); char[] host = "hostname".ToCharArray(); string userName = user.Name.Replace(" ",""); for (int i = 0; i < nom.Length; i++) { if (userName.Length < i) nom[i] = userName[i]; else nom[i] = ' '; } SendServerCommand("393 :" + nom + " " + term + " " + host + ""); } SendServerCommand("394 :End of users"); } private static string ExtractMessage(string buffer) { int pos = buffer.IndexOf("\r\n"); if (pos == -1) return null; string command = buffer.Substring(0, pos + 2); return command; } private static string ExtractCommand(string msg) { string[] msgs = msg.Split(' '); if (msgs.Length < 2) { m_log.Warn("[IRCd] Dropped msg: " + msg); return null; } if (msgs[0].StartsWith(":")) return msgs[1]; return msgs[0]; } private static string[] ExtractParameters(string msg) { string[] msgs = msg.Split(' '); List<string> parms = new List<string>(msgs.Length); bool foundCommand = false; string command = ExtractCommand(msg); for (int i=0;i<msgs.Length;i++) { if (msgs[i] == command) { foundCommand = true; continue; } if (foundCommand != true) continue; if (i != 0 && msgs[i].StartsWith(":")) { List<string> tmp = new List<string>(); for (int j=i;j<msgs.Length;j++) { tmp.Add(msgs[j]); } parms.Add(string.Join(" ", tmp.ToArray())); break; } parms.Add(msgs[i]); } return parms.ToArray(); } #region Implementation of IClientAPI public Vector3 StartPos { get { return new Vector3(m_scene.RegionInfo.RegionSizeX * 0.5f, m_scene.RegionInfo.RegionSizeY * 0.5f, 50f); } set { } } public bool TryGet<T>(out T iface) { iface = default(T); return false; } public T Get<T>() { return default(T); } public UUID AgentId { get { return m_agentID; } } public void Disconnect(string reason) { IRC_SendChannelPrivmsg("System", "You have been eaten by a grue. (" + reason + ")"); m_connected = false; m_client.Close(); } public void Disconnect() { IRC_SendChannelPrivmsg("System", "You have been eaten by a grue."); m_connected = false; m_client.Close(); SceneAgent = null; } public UUID SessionId { get { return m_agentID; } } public UUID SecureSessionId { get { return m_agentID; } } public UUID ActiveGroupId { get { return UUID.Zero; } } public string ActiveGroupName { get { return "IRCd User"; } } public ulong ActiveGroupPowers { get { return 0; } } public ulong GetGroupPowers(UUID groupID) { return 0; } public bool IsGroupMember(UUID GroupID) { return false; } public string FirstName { get { string[] names = m_username.Split(' '); return names[0]; } } public string LastName { get { string[] names = m_username.Split(' '); if (names.Length > 1) return names[1]; return names[0]; } } public IScene Scene { get { return m_scene; } } public int NextAnimationSequenceNumber { get { return 0; } } public string Name { get { return m_username; } } public bool IsActive { get { return true; } set { if (!value) Disconnect("IsActive Disconnected?"); } } public bool IsLoggingOut { get { return false; } set { } } public bool SendLogoutPacketWhenClosing { set { } } public uint CircuitCode { get { return (uint)Util.RandomClass.Next(0,int.MaxValue); } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint)m_client.Client.RemoteEndPoint; } } #pragma warning disable 67 public event GenericMessage OnGenericMessage; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event EstateChangeInfo OnEstateChangeInfo; public event EstateManageTelehub OnEstateManageTelehub; public event CachedTextureRequest OnCachedTextureRequest; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event ChangeAnim OnChangeAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event SetAlwaysRun OnSetAlwaysRun; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event TeleportCancel OnTeleportCancel; public event DeRezObject OnDeRezObject; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall1 OnRequestWearables; public event Action<IClientAPI, bool> OnCompleteMovementToRegion; public event UpdateAgent OnPreAgentUpdate; public event UpdateAgent OnAgentUpdate; public event UpdateAgent OnAgentCameraUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event ObjectRequest OnObjectRequest; public event ObjectSelect OnObjectSelect; public event ObjectDeselect OnObjectDeselect; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event ClientChangeObject onClientChangeObject; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<UUID> OnRemoveAvatar; public event ObjectPermissions OnObjectPermissions; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event LinkInventoryItem OnLinkInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event UUIDNameRequest OnNameFromUUIDRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event GrantUserFriendRights OnGrantUserRights; public event MoneyTransferRequest OnMoneyTransferRequest; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event ParcelBuy OnParcelBuy; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event AgentSit OnUndo; public event AgentSit OnRedo; public event LandUndo OnLandUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event Action<Vector3, bool, bool> OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event ActivateGesture OnActivateGesture; public event DeactivateGesture OnDeactivateGesture; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event MoveItemsAndLeaveCopy OnMoveItemsAndLeaveCopy; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedGodDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event AvatarInterestUpdate OnAvatarInterestUpdate; public event PlacesQuery OnPlacesQuery; public event FindAgentUpdate OnFindAgent; public event TrackAgentUpdate OnTrackAgent; public event NewUserReport OnUserReport; public event SaveStateHandler OnSaveState; public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest; public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest; public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest; public event FreezeUserUpdate OnParcelFreezeUser; public event EjectUserUpdate OnParcelEjectUser; public event ParcelBuyPass OnParcelBuyPass; public event ParcelGodMark OnParcelGodMark; public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest; public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest; public event SimWideDeletesDelegate OnSimWideDeletes; public event SendPostcard OnSendPostcard; public event ChangeInventoryItemFlags OnChangeInventoryItemFlags; public event MuteListEntryUpdate OnUpdateMuteListEntry; public event MuteListEntryRemove OnRemoveMuteListEntry; public event GodlikeMessage onGodlikeMessage; public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate; public event GenericCall2 OnUpdateThrottles; #pragma warning restore 67 public int DebugPacketLevel { get; set; } public void InPacket(object NewPack) { } public void ProcessInPacket(Packet NewPack) { } public void Close() { Close(true, false); } public void Close(bool sendStop, bool force) { Disconnect(); } public void Kick(string message) { Disconnect(message); } public void Start() { m_scene.AddNewAgent(this, PresenceType.User); // Mimicking LLClientView which gets always set appearance from client. AvatarAppearance appearance; m_scene.GetAvatarAppearance(this, out appearance); OnSetAppearance(this, appearance.Texture, (byte[])appearance.VisualParams.Clone(),appearance.AvatarSize, new WearableCacheItem[0]); } public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { m_log.Info("[IRCd ClientStack] Completing Handshake to Region"); if (OnRegionHandShakeReply != null) { OnRegionHandShakeReply(this); } if (OnCompleteMovementToRegion != null) { OnCompleteMovementToRegion(this, true); } } public void Stop() { Disconnect(); } public void SendWearables(AvatarWearable[] wearables, int serial) { } public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { } public void SendCachedTextureResponse(ISceneEntity avatar, int serial, List<CachedTextureResponseArg> cachedTextures) { } public void SendStartPingCheck(byte seq) { } public void SendKillObject(List<uint> localID) { } public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } public void SendChatMessage( string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, UUID ownerID, byte source, byte audible) { if (audible > 0 && message.Length > 0) IRC_SendChannelPrivmsg(fromName, message); } private void IRC_SendChannelPrivmsg(string fromName, string message) { SendCommand(":" + fromName.Replace(" ", "") + " PRIVMSG " + IrcRegionName + " :" + message); } public void SendInstantMessage(GridInstantMessage im) { // TODO } public void SendGenericMessage(string method, UUID invoice, List<string> message) { } public void SendGenericMessage(string method, UUID invoice, List<byte[]> message) { } public virtual bool CanSendLayerData() { return false; } public void SendLayerData(float[] map) { } public void SendLayerData(int px, int py, float[] map) { } public void SendWindData(Vector2[] windSpeeds) { } public void SendCloudData(float[] cloudCover) { } public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { } public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { } public AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { } public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { } public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { } public void SendTeleportFailed(string reason) { } public void SendTeleportStart(uint flags) { } public void SendTeleportProgress(uint flags, string message) { } public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance, int transactionType, UUID sourceID, bool sourceIsGroup, UUID destID, bool destIsGroup, int amount, string item) { } public void SendPayPrice(UUID objectID, int[] payPrice) { } public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { } public void SendAvatarDataImmediate(ISceneEntity avatar) { } public void SendEntityUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } public void ReprioritizeUpdates() { } public void FlushPrimUpdates() { } public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems) { } public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId) { } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, UUID transactionID, uint callbackId) { } public void SendRemoveInventoryItem(UUID itemID) { } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { } public void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { } public void SendBulkUpdateInventory(InventoryNodeBase node) { } public void SendXferPacket(ulong xferID, uint packet, byte[] data, bool isTaskInventory) { } public void SendAbortXferPacket(ulong xferID) { } public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { } public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { } public void SendAttachedSoundGainChange(UUID objectID, float gain) { } public void SendNameReply(UUID profileId, string firstname, string lastname) { } public void SendAlertMessage(string message) { IRC_SendChannelPrivmsg("Alert",message); } public void SendAgentAlertMessage(string message, bool modal) { } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { IRC_SendChannelPrivmsg(objectname,url); } public void SendDialog(string objectname, UUID objectID, UUID ownerID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition) { } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { } public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID) { } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(UUID covenant) { } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, uint covenantChanged, string abuseEmail, UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<LandAccessEntry> accessList, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { } public void SendImageNotFound(UUID imageid) { } public void SendShutdownConnectionNotice() { // TODO } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags) { } public void SendObjectPropertiesReply(ISceneEntity entity) { } public void SendAgentOffline(UUID[] agentIDs) { } public void SendAgentOnline(UUID[] agentIDs) { } public void SendFindAgent(UUID HunterID, UUID PreyID, double GlobalX, double GlobalY) { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { } public void SendJoinGroupReply(UUID groupID, bool success) { } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success) { } public void SendLeaveGroupReply(UUID groupID, bool success) { } public void SendCreateGroupReply(UUID groupID, bool success, string message) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { } public void SendAsset(AssetRequestToClient req) { } public void SendTexture(AssetBase TextureAsset) { } public virtual void SetChildAgentThrottle(byte[] throttle) { } public virtual void SetChildAgentThrottle(byte[] throttle,float factor) { } public void SetAgentThrottleSilent(int throttle, int setting) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } #pragma warning disable 0067 public event ViewerEffectEventHandler OnViewerEffect; public event Action<IClientAPI> OnLogout; public event Action<IClientAPI> OnConnectionClosed; #pragma warning restore 0067 public void SendBlueBoxMessage(UUID FromAvatarID, string FromAvatarName, string Message) { IRC_SendChannelPrivmsg(FromAvatarName, Message); } public void SendLogoutPacket() { Disconnect(); } public ClientInfo GetClientInfo() { return new ClientInfo(); } public void SetClientInfo(ClientInfo info) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return String.Empty; } public void Terminate() { Disconnect(); } public void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters) { } public void SendClearFollowCamProperties(UUID objectID) { } public void SendRegionHandle(UUID regoinID, ulong handle) { } public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { } public void SendEventInfoReply(EventData info) { } public void SendTelehubInfo(UUID ObjectID, string ObjectName, Vector3 ObjectPos, Quaternion ObjectRot, List<Vector3> SpawnPoint) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { } public void SendAgentGroupDataUpdate(UUID avatarID, GroupMembershipData[] data) { } public void SendOfferCallingCard(UUID srcID, UUID transactionID) { } public void SendAcceptCallingCard(UUID transactionID) { } public void SendDeclineCallingCard(UUID transactionID) { } public void SendTerminateFriend(UUID exFriendID) { } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(UUID groupID) { } public void RefreshGroupMembership() { } public void SendAvatarNotesReply(UUID targetID, string text) { } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { } public void SendPickInfoReply(UUID pickID, UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { } public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages) { } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { return true; } #endregion public void SendRebakeAvatarTextures(UUID textureID) { } public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) { } public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { } public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier) { } public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt) { } public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes) { } public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) { } public void SendChangeUserRights(UUID agentID, UUID friendID, int rights) { } public void SendTextBoxRequest(string message, int chatChannel, string objectname, UUID ownerID, string ownerFirstName, string ownerLastName, UUID objectId) { } public void SendAgentTerseUpdate(ISceneEntity presence) { } public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } public void SendPartPhysicsProprieties(ISceneEntity entity) { } public void SendPartFullUpdate(ISceneEntity ent, uint? parentID) { } public int GetAgentThrottleSilent(int throttle) { return 0; } } }
using System; using QUnit; namespace CoreLib.TestScript.SimpleTypes { [TestFixture] public class TimeSpanTests { [Test] public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(TimeSpan).FullName, "ss.TimeSpan"); Assert.IsFalse(typeof(TimeSpan).IsClass); Assert.IsTrue(typeof(IComparable<TimeSpan>).IsAssignableFrom(typeof(TimeSpan))); Assert.IsTrue(typeof(IEquatable<TimeSpan>).IsAssignableFrom(typeof(TimeSpan))); object d = new TimeSpan(); Assert.IsTrue(d is TimeSpan); Assert.IsTrue(d is IComparable<TimeSpan>); Assert.IsTrue(d is IEquatable<TimeSpan>); var interfaces = typeof(TimeSpan).GetInterfaces(); Assert.AreEqual(interfaces.Length, 2); Assert.IsTrue(interfaces.Contains(typeof(IComparable<DateTime>))); Assert.IsTrue(interfaces.Contains(typeof(IEquatable<DateTime>))); } [Test] public void DefaultConstructorWorks() { var time = new TimeSpan(); Assert.AreEqual(time.Ticks, 0); } [Test] public void DefaultValueWorks() { var ts = default(TimeSpan); Assert.AreEqual(ts.Ticks, 0); } [Test] public void CreatingInstanceReturnsTimeSpanWithZeroValue() { var ts = Activator.CreateInstance<TimeSpan>(); Assert.AreEqual(ts.Ticks, 0); } [Test] public void ParameterConstructorsWorks() { var time = new TimeSpan(34567L); Assert.IsTrue((object)time is TimeSpan, "ticks type"); Assert.AreEqual(time.Ticks, 34567, "ticks value"); time = new TimeSpan(10, 20, 5); Assert.IsTrue((object)time is TimeSpan, "h, m, s type"); Assert.AreEqual(time.Ticks, 372050000000, "h, m, s value"); time = new TimeSpan(15, 10, 20, 5); Assert.IsTrue((object)time is TimeSpan, "d, h, m, s type"); Assert.AreEqual(time.Ticks, 13332050000000, "d, h, m, s value"); time = new TimeSpan(15, 10, 20, 5, 14); Assert.IsTrue((object)time is TimeSpan, "full type"); Assert.AreEqual(time.Ticks, 13332050140000, "full value"); } [Test] public void FactoryMethodsWork() { var time = TimeSpan.FromDays(3); Assert.IsTrue((object)time is TimeSpan, "FromDays type"); Assert.AreEqual(time.Ticks, 2592000000000, "FromDays value"); time = TimeSpan.FromHours(3); Assert.IsTrue((object)time is TimeSpan, "FromHours type"); Assert.AreEqual(time.Ticks, 108000000000, "FromHours value"); time = TimeSpan.FromMinutes(3); Assert.IsTrue((object)time is TimeSpan, "FromMinutes type"); Assert.AreEqual(time.Ticks, 1800000000, "FromMinutes value"); time = TimeSpan.FromSeconds(3); Assert.IsTrue((object)time is TimeSpan, "FromSeconds type"); Assert.AreEqual(time.Ticks, 30000000, "FromSeconds value"); time = TimeSpan.FromMilliseconds(3); Assert.IsTrue((object)time is TimeSpan, "FromMilliseconds type"); Assert.AreEqual(time.Ticks, 30000, "FromMilliseconds value"); time = TimeSpan.FromTicks(3); Assert.IsTrue((object)time is TimeSpan, "FromTicks type"); Assert.AreEqual(time.Ticks, 3, "FromTicks value"); } [Test] public void PropertiesWork() { var time = new TimeSpan(15, 10, 20, 5, 14); Assert.AreEqual(time.Days, 15); Assert.AreEqual(time.Hours, 10); Assert.AreEqual(time.Minutes, 20); Assert.AreEqual(time.Seconds, 5); Assert.AreEqual(time.Milliseconds, 14); AssertAlmostEqual(time.TotalDays, 15.430613587962963d); AssertAlmostEqual(time.TotalHours, 370.33472611111108d); AssertAlmostEqual(time.TotalMinutes, 22220.083566666668d); AssertAlmostEqual(time.TotalSeconds, 1333205.014d); AssertAlmostEqual(time.TotalMilliseconds, 1333205014.0d); Assert.AreEqual(time.Ticks, 15 * TimeSpan.TicksPerDay + 10 * TimeSpan.TicksPerHour + 20 * TimeSpan.TicksPerMinute + 5 * TimeSpan.TicksPerSecond + 14 * TimeSpan.TicksPerMillisecond); } [Test] public void CompareToWorks() { var time1 = new TimeSpan(15, 10, 20, 5, 14); var time2 = new TimeSpan(15, 10, 20, 5, 14); var time3 = new TimeSpan(14, 10, 20, 5, 14); var time4 = new TimeSpan(15, 11, 20, 5, 14); Assert.AreEqual(0, time1.CompareTo(time1)); Assert.AreEqual(0, time1.CompareTo(time2)); Assert.AreEqual(1, time1.CompareTo(time3)); Assert.AreEqual(-1, time1.CompareTo(time4)); } [Test] public void CompareWorks() { var time1 = new TimeSpan(15, 10, 20, 5, 14); var time2 = new TimeSpan(15, 10, 20, 5, 14); var time3 = new TimeSpan(14, 10, 20, 5, 14); var time4 = new TimeSpan(15, 11, 20, 5, 14); Assert.AreEqual(0, TimeSpan.Compare(time1, time1)); Assert.AreEqual(0, TimeSpan.Compare(time1, time2)); Assert.AreEqual(1, TimeSpan.Compare(time1, time3)); Assert.AreEqual(-1, TimeSpan.Compare(time1, time4)); } [Test] public void StaticEqualsWorks() { var time1 = new TimeSpan(15, 10, 20, 5, 14); var time2 = new TimeSpan(14, 10, 20, 5, 14); var time3 = new TimeSpan(15, 10, 20, 5, 14); Assert.IsFalse(TimeSpan.Equals(time1, time2)); Assert.IsTrue (TimeSpan.Equals(time1, time3)); } [Test] public void EqualsWorks() { var time1 = new TimeSpan(15, 10, 20, 5, 14); var time2 = new TimeSpan(14, 10, 20, 5, 14); var time3 = new TimeSpan(15, 10, 20, 5, 14); Assert.IsFalse(time1.Equals(time2)); Assert.IsTrue (time1.Equals(time3)); } [Test] public void IEquatableEqualsWorks() { var time1 = new TimeSpan(15, 10, 20, 5, 14); var time2 = new TimeSpan(14, 10, 20, 5, 14); var time3 = new TimeSpan(15, 10, 20, 5, 14); Assert.IsFalse(((IEquatable<TimeSpan>)time1).Equals(time2)); Assert.IsTrue (((IEquatable<TimeSpan>)time1).Equals(time3)); } [Test] public void ToStringWorks() { var time1 = new TimeSpan(15, 10, 20, 5, 14); var time2 = new TimeSpan(14, 10, 20, 5, 2); var time3 = new TimeSpan(15, 11, 20, 6, 14); var time4 = new TimeSpan(1, 2, 3); Assert.AreEqual(time1.ToString(), "15.10:20:05.0140000"); Assert.AreEqual(time2.ToString(), "14.10:20:05.0020000"); Assert.AreEqual(time3.ToString(), "15.11:20:06.0140000"); Assert.AreEqual(time4.ToString(), "01:02:03"); } [Test] public void AddWorks() { var time1 = new TimeSpan(2, 3, 4, 5, 6); var time2 = new TimeSpan(3, 4, 5, 6, 7); TimeSpan actual = time1.Add(time2); Assert.IsTrue((object)actual is TimeSpan, "Should be TimeSpan"); Assert.AreEqual(actual.TotalMilliseconds, ((((((5 * 24) + 7) * 60) + 9) * 60) + 11) * 1000 + 13, "TotalMilliseconds should be correct"); } [Test] public void SubtractWorks() { var time1 = new TimeSpan(4, 3, 7, 2, 6); var time2 = new TimeSpan(3, 4, 5, 6, 7); TimeSpan actual = time1.Subtract(time2); Assert.IsTrue((object)actual is TimeSpan, "Should be TimeSpan"); Assert.AreEqual(actual.TotalMilliseconds, ((((((1 * 24) - 1) * 60) + 2) * 60) - 4) * 1000 - 1, "TotalMilliseconds should be correct"); } [Test] public void DurationWorks() { var time1 = new TimeSpan(-3, -2, -1, -5, -4); var time2 = new TimeSpan( 2, 1, 5, 4, 3); TimeSpan actual1 = time1.Duration(); TimeSpan actual2 = time2.Duration(); Assert.IsTrue((object)time1 is TimeSpan, "Should be TimeSpan"); Assert.AreEqual(actual1.TotalMilliseconds, (((((3 * 24) + 2) * 60 + 1) * 60) + 5) * 1000 + 4, "Negative should be negated"); Assert.AreEqual(actual2.TotalMilliseconds, (((((2 * 24) + 1) * 60 + 5) * 60) + 4) * 1000 + 3, "Positive should be preserved"); } [Test] public void NegateWorks() { var time = new TimeSpan(-3, 2, -1, 5, -4); TimeSpan actual = time.Negate(); Assert.IsTrue((object)actual is TimeSpan, "Should be TimeSpan"); Assert.AreEqual(actual.TotalMilliseconds, (((((3 * 24) - 2) * 60 + 1) * 60) - 5) * 1000 + 4, "Ticks should be correct"); } private void AssertAlmostEqual(double d1, double d2) { var diff = d2 - d1; if (diff < 0) diff = -diff; Assert.IsTrue(diff < 1e-8); } [Test] public void ComparisonOperatorsWork() { #pragma warning disable 1718 var time1 = new TimeSpan(15, 10, 20, 5, 14); var time2 = new TimeSpan(15, 10, 20, 5, 14); var time3 = new TimeSpan(14, 10, 20, 5, 14); var time4 = new TimeSpan(15, 11, 20, 5, 14); Assert.IsFalse(time1 > time2, "> 1"); Assert.IsTrue (time1 > time3, "> 2"); Assert.IsFalse(time1 > time4, "> 3"); Assert.IsTrue (time1 >= time2, ">= 1"); Assert.IsTrue (time1 >= time3, ">= 2"); Assert.IsFalse(time1 >= time4, ">= 3"); Assert.IsFalse(time1 < time2, "< 1"); Assert.IsFalse(time1 < time3, "< 2"); Assert.IsTrue (time1 < time4, "< 3"); Assert.IsTrue (time1 <= time2, "<= 1"); Assert.IsFalse(time1 <= time3, "<= 2"); Assert.IsTrue (time1 <= time4, "<= 3"); Assert.IsTrue (time1 == time1, "== 1"); Assert.IsTrue (time1 == time2, "== 2"); Assert.IsFalse(time1 == time3, "== 3"); Assert.IsFalse(time1 == time4, "== 4"); Assert.IsFalse(time1 != time1, "!= 1"); Assert.IsFalse(time1 != time2, "!= 2"); Assert.IsTrue (time1 != time3, "!= 3"); Assert.IsTrue (time1 != time4, "!= 4"); #pragma warning restore 1718 } [Test] public void AdditionOperatorWorks() { var time1 = new TimeSpan(2, 3, 4, 5, 6); var time2 = new TimeSpan(3, 4, 5, 6, 7); TimeSpan actual = time1 + time2; Assert.IsTrue((object)actual is TimeSpan, "Should be TimeSpan"); Assert.AreEqual(actual.TotalMilliseconds, ((((((5 * 24) + 7) * 60) + 9) * 60) + 11) * 1000 + 13, "TotalMilliseconds should be correct"); } [Test] public void SubtractionOperatorWorks() { var time1 = new TimeSpan(4, 3, 7, 2, 6); var time2 = new TimeSpan(3, 4, 5, 6, 7); TimeSpan actual = time1 - time2; Assert.IsTrue((object)actual is TimeSpan, "Should be TimeSpan"); Assert.AreEqual(actual.TotalMilliseconds, ((((((1 * 24) - 1) * 60) + 2) * 60) - 4) * 1000 - 1, "TotalMilliseconds should be correct"); } [Test] public void UnaryPlusWorks() { var time = new TimeSpan(-3, 2, -1, 5, -4); TimeSpan actual = +time; Assert.IsTrue((object)actual is TimeSpan, "Should be TimeSpan"); Assert.AreEqual(actual.TotalMilliseconds, (((((-3 * 24) + 2) * 60 - 1) * 60) + 5) * 1000 - 4, "Ticks should be correct"); } [Test] public void UnaryMinusWorks() { var time = new TimeSpan(-3, 2, -1, 5, -4); TimeSpan actual = -time; Assert.IsTrue((object)actual is TimeSpan, "Should be TimeSpan"); Assert.AreEqual(actual.TotalMilliseconds, (((((3 * 24) - 2) * 60 + 1) * 60) - 5) * 1000 + 4, "Ticks should be correct"); } } }
namespace Sitecore.FakeDb.Tests.Links { using System; using System.Collections.Specialized; using System.Web; using FluentAssertions; using NSubstitute; using global::AutoFixture; using global::AutoFixture.AutoNSubstitute; using global::AutoFixture.Xunit2; using Sitecore.Common; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.FakeDb.Links; using Sitecore.Links; using Sitecore.Links.UrlBuilders; using Sitecore.Web; using Xunit; using StringDictionary = Sitecore.Collections.StringDictionary; [Obsolete("SwitchingLinkProvider is obsolete.")] public class SwitchingLinkProviderTest { [Theory, AutoData] public void SutIsLinkProvider(SwitchingLinkProvider sut) { sut.Should().BeAssignableTo<LinkProvider>(); } [Theory, AutoData] public void SutGetCurrentProvider( SwitchingLinkProvider sut, LinkProvider expected) { using (new Switcher<LinkProvider>(expected)) { sut.CurrentProvider.Should().BeSameAs(expected); } } [Theory, SwitchingAutoData] public void SutUsesDefaultNameIfCurrentProviderSet(SwitchingLinkProvider sut, [Substitute] LinkProvider current) { using (new Switcher<LinkProvider>(current)) { sut.Name.Should().BeNull(); } } [Theory, SwitchingAutoData] public void SutCallsCurrentProviderProperties( SwitchingLinkProvider sut, [Substitute] LinkProvider current) { using (new Switcher<LinkProvider>(current)) { sut.AddAspxExtension.Should().Be(current.AddAspxExtension); sut.AlwaysIncludeServerUrl.Should().Be(current.AlwaysIncludeServerUrl); sut.Description.Should().Be(current.Description); sut.EncodeNames.Should().Be(current.EncodeNames); sut.LanguageEmbedding.Should().Be(current.LanguageEmbedding); sut.LanguageLocation.Should().Be(current.LanguageLocation); sut.LowercaseUrls.Should().Be(current.LowercaseUrls); sut.ShortenUrls.Should().Be(current.ShortenUrls); sut.UseDisplayName.Should().Be(current.UseDisplayName); } } [Theory, SwitchingAutoData] public void SutCallsBaseProviderDefaultPropertiesIfCurrentNorSet( SwitchingLinkProvider sut, string name, NameValueCollection config) { sut.Initialize(name, config); sut.Name.Should().Be(name); sut.AddAspxExtension.Should().BeFalse(); sut.AlwaysIncludeServerUrl.Should().BeFalse(); sut.Description.Should().Be(name); sut.EncodeNames.Should().BeTrue(); sut.LanguageEmbedding.Should().Be(LanguageEmbedding.AsNeeded); sut.LanguageLocation.Should().Be(LanguageLocation.FilePath); sut.LowercaseUrls.Should().BeFalse(); sut.ShortenUrls.Should().BeTrue(); sut.UseDisplayName.Should().BeFalse(); } [Theory, SwitchingAutoData] public void GetDefaultUrlOptionsCallsCurrentProvider( SwitchingLinkProvider sut, [Substitute] LinkProvider current) { using (new Switcher<LinkProvider>(current)) { sut.GetDefaultUrlOptions().Should().BeSameAs(current.GetDefaultUrlOptions()); } } [Theory, SwitchingAutoData] public void GetDefaultUrlOptionsCallsBaseProviderIfCurrentNotSet( SwitchingLinkProvider sut, string name, NameValueCollection config) { sut.Initialize(name, config); sut.GetDefaultUrlOptions().Should().NotBeNull(); } [Theory, SwitchingAutoData] public void GetDynamicUrlCallsCurrentProvider( SwitchingLinkProvider sut, [Substitute] LinkProvider current, Item item, LinkUrlOptions options) { using (new Switcher<LinkProvider>(current)) { sut.GetDynamicUrl(item, options).Should().BeSameAs(current.GetDynamicUrl(item, options)); } } [Theory, SwitchingAutoData] public void GetDynamicUrlCallsCallsBaseProviderIfCurrentNotSet( SwitchingLinkProvider sut, Item item, LinkUrlOptions options) { sut.GetDynamicUrl(item, options).Should().NotBeEmpty(); } [Theory, SwitchingAutoData] public void GetItemUrlCallsCurrentProvider( SwitchingLinkProvider sut, [Substitute] LinkProvider current, Item item, UrlOptions options) { using (new Switcher<LinkProvider>(current)) { sut.GetItemUrl(item, options).Should().BeSameAs(current.GetItemUrl(item, options)); } } [Theory, SwitchingAutoData] [Trait("Category", "RequireLicense")] public void GetItemUrlOptionsCallsBaseProviderIfCurrentNotSet( SwitchingLinkProvider sut, Item item, UrlOptions options) { using (new Db()) { sut.Initialize("name", new NameValueCollection()); sut.GetItemUrl(item, options).Should().NotBeNull(); } } [Theory, SwitchingAutoData] [Trait("Category", "RequireLicense")] public void GetItemUrlWithItemUrlBuilderOptionsCallsBaseProviderIfCurrentNotSet( SwitchingLinkProvider sut, Item item, ItemUrlBuilderOptions options) { using (new Db()) { sut.Initialize("name", new NameValueCollection()); sut.GetItemUrl(item, options).Should().NotBeNull(); } } [Theory, SwitchingAutoData] public void InitializeCallsCurrentProviderIfSet( SwitchingLinkProvider sut, [Substitute] LinkProvider current, string name, NameValueCollection config) { using (new Switcher<LinkProvider>(current)) { sut.Initialize(name, config); current.Received().Initialize(name, config); } } [Theory, SwitchingAutoData] public void InitializeCallsBaseProviderIfCurrentNotSet( SwitchingLinkProvider sut, string name, NameValueCollection config) { sut.Initialize(name, config); } [Theory, SwitchingAutoData] public void IsDynamicLinkCallsCurrentProvider( SwitchingLinkProvider sut, [Substitute] LinkProvider current, string linkText) { using (new Switcher<LinkProvider>(current)) { sut.IsDynamicLink(linkText).Should().Be(current.IsDynamicLink(linkText)); } } [Theory, SwitchingAutoData] public void IsDynamicLinkCallsBaseProviderIfCurrentNotSet(SwitchingLinkProvider sut, string linkText) { sut.IsDynamicLink(linkText).Should().BeFalse(); } [Theory, SwitchingAutoData] public void ParseDynamicLinkCallsCurrentProvider( SwitchingLinkProvider sut, [Substitute] LinkProvider current, ID id) { using (new Switcher<LinkProvider>(current)) { var linkText = "~/link.aspx?_id=" + id; sut.ParseDynamicLink(linkText).Should().Be(current.ParseDynamicLink(linkText)); } } [Theory, SwitchingAutoData] public void ParseDynamicLinkCallsBaseProviderIfCurrentNotSet(SwitchingLinkProvider sut, ID id) { var linkText = "~/link.aspx?_id=" + id; sut.ParseDynamicLink(linkText).Should().NotBeNull(); } [Theory, SwitchingAutoData] public void ParseRequestUrlCallsCurrentProvider( SwitchingLinkProvider sut, [Substitute] LinkProvider current, HttpRequestBase request) { using (new Switcher<LinkProvider>(current)) { sut.ParseRequestUrl(request).Should().Be(current.ParseRequestUrl(request)); } } [Theory, SwitchingAutoData] public void ParseRequestUrlCallsBaseProviderIfCurrentNotSet( SwitchingLinkProvider sut, HttpRequestBase request) { sut.ParseRequestUrl(request).Should().NotBeNull(); } [Theory, SwitchingAutoData] public void ResolveTargetSiteCallsCurrentProvider( SwitchingLinkProvider sut, [Substitute] LinkProvider current, Item item) { using (new Switcher<LinkProvider>(current)) { sut.ResolveTargetSite(item).Should().Be(current.ResolveTargetSite(item)); } } [Theory, SwitchingAutoData] public void ResolveTargetSiteCallsBaseProviderIfCurrentNotSet( SwitchingLinkProvider sut, Item item) { sut.ResolveTargetSite(item); } [Theory, SwitchingAutoData] public void ExpandDynamicLinksCallsCurrentProvider( SwitchingLinkProvider sut, [Substitute] LinkProvider current, string text, bool resolveSite) { using (new Switcher<LinkProvider>(current)) { sut.ExpandDynamicLinks(text, resolveSite).Should().Be(current.ExpandDynamicLinks(text, resolveSite)); } } [Theory, SwitchingAutoData] public void ExpandDynamicLinksCallsBaseProviderIfCurrentNotSet( SwitchingLinkProvider sut, string name, NameValueCollection config, string text, bool resolveSites) { sut.Initialize(name, config); sut.ExpandDynamicLinks(text, resolveSites); } private class SwitchingAutoDataAttribute : DefaultAutoDataAttribute { public SwitchingAutoDataAttribute() { this.Fixture.Customize(new AutoNSubstituteCustomization()) .Customize(new AutoConfiguredNSubstituteCustomization()); this.Fixture.Register(() => LanguageEmbedding.Never); this.Fixture.Register(() => LanguageLocation.QueryString); this.Fixture.Register(() => new HttpRequest("default.aspx", "http://google.com", null)); this.Fixture.Register(() => new SiteInfo(new StringDictionary())); this.Fixture.Customize<UrlOptions>(x => x.OmitAutoProperties()); } } } }
/** * Copyright (c) 2015, GruntTheDivine 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 copyright holder 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.Linq; using System.Collections; using System.Collections.Generic; using Iodine.Util; namespace Iodine.Runtime { public class IodineDictionary : IodineObject { public static readonly IodineTypeDefinition TypeDefinition = new MapTypeDef (); sealed class MapTypeDef : IodineTypeDefinition { public MapTypeDef () : base ("Dict") { BindAttributes (this); SetDocumentation ( "A dictionary containing a list of unique keys and an associated value", "@optional values An iterable collection of tuples to initialize the dictionary with" ); } public override IodineObject BindAttributes (IodineObject obj) { obj.SetAttribute ("contains", new BuiltinMethodCallback (Contains, obj)); obj.SetAttribute ("getSize", new BuiltinMethodCallback (GetSize, obj)); obj.SetAttribute ("clear", new BuiltinMethodCallback (Clear, obj)); obj.SetAttribute ("set", new BuiltinMethodCallback (Set, obj)); obj.SetAttribute ("get", new BuiltinMethodCallback (Get, obj)); obj.SetAttribute ("remove", new BuiltinMethodCallback (Remove, obj)); return obj; } public override IodineObject Invoke (VirtualMachine vm, IodineObject[] args) { if (args.Length >= 1) { var inputList = args [0] as IodineList; var ret = new IodineDictionary (); if (inputList != null) { foreach (IodineObject item in inputList.Objects) { IodineTuple kv = item as IodineTuple; if (kv != null) { ret.Set (kv.Objects [0], kv.Objects [1]); } } } return ret; } return new IodineDictionary (); } [BuiltinDocString ( "Tests to see if the dictionary contains a key, returning true if it does.", "@param key The key to test if this dictionary contains." )] IodineObject Contains (VirtualMachine vm, IodineObject self, IodineObject [] args) { var thisObj = self as IodineDictionary; if (args.Length <= 0) { vm.RaiseException (new IodineArgumentException (1)); return null; } return IodineBool.Create (thisObj.dict.ContainsKey (args [0])); } IodineObject GetSize (VirtualMachine vm, IodineObject self, IodineObject [] arguments) { var thisObj = self as IodineDictionary; return new IodineInteger (thisObj.dict.Count); } [BuiltinDocString ( "Clears the dictionary, removing all items." )] IodineObject Clear (VirtualMachine vm, IodineObject self, IodineObject [] arguments) { var thisObj = self as IodineDictionary; thisObj.dict.Clear (); return null; } [BuiltinDocString ( "Sets a key to a specified value, if the key does not exist, it will be created.", "@param key The key of the specified value", "@param value The value associated with [key]" )] IodineObject Set (VirtualMachine vm, IodineObject self, IodineObject [] arguments) { var thisObj = self as IodineDictionary; if (arguments.Length >= 2) { IodineObject key = arguments [0]; IodineObject val = arguments [1]; thisObj.dict [key] = val; return null; } vm.RaiseException (new IodineArgumentException (2)); return null; } [BuiltinDocString ( "Returns the value specified by [key], raising a KeyNotFound exception if the given key does not exist.", "@param key The key whose value will be returned." )] IodineObject Get (VirtualMachine vm, IodineObject self, IodineObject [] arguments) { var thisObj = self as IodineDictionary; if (arguments.Length <= 0) { vm.RaiseException (new IodineArgumentException (1)); return null; } else if (arguments.Length == 1) { IodineObject key = arguments [0]; if (thisObj.dict.ContainsKey (key)) { return thisObj.dict [key] as IodineObject; } vm.RaiseException (new IodineKeyNotFound ()); return null; } else { IodineObject key = arguments [0]; if (thisObj.dict.ContainsKey (key)) { return thisObj.dict [key] as IodineObject; } return arguments [1]; } } [BuiltinDocString ( "Removes a specified entry from the dictionary, raising a KeyNotFound exception if the given key does not exist.", "@param key The key which is to be removed." )] IodineObject Remove (VirtualMachine vm, IodineObject self, IodineObject [] arguments) { var thisObj = self as IodineDictionary; if (arguments.Length >= 1) { IodineObject key = arguments [0]; if (!thisObj.dict.ContainsKey (key)) { vm.RaiseException (new IodineKeyNotFound ()); return null; } thisObj.dict.Remove (key); return null; } vm.RaiseException (new IodineArgumentException (2)); return null; } } class DictIterator : IodineObject { static IodineTypeDefinition TypeDefinition = new IodineTypeDefinition ("DictIterator"); IDictionaryEnumerator enumerator; public DictIterator (ObjectDictionary dict) : base (TypeDefinition) { enumerator = dict.GetEnumerator (); } public override IodineObject IterGetCurrent (VirtualMachine vm) { return new IodineTuple (new IodineObject [] { enumerator.Key as IodineObject, enumerator.Value as IodineObject }); } public override bool IterMoveNext (VirtualMachine vm) { return enumerator.MoveNext (); } public override void IterReset (VirtualMachine vm) { enumerator.Reset (); } } ObjectDictionary dict; public IEnumerable<IodineObject> Keys { get { return dict.Keys.Cast<IodineObject> (); } } public IodineDictionary () : this (new ObjectDictionary ()) { } public IodineDictionary (ObjectDictionary dict) : base (TypeDefinition) { this.dict = dict; SetAttribute ("__iter__", new BuiltinMethodCallback ((VirtualMachine vm, IodineObject self, IodineObject [] args) => { return GetIterator (vm); }, this)); } public IodineDictionary (AttributeDictionary dict) : this () { foreach (KeyValuePair<string, IodineObject> kv in dict) { this.dict [new IodineString (kv.Key)] = kv.Value; } } public override IodineObject Len (VirtualMachine vm) { return new IodineInteger (dict.Count); } public override IodineObject GetIndex (VirtualMachine vm, IodineObject key) { if (!dict.ContainsKey (key)) { vm.RaiseException (new IodineKeyNotFound ()); return null; } return dict [key] as IodineObject; } public override void SetIndex (VirtualMachine vm, IodineObject key, IodineObject value) { dict [key] = value; } public override bool Equals (IodineObject obj) { var map = obj as IodineDictionary; if (map != null) { if (map.dict.Count != this.dict.Count) { return false; } foreach (IodineObject key in map.Keys) { if (!map.ContainsKey (key)) { return false; } var dictKey = map.Get (key) as IodineObject; if (!dictKey.Equals ((IodineObject)dict [key])) { return false; } } return true; } return false; } public override IodineObject Equals (VirtualMachine vm, IodineObject right) { var hash = right as IodineDictionary; if (hash == null) { vm.RaiseException (new IodineTypeException ("HashMap")); return null; } return IodineBool.Create (Equals (hash)); } public override int GetHashCode () { return dict.GetHashCode (); } public override IodineObject GetIterator (VirtualMachine vm) { return new DictIterator (dict); } /// <summary> /// Set the specified key and valuw. /// </summary> /// <param name="key">Key.</param> /// <param name="val">Value.</param> public void Set (IodineObject key, IodineObject val) { dict [key] = val; } /// <summary> /// Get the specified key. /// </summary> /// <param name="key">Key.</param> public IodineObject Get (IodineObject key) { return dict [key] as IodineObject; } /// <summary> /// Determines whether or not this dictionary contains the specific key /// </summary> /// <returns><c>true</c>, if key was containsed, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> public bool ContainsKey (IodineObject key) { return dict.ContainsKey (key); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Reflection; using System.Threading; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Security; using System.Linq; #if USE_REFEMIT || NET_NATIVE public sealed class ClassDataContract : DataContract #else internal sealed class ClassDataContract : DataContract #endif { /// <SecurityNote> /// Review - XmlDictionaryString(s) representing the XML namespaces for class members. /// statically cached and used from IL generated code. should ideally be Critical. /// marked SecurityRequiresReview to be callable from transparent IL generated code. /// not changed to property to avoid regressing performance; any changes to initalization should be reviewed. /// </SecurityNote> public XmlDictionaryString[] ContractNamespaces; /// <SecurityNote> /// Review - XmlDictionaryString(s) representing the XML element names for class members. /// statically cached and used from IL generated code. should ideally be Critical. /// marked SecurityRequiresReview to be callable from transparent IL generated code. /// not changed to property to avoid regressing performance; any changes to initalization should be reviewed. /// </SecurityNote> public XmlDictionaryString[] MemberNames; /// <SecurityNote> /// Review - XmlDictionaryString(s) representing the XML namespaces for class members. /// statically cached and used when calling IL generated code. should ideally be Critical. /// marked SecurityRequiresReview to be callable from transparent code. /// not changed to property to avoid regressing performance; any changes to initalization should be reviewed. /// </SecurityNote> public XmlDictionaryString[] MemberNamespaces; [SecurityCritical] /// <SecurityNote> /// Critical - XmlDictionaryString representing the XML namespaces for members of class. /// statically cached and used from IL generated code. /// </SecurityNote> private XmlDictionaryString[] _childElementNamespaces; [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization. /// Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> private ClassDataContractCriticalHelper _helper; private bool _isScriptObject; #if NET_NATIVE public ClassDataContract() : base(new ClassDataContractCriticalHelper()) { InitClassDataContract(); } #endif /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type)) { InitClassDataContract(); } [SecuritySafeCritical] /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames)) { InitClassDataContract(); } [SecurityCritical] /// <SecurityNote> /// Critical - initializes SecurityCritical fields; called from all constructors /// </SecurityNote> private void InitClassDataContract() { _helper = base.Helper as ClassDataContractCriticalHelper; this.ContractNamespaces = _helper.ContractNamespaces; this.MemberNames = _helper.MemberNames; this.MemberNamespaces = _helper.MemberNamespaces; _isScriptObject = _helper.IsScriptObject; } internal ClassDataContract BaseContract { /// <SecurityNote> /// Critical - fetches the critical baseContract property /// Safe - baseContract only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.BaseContract; } } internal List<DataMember> Members { /// <SecurityNote> /// Critical - fetches the critical members property /// Safe - members only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.Members; } } public XmlDictionaryString[] ChildElementNamespaces { /// <SecurityNote> /// Critical - fetches the critical childElementNamespaces property /// Safe - childElementNamespaces only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { if (_childElementNamespaces == null) { lock (this) { if (_childElementNamespaces == null) { if (_helper.ChildElementNamespaces == null) { XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces(); Interlocked.MemoryBarrier(); _helper.ChildElementNamespaces = tempChildElementamespaces; } _childElementNamespaces = _helper.ChildElementNamespaces; } } } return _childElementNamespaces; } #if NET_NATIVE set { _childElementNamespaces = value; } #endif } internal MethodInfo OnSerializing { /// <SecurityNote> /// Critical - fetches the critical onSerializing property /// Safe - onSerializing only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.OnSerializing; } } internal MethodInfo OnSerialized { /// <SecurityNote> /// Critical - fetches the critical onSerialized property /// Safe - onSerialized only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.OnSerialized; } } internal MethodInfo OnDeserializing { /// <SecurityNote> /// Critical - fetches the critical onDeserializing property /// Safe - onDeserializing only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.OnDeserializing; } } internal MethodInfo OnDeserialized { /// <SecurityNote> /// Critical - fetches the critical onDeserialized property /// Safe - onDeserialized only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.OnDeserialized; } } #if !NET_NATIVE public override DataContractDictionary KnownDataContracts { /// <SecurityNote> /// Critical - fetches the critical knownDataContracts property /// Safe - knownDataContracts only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.KnownDataContracts; } } #endif internal bool IsNonAttributedType { /// <SecurityNote> /// Critical - fetches the critical IsNonAttributedType property /// Safe - IsNonAttributedType only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.IsNonAttributedType; } } #if NET_NATIVE public bool HasDataContract { [SecuritySafeCritical] get { return _helper.HasDataContract; } set { _helper.HasDataContract = value; } } public bool HasExtensionData { [SecuritySafeCritical] get { return _helper.HasExtensionData; } set { _helper.HasExtensionData = value; } } #endif internal bool IsKeyValuePairAdapter { [SecuritySafeCritical] get { return _helper.IsKeyValuePairAdapter; } } internal Type[] KeyValuePairGenericArguments { [SecuritySafeCritical] get { return _helper.KeyValuePairGenericArguments; } } internal ConstructorInfo KeyValuePairAdapterConstructorInfo { [SecuritySafeCritical] get { return _helper.KeyValuePairAdapterConstructorInfo; } } internal MethodInfo GetKeyValuePairMethodInfo { [SecuritySafeCritical] get { return _helper.GetKeyValuePairMethodInfo; } } /// <SecurityNote> /// Critical - fetches information about which constructor should be used to initialize non-attributed types that are valid for serialization /// Safe - only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] internal ConstructorInfo GetNonAttributedTypeConstructor() { return _helper.GetNonAttributedTypeConstructor(); } #if !NET_NATIVE internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { /// <SecurityNote> /// Critical - fetches the critical xmlFormatWriterDelegate property /// Safe - xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { if (_helper.XmlFormatWriterDelegate == null) { lock (this) { if (_helper.XmlFormatWriterDelegate == null) { XmlFormatClassWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateClassWriter(this); Interlocked.MemoryBarrier(); _helper.XmlFormatWriterDelegate = tempDelegate; } } } return _helper.XmlFormatWriterDelegate; } } #else public XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get; set; } #endif #if !NET_NATIVE internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { /// <SecurityNote> /// Critical - fetches the critical xmlFormatReaderDelegate property /// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { if (_helper.XmlFormatReaderDelegate == null) { lock (this) { if (_helper.XmlFormatReaderDelegate == null) { XmlFormatClassReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateClassReader(this); Interlocked.MemoryBarrier(); _helper.XmlFormatReaderDelegate = tempDelegate; } } } return _helper.XmlFormatReaderDelegate; } } #else public XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get; set; } #endif internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames) { #if !NET_NATIVE return new ClassDataContract(type, ns, memberNames); #else return (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type); #endif } internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable) { DataMember existingMemberContract; if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract)) { Type declaringType = memberContract.MemberInfo.DeclaringType; DataContract.ThrowInvalidDataContractException( SR.Format((declaringType.GetTypeInfo().IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName), existingMemberContract.MemberInfo.Name, memberContract.MemberInfo.Name, DataContract.GetClrTypeFullName(declaringType), memberContract.Name), declaringType); } memberNamesTable.Add(memberContract.Name, memberContract); members.Add(memberContract); } internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary) { childType = DataContract.UnwrapNullableType(childType); if (!childType.GetTypeInfo().IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType) && DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull) { string ns = DataContract.GetStableName(childType).Namespace; if (ns.Length > 0 && ns != dataContract.Namespace.Value) return dictionary.Add(ns); } return null; } private static bool IsArraySegment(Type t) { return t.GetTypeInfo().IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } /// <SecurityNote> /// RequiresReview - callers may need to depend on isNonAttributedType for a security decision /// isNonAttributedType must be calculated correctly /// IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and /// is therefore marked SRR /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value /// </SecurityNote> static internal bool IsNonAttributedTypeValidForSerialization(Type type) { if (type.IsArray) return false; if (type.GetTypeInfo().IsEnum) return false; if (type.IsGenericParameter) return false; if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) return false; if (type.IsPointer) return false; if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) return false; Type[] interfaceTypes = type.GetInterfaces(); if (!IsArraySegment(type)) { foreach (Type interfaceType in interfaceTypes) { if (CollectionDataContract.IsCollectionInterface(interfaceType)) return false; } } if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false)) return false; if (type.GetTypeInfo().IsValueType) { return type.GetTypeInfo().IsVisible; } else { return (type.GetTypeInfo().IsVisible && type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()) != null); } } private static string[] s_knownSerializableTypeNames = new string[] { "System.Collections.Queue", "System.Collections.Stack", "System.Globalization.CultureInfo", "System.Version", "System.Collections.Generic.KeyValuePair`2", "System.Collections.Generic.Queue`1", "System.Collections.Generic.Stack`1", "System.Collections.ObjectModel.ReadOnlyCollection`1", "System.Collections.ObjectModel.ReadOnlyDictionary`2", "System.Tuple`1", "System.Tuple`2", "System.Tuple`3", "System.Tuple`4", "System.Tuple`5", "System.Tuple`6", "System.Tuple`7", "System.Tuple`8", }; internal static bool IsKnownSerializableType(Type type) { // Applies to known types that DCS understands how to serialize/deserialize // // Ajdust for generic type if (type.GetTypeInfo().IsGenericType && !type.GetTypeInfo().IsGenericTypeDefinition) { type = type.GetGenericTypeDefinition(); } // Check for known types if (Enumerable.Contains(s_knownSerializableTypeNames, type.FullName)) { return true; } //Enable ClassDataContract to give support to Exceptions. if (Globals.TypeOfException.IsAssignableFrom(type)) return true; return false; } private XmlDictionaryString[] CreateChildElementNamespaces() { if (Members == null) return null; XmlDictionaryString[] baseChildElementNamespaces = null; if (this.BaseContract != null) baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces; int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0; XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount]; if (baseChildElementNamespaceCount > 0) Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length); XmlDictionary dictionary = new XmlDictionary(); for (int i = 0; i < this.Members.Count; i++) { childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary); } return childElementNamespaces; } [SecuritySafeCritical] /// <SecurityNote> /// Critical - calls critical method on helper /// Safe - doesn't leak anything /// </SecurityNote> private void EnsureMethodsImported() { _helper.EnsureMethodsImported(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } xmlReader.Read(); object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces); xmlReader.ReadEndElement(); return o; } /// <SecurityNote> /// Review - calculates whether this class requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForRead(SecurityException securityException, string[] serializationAssemblyPatterns) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType, serializationAssemblyPatterns)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException, serializationAssemblyPatterns)) return true; if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor(), serializationAssemblyPatterns)) { if (Globals.TypeOfScriptObject_IsAssignableFrom(UnderlyingType)) { return true; } if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserializing, serializationAssemblyPatterns)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializingNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserialized, serializationAssemblyPatterns)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForSet(serializationAssemblyPatterns)) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractFieldSetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractPropertySetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } /// <SecurityNote> /// Review - calculates whether this class requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForWrite(SecurityException securityException, string[] serializationAssemblyPatterns) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType, serializationAssemblyPatterns)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException, serializationAssemblyPatterns)) return true; if (MethodRequiresMemberAccess(this.OnSerializing, serializationAssemblyPatterns)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializingNotPublic, DataContract.GetClrTypeFullName(this.UnderlyingType), this.OnSerializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnSerialized, serializationAssemblyPatterns)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnSerialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForGet(serializationAssemblyPatterns)) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractFieldGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractPropertyGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } [SecurityCritical] /// <SecurityNote> /// Critical - holds all state used for (de)serializing classes. /// since the data is cached statically, we lock down access to it. /// </SecurityNote> private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private ClassDataContract _baseContract; private List<DataMember> _members; private MethodInfo _onSerializing, _onSerialized; private MethodInfo _onDeserializing, _onDeserialized; #if !NET_NATIVE private DataContractDictionary _knownDataContracts; private bool _isKnownTypeAttributeChecked; #endif private bool _isMethodChecked; /// <SecurityNote> /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract /// </SecurityNote> private bool _isNonAttributedType; /// <SecurityNote> /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType /// </SecurityNote> private bool _hasDataContract; #if NET_NATIVE private bool _hasExtensionData; #endif private bool _isScriptObject; private XmlDictionaryString[] _childElementNamespaces; private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate; private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate; public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; internal ClassDataContractCriticalHelper() : base() { } internal ClassDataContractCriticalHelper(Type type) : base(type) { XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type); if (type == Globals.TypeOfDBNull) { this.StableName = stableName; _members = new List<DataMember>(); XmlDictionary dictionary = new XmlDictionary(2); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = Array.Empty<XmlDictionaryString>(); EnsureMethodsImported(); return; } Type baseType = type.GetTypeInfo().BaseType; SetIsNonAttributedType(type); SetKeyValuePairAdapterFlags(type); this.IsValueType = type.GetTypeInfo().IsValueType; if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) { DataContract baseContract = DataContract.GetDataContract(baseType); if (baseContract is CollectionDataContract) this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract; else this.BaseContract = baseContract as ClassDataContract; if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError (new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes, DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType)))); } } else this.BaseContract = null; { this.StableName = stableName; ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(2 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = dictionary.Add(StableName.Namespace); int baseMemberCount = 0; int baseContractCount = 0; if (BaseContract == null) { MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; ContractNamespaces = new XmlDictionaryString[1]; } else { baseMemberCount = BaseContract.MemberNames.Length; MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNames, MemberNames, baseMemberCount); MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNamespaces, MemberNamespaces, baseMemberCount); baseContractCount = BaseContract.ContractNamespaces.Length; ContractNamespaces = new XmlDictionaryString[1 + baseContractCount]; Array.Copy(BaseContract.ContractNamespaces, ContractNamespaces, baseContractCount); } ContractNamespaces[baseContractCount] = Namespace; for (int i = 0; i < Members.Count; i++) { MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name); MemberNamespaces[i + baseMemberCount] = Namespace; } } EnsureMethodsImported(); _isScriptObject = this.IsNonAttributedType && Globals.TypeOfScriptObject_IsAssignableFrom(this.UnderlyingType); } internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type) { this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value); ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(1 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = ns; ContractNamespaces = new XmlDictionaryString[] { Namespace }; MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) { Members[i].Name = memberNames[i]; MemberNames[i] = dictionary.Add(Members[i].Name); MemberNamespaces[i] = Namespace; } EnsureMethodsImported(); } private void EnsureIsReferenceImported(Type type) { DataContractAttribute dataContractAttribute; bool isReference = false; bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute); if (BaseContract != null) { if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly) { bool baseIsReference = this.BaseContract.IsReference; if ((baseIsReference && !dataContractAttribute.IsReference) || (!baseIsReference && dataContractAttribute.IsReference)) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.InconsistentIsReference, DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType), this.BaseContract.IsReference), type); } else { isReference = dataContractAttribute.IsReference; } } else { isReference = this.BaseContract.IsReference; } } else if (hasDataContractAttribute) { if (dataContractAttribute.IsReference) isReference = dataContractAttribute.IsReference; } if (isReference && type.GetTypeInfo().IsValueType) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.ValueTypeCannotHaveIsReference, DataContract.GetClrTypeFullName(type), true, false), type); return; } this.IsReference = isReference; } private void ImportDataMembers() { Type type = this.UnderlyingType; EnsureIsReferenceImported(type); List<DataMember> tempMembers = new List<DataMember>(); Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>(); MemberInfo[] memberInfos; bool isPodSerializable = !_isNonAttributedType || IsKnownSerializableType(type); if (!isPodSerializable) { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); } else { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } for (int i = 0; i < memberInfos.Length; i++) { MemberInfo member = memberInfos[i]; if (HasDataContract) { object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); DataMember memberContract = new DataMember(member); if (member is PropertyInfo) { PropertyInfo property = (PropertyInfo)member; MethodInfo getMethod = property.GetMethod; if (getMethod != null && IsMethodOverriding(getMethod)) continue; MethodInfo setMethod = property.SetMethod; if (setMethod != null && IsMethodOverriding(setMethod)) continue; if (getMethod == null) ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name)); if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) { ThrowInvalidDataContractException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property.Name)); } } if (getMethod.GetParameters().Length > 0) ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name)); } else if (!(member is FieldInfo)) ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name)); DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; if (memberAttribute.IsNameSetExplicitly) { if (memberAttribute.Name == null || memberAttribute.Name.Length == 0) ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Name; } else memberContract.Name = member.Name; memberContract.Name = DataContract.EncodeLocalName(memberContract.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); memberContract.IsRequired = memberAttribute.IsRequired; if (memberAttribute.IsRequired && this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue; memberContract.Order = memberAttribute.Order; CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } else if (!isPodSerializable) { FieldInfo field = member as FieldInfo; PropertyInfo property = member as PropertyInfo; if ((field == null && property == null) || (field != null && field.IsInitOnly)) continue; object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); else continue; } DataMember memberContract = new DataMember(member); if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0) continue; MethodInfo setMethod = property.SetMethod; if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) continue; } else { if (!setMethod.IsPublic || IsMethodOverriding(setMethod)) continue; } } memberContract.Name = DataContract.EncodeLocalName(member.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } else { // [Serializible] and [NonSerialized] are deprecated on FxCore // Try to mimic the behavior by allowing certain known types to go through // POD types are fine also FieldInfo field = member as FieldInfo; if (CanSerializeMember(field)) { DataMember memberContract = new DataMember(member); memberContract.Name = DataContract.EncodeLocalName(member.Name); object[] optionalFields = null; if (optionalFields == null || optionalFields.Length == 0) { if (this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.IsRequired = true; } memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } } if (tempMembers.Count > 1) tempMembers.Sort(DataMemberComparer.Singleton); SetIfMembersHaveConflict(tempMembers); Interlocked.MemoryBarrier(); _members = tempMembers; } private static bool CanSerializeMember(FieldInfo field) { return field != null; } private bool SetIfGetOnlyCollection(DataMember memberContract) { //OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.GetTypeInfo().IsValueType) { memberContract.IsGetOnlyCollection = true; return true; } return false; } private void SetIfMembersHaveConflict(List<DataMember> members) { if (BaseContract == null) return; int baseTypeIndex = 0; List<Member> membersInHierarchy = new List<Member>(); foreach (DataMember member in members) { membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex)); } ClassDataContract currContract = BaseContract; while (currContract != null) { baseTypeIndex++; foreach (DataMember member in currContract.Members) { membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex)); } currContract = currContract.BaseContract; } IComparer<Member> comparer = DataMemberConflictComparer.Singleton; membersInHierarchy.Sort(comparer); for (int i = 0; i < membersInHierarchy.Count - 1; i++) { int startIndex = i; int endIndex = i; bool hasConflictingType = false; while (endIndex < membersInHierarchy.Count - 1 && String.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0 && String.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0) { membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member; if (!hasConflictingType) { if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType) { hasConflictingType = true; } else { hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType); } } endIndex++; } if (hasConflictingType) { for (int j = startIndex; j <= endIndex; j++) { membersInHierarchy[j].member.HasConflictingNameAndType = true; } } i = endIndex + 1; } } /// <SecurityNote> /// Critical - sets the critical hasDataContract field /// Safe - uses a trusted critical API (DataContract.GetStableName) to calculate the value /// does not accept the value from the caller /// </SecurityNote> //CSD16748 //[SecuritySafeCritical] private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type) { return DataContract.GetStableName(type, out _hasDataContract); } /// <SecurityNote> /// RequiresReview - marked SRR because callers may need to depend on isNonAttributedType for a security decision /// isNonAttributedType must be calculated correctly /// SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it /// is dependent on the correct calculation of hasDataContract /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value /// </SecurityNote> private void SetIsNonAttributedType(Type type) { _isNonAttributedType = !_hasDataContract && IsNonAttributedTypeValidForSerialization(type); } private static bool IsMethodOverriding(MethodInfo method) { return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0); } internal void EnsureMethodsImported() { if (!_isMethodChecked && UnderlyingType != null) { lock (this) { if (!_isMethodChecked) { Type type = this.UnderlyingType; MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; Type prevAttributeType = null; ParameterInfo[] parameters = method.GetParameters(); //THese attributes are cut from mscorlib. if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, _onSerializing, ref prevAttributeType)) _onSerializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, _onSerialized, ref prevAttributeType)) _onSerialized = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, _onDeserializing, ref prevAttributeType)) _onDeserializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, _onDeserialized, ref prevAttributeType)) _onDeserialized = method; } Interlocked.MemoryBarrier(); _isMethodChecked = true; } } } } private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) { if (method.IsDefined(attributeType, false)) { if (currentCallback != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else if (prevAttributeType != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); else if (method.IsVirtual) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else { if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType); prevAttributeType = attributeType; } return true; } return false; } internal ClassDataContract BaseContract { get { return _baseContract; } set { _baseContract = value; if (_baseContract != null && IsValueType) ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace)); } } internal List<DataMember> Members { get { return _members; } } internal MethodInfo OnSerializing { get { EnsureMethodsImported(); return _onSerializing; } } internal MethodInfo OnSerialized { get { EnsureMethodsImported(); return _onSerialized; } } internal MethodInfo OnDeserializing { get { EnsureMethodsImported(); return _onDeserializing; } } internal MethodInfo OnDeserialized { get { EnsureMethodsImported(); return _onDeserialized; } } #if !NET_NATIVE internal override DataContractDictionary KnownDataContracts { [SecurityCritical] get { if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } [SecurityCritical] set { _knownDataContracts = value; } } #endif internal bool HasDataContract { get { return _hasDataContract; } #if NET_NATIVE set { _hasDataContract = value; } #endif } #if NET_NATIVE internal bool HasExtensionData { get { return _hasExtensionData; } set { _hasExtensionData = value; } } #endif internal bool IsNonAttributedType { get { return _isNonAttributedType; } } private void SetKeyValuePairAdapterFlags(Type type) { if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { _isKeyValuePairAdapter = true; _keyValuePairGenericArguments = type.GetGenericArguments(); _keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) }); _getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers); } } private bool _isKeyValuePairAdapter; private Type[] _keyValuePairGenericArguments; private ConstructorInfo _keyValuePairCtorInfo; private MethodInfo _getKeyValuePairMethodInfo; internal bool IsKeyValuePairAdapter { get { return _isKeyValuePairAdapter; } } internal bool IsScriptObject { get { return _isScriptObject; } } internal Type[] KeyValuePairGenericArguments { get { return _keyValuePairGenericArguments; } } internal ConstructorInfo KeyValuePairAdapterConstructorInfo { get { return _keyValuePairCtorInfo; } } internal MethodInfo GetKeyValuePairMethodInfo { get { return _getKeyValuePairMethodInfo; } } internal ConstructorInfo GetNonAttributedTypeConstructor() { if (!this.IsNonAttributedType) return null; Type type = UnderlyingType; if (type.GetTypeInfo().IsValueType) return null; ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } public XmlDictionaryString[] ChildElementNamespaces { get { return _childElementNamespaces; } set { _childElementNamespaces = value; } } internal struct Member { internal Member(DataMember member, string ns, int baseTypeIndex) { this.member = member; this.ns = ns; this.baseTypeIndex = baseTypeIndex; } internal DataMember member; internal string ns; internal int baseTypeIndex; } internal class DataMemberConflictComparer : IComparer<Member> { [SecuritySafeCritical] public int Compare(Member x, Member y) { int nsCompare = String.CompareOrdinal(x.ns, y.ns); if (nsCompare != 0) return nsCompare; int nameCompare = String.CompareOrdinal(x.member.Name, y.member.Name); if (nameCompare != 0) return nameCompare; return x.baseTypeIndex - y.baseTypeIndex; } internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer(); } } internal class DataMemberComparer : IComparer<DataMember> { public int Compare(DataMember x, DataMember y) { int orderCompare = x.Order - y.Order; if (orderCompare != 0) return orderCompare; return String.CompareOrdinal(x.Name, y.Name); } internal static DataMemberComparer Singleton = new DataMemberComparer(); } #if !NET_NATIVE && MERGE_DCJS /// <summary> /// Get object type for Xml/JsonFormmatReaderGenerator /// </summary> internal Type ObjectType { get { Type type = UnderlyingType; if (type.GetTypeInfo().IsValueType && !IsNonAttributedType) { type = Globals.TypeOfValueType; } return type; } } #endif } }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using Htc.Vita.Core.Interop; namespace Htc.Vita.Core.Util { public static partial class Win32Registry { /// <summary> /// Class Key. /// Implements the <see cref="IDisposable" /> /// </summary> /// <seealso cref="IDisposable" /> public class Key : IDisposable { private const int MaxKeyLength = 255; private const int MaxValueNameLength = 16383; private static readonly Dictionary<Hive, string> RegistryHiveWithName = new Dictionary<Hive, string> { { Hive.ClassesRoot, "HKEY_CLASSES_ROOT" }, { Hive.CurrentUser, "HKEY_CURRENT_USER" }, { Hive.LocalMachine, "HKEY_LOCAL_MACHINE" }, { Hive.Users, "HKEY_USERS" }, { Hive.PerformanceData, "HKEY_PERFORMANCE_DATA" }, { Hive.CurrentConfig, "HKEY_CURRENT_CONFIG" } }; private readonly KeyStateFlag _keyStateFlag; private readonly View _view; private volatile Windows.SafeRegistryHandle _handle; private volatile string _name; private volatile KeyPermissionCheck _keyPermissionCheck; /// <summary> /// Gets the subkey count. /// </summary> /// <value>The subkey count.</value> /// <exception cref="ObjectDisposedException">Cannot access a closed registry key.</exception> public int SubKeyCount { get { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } return DoGetSubKeyCount(); } } /// <summary> /// Gets the value count. /// </summary> /// <value>The value count.</value> /// <exception cref="ObjectDisposedException">Cannot access a closed registry key.</exception> public int ValueCount { get { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } return DoGetValueCount(); } } private Key( Windows.SafeRegistryHandle registryHandle, View view, bool isWritable, bool isSystemKey) { _handle = registryHandle; _name = ""; _view = view; if (isSystemKey) { _keyStateFlag |= KeyStateFlag.SystemKey; } if (isWritable) { _keyStateFlag |= KeyStateFlag.WriteAccess; } } /// <summary> /// Creates the subkey. /// </summary> /// <param name="subKeyName">The subkey name.</param> /// <returns>Key.</returns> public Key CreateSubKey(string subKeyName) { return CreateSubKey( subKeyName, _keyPermissionCheck ); } /// <summary> /// Creates the subkey. /// </summary> /// <param name="subKeyName">The subkey name.</param> /// <param name="keyPermissionCheck">The key permission check.</param> /// <returns>Key.</returns> public Key CreateSubKey( string subKeyName, KeyPermissionCheck keyPermissionCheck) { return DoOpenSubKey( subKeyName, keyPermissionCheck, keyPermissionCheck != KeyPermissionCheck.ReadSubTree, false ) ?? DoCreateSubKey( subKeyName, keyPermissionCheck ); } /// <summary> /// Deletes the subkey tree. /// </summary> /// <param name="subKeyName">The subkey name.</param> /// <param name="throwOnMissingSubKey">If set to <c>true</c>, throw on missing subkey.</param> /// <exception cref="ArgumentException">Cannot delete a registry hive's subtree.</exception> /// <exception cref="ArgumentException">Cannot delete a subkey tree because the subkey does not exist.</exception> /// <exception cref="ObjectDisposedException">Cannot access a closed registry key.</exception> /// <exception cref="UnauthorizedAccessException">Cannot write to the registry key.</exception> /// <exception cref="ArgumentException">Cannot delete a registry hive's subtree.</exception> public void DeleteSubKeyTree( string subKeyName, bool throwOnMissingSubKey) { if (subKeyName.Length == 0 && IsSystemKey()) { throw new ArgumentException("Cannot delete a registry hive's subtree."); } if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } if (!IsWritable()) { throw new UnauthorizedAccessException("Cannot write to the registry key."); } var subKey = DoOpenSubKey( subKeyName, KeyPermissionCheck.ReadWriteSubTree, true, false ); if (subKey != null) { using (subKey) { var subSubKeyNames = subKey.GetSubKeyNames(); foreach (var subSubKeyName in subSubKeyNames) { subKey.DoDeleteSubKeyTree(subSubKeyName); } } DoDeleteSubKey(subKeyName); } else if (throwOnMissingSubKey) { throw new ArgumentException("Cannot delete a subkey tree because the subkey does not exist."); } } /// <summary> /// Deletes the value. /// </summary> /// <param name="valueName">The value name.</param> /// <param name="throwOnMissingValue">Tf set to <c>true</c>, throw on missing value.</param> public void DeleteValue( string valueName, bool throwOnMissingValue) { DoDeleteValue( valueName, throwOnMissingValue ); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (_handle != null && !IsSystemKey()) { try { _handle.Dispose(); } catch (IOException) { // skip } finally { _handle = null; } } } private Key DoCreateSubKey( string subKeyName, KeyPermissionCheck keyPermissionCheck) { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } var normalizedSubKeyName = NormalizeSubKeyName(subKeyName); var securityAttributes = new Windows.SecurityAttributes(); securityAttributes.nLength = Marshal.SizeOf(securityAttributes); int disposition; Windows.SafeRegistryHandle handle; var errorCode = Windows.RegCreateKeyExW( _handle, normalizedSubKeyName, IntPtr.Zero, null, 0, ToRegistryKeyAccessRight(keyPermissionCheck != KeyPermissionCheck.ReadSubTree) | ToRegistryKeyAccessRight(_view), securityAttributes, out handle, out disposition ); if (errorCode == Windows.Error.Success && !handle.IsInvalid) { return new Key( handle, _view, (keyPermissionCheck != KeyPermissionCheck.ReadSubTree), false ) { _name = (normalizedSubKeyName.Length == 0) ? _name : $"{_name}\\{normalizedSubKeyName}", _keyPermissionCheck = keyPermissionCheck }; } if (errorCode != Windows.Error.Success) { ThrowException( errorCode, $"{_name}\\{normalizedSubKeyName}" ); } return null; } private void DoDeleteSubKey(string subKeyName) { var errorCode = Windows.RegDeleteKeyExW( _handle, subKeyName, ToRegistryKeyAccessRight(_view), IntPtr.Zero ); if (errorCode != Windows.Error.Success) { ThrowException( errorCode, null ); } } private void DoDeleteSubKeyTree(string subKeyName) { var subKey = DoOpenSubKey( subKeyName, KeyPermissionCheck.ReadWriteSubTree, true, false ); if (subKey != null) { using (subKey) { var subSubKeyNames = subKey.GetSubKeyNames(); foreach (var subSubKeyName in subSubKeyNames) { subKey.DoDeleteSubKeyTree(subSubKeyName); } } DoDeleteSubKey(subKeyName); } else { throw new ArgumentException("Cannot delete a subkey tree because the subkey does not exist."); } } private void DoDeleteValue( string valueName, bool throwOnMissingValue) { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } if (!IsWritable()) { throw new UnauthorizedAccessException("Cannot write to the registry key."); } var errorCode = Windows.RegDeleteValueW( _handle, valueName ); if (throwOnMissingValue && (errorCode == Windows.Error.FileNotFound || errorCode == Windows.Error.FilenameExceedRange)) { throw new ArgumentException("No value exists with that name."); } } private int DoGetSubKeyCount() { var bufferSize = 0u; var subKeyCount = 0u; var maxSubKeyLen = 0u; var maxClassLen = 0u; var maxValueLen = 0u; var maxValueNameLen = 0u; var valueCount = 0u; var errorCode = Windows.RegQueryInfoKeyW( _handle, null, ref bufferSize, IntPtr.Zero, ref subKeyCount, ref maxSubKeyLen, ref maxClassLen, ref valueCount, ref maxValueNameLen, ref maxValueLen, IntPtr.Zero, IntPtr.Zero ); if (errorCode != Windows.Error.Success) { ThrowException( errorCode, null ); } return (int)subKeyCount; } private string[] DoGetSubKeyNames(int subKeyCount) { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } var subKeyNameList = new List<string>(subKeyCount); var subKeyNameCharArray = new char[MaxKeyLength + 1]; var subKeyCharArrayLength = subKeyNameCharArray.Length; var bufferSize = 0u; Windows.Error result; while ((result = Windows.RegEnumKeyExW( _handle, (uint)subKeyNameList.Count, subKeyNameCharArray, ref subKeyCharArrayLength, IntPtr.Zero, null, ref bufferSize, IntPtr.Zero)) != Windows.Error.NoMoreItems) { if (result == Windows.Error.Success) { subKeyNameList.Add(new string(subKeyNameCharArray, 0, subKeyCharArrayLength)); subKeyCharArrayLength = subKeyNameCharArray.Length; } else { ThrowException( result, null ); } } return subKeyNameList.ToArray(); } private object DoGetValue( string valueName, object defaultValue) { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } var data = defaultValue; var registryValueType = Windows.RegistryValueType.None; uint bufferSize = 0; var errorCode = Windows.RegQueryValueExW( _handle, valueName, IntPtr.Zero, ref registryValueType, (byte[])null, ref bufferSize ); if (errorCode != Windows.Error.Success && errorCode != Windows.Error.MoreData) { return data; } if (registryValueType == Windows.RegistryValueType.DWord) { var buffer = 0; Windows.RegQueryValueExW( _handle, valueName, IntPtr.Zero, ref registryValueType, ref buffer, ref bufferSize ); data = buffer; } if (registryValueType == Windows.RegistryValueType.QWord && bufferSize == 8) { var buffer = 0L; Windows.RegQueryValueExW( _handle, valueName, IntPtr.Zero, ref registryValueType, ref buffer, ref bufferSize ); data = buffer; } if (registryValueType == Windows.RegistryValueType.None || registryValueType == Windows.RegistryValueType.Binary || registryValueType == Windows.RegistryValueType.DWordBigEndian) { var buffer = new byte[bufferSize]; Windows.RegQueryValueExW( _handle, valueName, IntPtr.Zero, ref registryValueType, buffer, ref bufferSize ); data = buffer; } if (registryValueType == Windows.RegistryValueType.String) { bufferSize = NormalizeStringBufferSize(bufferSize); var buffer = new char[bufferSize / 2]; Windows.RegQueryValueExW( _handle, valueName, IntPtr.Zero, ref registryValueType, buffer, ref bufferSize ); data = ToStringFromBuffer(buffer); } if (registryValueType == Windows.RegistryValueType.ExpandString) { bufferSize = NormalizeStringBufferSize(bufferSize); var buffer = new char[bufferSize / 2]; Windows.RegQueryValueExW( _handle, valueName, IntPtr.Zero, ref registryValueType, buffer, ref bufferSize ); data = Environment.ExpandEnvironmentVariables(ToStringFromBuffer(buffer)); } if (registryValueType == Windows.RegistryValueType.MultiString) { bufferSize = NormalizeStringBufferSize(bufferSize); var buffer = new char[bufferSize / 2]; errorCode = Windows.RegQueryValueExW( _handle, valueName, IntPtr.Zero, ref registryValueType, buffer, ref bufferSize ); if (buffer.Length > 0 && buffer[buffer.Length - 1] != (char)0) { System.Array.Resize(ref buffer, buffer.Length + 1); } var stringList = new List<string>(); var beginIndex = 0; var bufferLength = buffer.Length; while (errorCode == Windows.Error.Success && beginIndex < bufferLength) { var endIndex = beginIndex; while (endIndex < bufferLength && buffer[endIndex] != (char)0) { endIndex++; } string subString = null; if (endIndex < bufferLength) { if (endIndex - beginIndex > 0) { subString = new string(buffer, beginIndex, endIndex - beginIndex); } else if (endIndex != bufferLength - 1) { subString = string.Empty; } } else { subString = new string(buffer, beginIndex, bufferLength - beginIndex); } beginIndex = endIndex + 1; if (subString == null) { continue; } stringList.Add(subString); } data = stringList.ToArray(); } return data; } private int DoGetValueCount() { var bufferSize = 0u; var subKeyCount = 0u; var maxSubKeyLen = 0u; var maxClassLen = 0u; var maxValueLen = 0u; var maxValueNameLen = 0u; var valueCount = 0u; var errorCode = Windows.RegQueryInfoKeyW( _handle, null, ref bufferSize, IntPtr.Zero, ref subKeyCount, ref maxSubKeyLen, ref maxClassLen, ref valueCount, ref maxValueNameLen, ref maxValueLen, IntPtr.Zero, IntPtr.Zero ); if (errorCode != Windows.Error.Success) { ThrowException( errorCode, null ); } return (int)valueCount; } private ValueKind DoGetValueKind(string valueName) { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } var registryValueType = Windows.RegistryValueType.None; uint bufferSize = 0; var errorCode = Windows.RegQueryValueExW( _handle, valueName, IntPtr.Zero, ref registryValueType, (byte[])null, ref bufferSize ); if (errorCode != Windows.Error.Success) { ThrowException( errorCode, null ); } if (!Enum.IsDefined(typeof(Windows.RegistryValueType), registryValueType)) { return ValueKind.None; } return (ValueKind)registryValueType; } private string[] DoGetValueNames(int valueCount) { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } var valueNameList = new List<string>(valueCount); var valueNameCharArray = new char[128]; var valueNameCharArrayLength = valueNameCharArray.Length; Windows.Error result; while ((result = Windows.RegEnumValueW( _handle, (uint)valueNameList.Count, valueNameCharArray, ref valueNameCharArrayLength, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)) != Windows.Error.NoMoreItems) { if (result == Windows.Error.Success) { valueNameList.Add(new string(valueNameCharArray, 0, valueNameCharArrayLength)); } else if (result == Windows.Error.MoreData) { var oldValueNameCharArray = valueNameCharArray; var oldValueNameCharArrayLength = oldValueNameCharArray.Length; valueNameCharArray = new char[checked(oldValueNameCharArrayLength * 2)]; } else { ThrowException( result, null ); } valueNameCharArrayLength = valueNameCharArray.Length; } return valueNameList.ToArray(); } private Key DoOpenSubKey( string subKeyName, KeyPermissionCheck keyPermissionCheck, bool writable, bool throwOnAccessDenied) { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } var normalizedSubKeyName = NormalizeSubKeyName(subKeyName); Windows.SafeRegistryHandle handle; var errorCode = Windows.RegOpenKeyExW( _handle, normalizedSubKeyName, 0, ToRegistryKeyAccessRight(writable) | ToRegistryKeyAccessRight(_view), out handle ); if (errorCode == Windows.Error.Success && !handle.IsInvalid) { return new Key( handle, _view, writable, false ) { _name = $"{_name}\\{normalizedSubKeyName}", _keyPermissionCheck = keyPermissionCheck }; } if (throwOnAccessDenied && (errorCode == Windows.Error.AccessDenied || errorCode == Windows.Error.BadImpersonationLevel)) { throw new SecurityException("Requested registry access is not allowed."); } return null; } private void DoSetValue( string valueName, object value, ValueKind valueKind) { if (_handle == null) { throw new ObjectDisposedException(_name, "Cannot access a closed registry key."); } if (!IsWritable()) { throw new UnauthorizedAccessException("Cannot write to the registry key."); } var errorCode = Windows.Error.Success; try { if (valueKind == ValueKind.DWord) { var data = System.Convert.ToInt32( value, System.Globalization.CultureInfo.InvariantCulture ); errorCode = Windows.RegSetValueExW( _handle, valueName, 0, Windows.RegistryValueType.DWord, ref data, 4 ); } if (valueKind == ValueKind.QWord) { var data = System.Convert.ToInt64( value, System.Globalization.CultureInfo.InvariantCulture ); errorCode = Windows.RegSetValueExW( _handle, valueName, 0, Windows.RegistryValueType.QWord, ref data, 8 ); } if (valueKind == ValueKind.None || valueKind == ValueKind.Binary) { var data = (byte[])value; errorCode = Windows.RegSetValueExW( _handle, valueName, 0, ToRegistryValueType(valueKind), data, data.Length ); } if (valueKind == ValueKind.ExpandString || valueKind == ValueKind.String) { var data = value.ToString(); errorCode = Windows.RegSetValueExW( _handle, valueName, 0, ToRegistryValueType(valueKind), data, checked(data.Length * 2 + 2) ); } if (valueKind == ValueKind.MultiString) { var clonedStringArray = (string[])((string[])value).Clone(); // Format: str1\0str2\0str3\0\0 var sizeInChars = 1; foreach (var item in clonedStringArray) { if (item == null) { throw new ArgumentException("Win32Registry.Key.SetValue does not allow a string[] that contains a null string reference."); } sizeInChars = checked(sizeInChars + (item.Length + 1)); } var sizeInBytes = checked(sizeInChars * sizeof(char)); var data = new char[sizeInChars]; var destinationIndex = 0; foreach (var item in clonedStringArray) { var itemLength = item.Length; item.CopyTo( 0, data, destinationIndex, itemLength ); destinationIndex += (itemLength + 1); } errorCode = Windows.RegSetValueExW( _handle, valueName, 0, Windows.RegistryValueType.MultiString, data, sizeInBytes ); } } catch (Exception exc) when (exc is OverflowException || exc is InvalidOperationException || exc is FormatException || exc is InvalidCastException) { throw new ArgumentException("The type of the value object did not match the specified Win32Registry.ValueKind or the object could not be properly converted."); } if (errorCode != Windows.Error.Success) { ThrowException( errorCode, null ); } } /// <summary> /// Gets the subkey names. /// </summary> /// <returns>System.String[].</returns> public string[] GetSubKeyNames() { var subKeyCount = SubKeyCount; if (subKeyCount <= 0) { return Array.Empty<string>(); } return DoGetSubKeyNames(subKeyCount); } /// <summary> /// Gets the value. /// </summary> /// <param name="valueName">The value name.</param> /// <returns>System.Object.</returns> public object GetValue(string valueName) { return DoGetValue( valueName, null ); } /// <summary> /// Gets the value kind. /// </summary> /// <param name="valueName">The value name.</param> /// <returns>ValueKind.</returns> public ValueKind GetValueKind(string valueName) { return DoGetValueKind(valueName); } /// <summary> /// Gets the value names. /// </summary> /// <returns>System.String[].</returns> public string[] GetValueNames() { var values = ValueCount; if (values <= 0) { return Array.Empty<string>(); } return DoGetValueNames(values); } private bool IsSystemKey() { return (_keyStateFlag & KeyStateFlag.SystemKey) != 0; } private bool IsWritable() { return (_keyStateFlag & KeyStateFlag.WriteAccess) != 0; } private static void NormalizePath(StringBuilder path) { var pathLength = path.Length; var needToBeNormalized = false; const char markerChar = (char)0xFFFF; var i = 1; while (i < pathLength - 1) { if (path[i] == '\\') { i++; while (i < pathLength && path[i] == '\\') { path[i] = markerChar; i++; needToBeNormalized = true; } } i++; } if (!needToBeNormalized) { return; } i = 0; var j = 0; while (i < pathLength) { if (path[i] == markerChar) { i++; continue; } path[j] = path[i]; i++; j++; } path.Length += j - i; } private static uint NormalizeStringBufferSize(uint bufferSize) { if (bufferSize % 2 != 1) { return bufferSize; } try { bufferSize = checked(bufferSize + 1); } catch (OverflowException e) { throw new IOException("Win32Registry.Key.GetValue does not allow a String that has a length greater than Int32.MaxValue.", e); } return bufferSize; } private static string NormalizeSubKeyName(string name) { if (name.IndexOf('\\') == -1) { return name; } var stringBuilder = new StringBuilder(name); NormalizePath(stringBuilder); var index = stringBuilder.Length - 1; if (index >= 0 && stringBuilder[index] == '\\') // Remove trailing slash { stringBuilder.Length = index; } return stringBuilder.ToString(); } /// <summary> /// Opens the base key. /// </summary> /// <param name="hive">The hive.</param> /// <returns>Key.</returns> public static Key OpenBaseKey(Hive hive) { return OpenBaseKey( hive, View.Default ); } /// <summary> /// Opens the base key. /// </summary> /// <param name="hive">The hive.</param> /// <param name="view">The view.</param> /// <returns>Key.</returns> public static Key OpenBaseKey( Hive hive, View view) { return new Key( new Windows.SafeRegistryHandle( (IntPtr)hive, false ), view, true, true ) { _keyPermissionCheck = KeyPermissionCheck.Default, _name = RegistryHiveWithName[hive] }; } /// <summary> /// Opens the subkey. /// </summary> /// <param name="subKeyName">The subkey name.</param> /// <returns>Key.</returns> public Key OpenSubKey(string subKeyName) { return OpenSubKey( subKeyName, KeyPermissionCheck.Default ); } /// <summary> /// Opens the subkey. /// </summary> /// <param name="subKeyName">The subkey name.</param> /// <param name="keyPermissionCheck">The key permission check.</param> /// <returns>Key.</returns> public Key OpenSubKey( string subKeyName, KeyPermissionCheck keyPermissionCheck) { return DoOpenSubKey( subKeyName, keyPermissionCheck, keyPermissionCheck == KeyPermissionCheck.ReadWriteSubTree, true ); } /// <summary> /// Sets the value. /// </summary> /// <param name="valueName">The value name.</param> /// <param name="value">The value.</param> /// <param name="valueKind">The value kind.</param> /// <exception cref="ArgumentNullException">value</exception> /// <exception cref="ArgumentException">Registry value names should not be greater than 16,383 characters. - valueName</exception> /// <exception cref="ArgumentException">The specified RegistryValueKind is an invalid value - valueKind</exception> /// <exception cref="ArgumentException">value</exception> public void SetValue( string valueName, object value, ValueKind valueKind) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (valueName != null && valueName.Length > MaxValueNameLength) { throw new ArgumentException("Registry value names should not be greater than 16,383 characters.", nameof(valueName)); } if (!Enum.IsDefined(typeof(ValueKind), valueKind)) { throw new ArgumentException("The specified RegistryValueKind is an invalid value", nameof(valueKind)); } DoSetValue(valueName, value, valueKind); } private void ThrowException( Windows.Error errorCode, string keyName) { if (errorCode == Windows.Error.AccessDenied) { if (keyName != null) { throw new UnauthorizedAccessException($"Access to the registry key '{keyName}' is denied."); } throw new UnauthorizedAccessException(); } if (errorCode == Windows.Error.InvalidHandle) { _handle.SetHandleAsInvalid(); _handle = null; throw new IOException($"Unexpected error: {errorCode}", (int)errorCode); } if (errorCode == Windows.Error.FileNotFound) { throw new IOException("The specified registry key does not exist.", (int)errorCode); } throw new IOException($"Unexpected error: {errorCode}", (int)errorCode); } private static Windows.RegistryKeyAccessRights ToRegistryKeyAccessRight(bool isWritable) { if (!isWritable) { return Windows.RegistryKeyAccessRights.Read; } return Windows.RegistryKeyAccessRights.Read | Windows.RegistryKeyAccessRights.Write; } private static Windows.RegistryKeyAccessRights ToRegistryKeyAccessRight(View view) { return (Windows.RegistryKeyAccessRights)view; } private static Windows.RegistryValueType ToRegistryValueType(ValueKind valueKind) { return (Windows.RegistryValueType)valueKind; } private static string ToStringFromBuffer(char[] buffer) { if (buffer == null) { return null; } if (buffer.Length <= 0 || buffer[buffer.Length - 1] != (char)0) { return new string(buffer); } return new string(buffer, 0, buffer.Length - 1); } } } }
// 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.AcceptanceTestsBodyComplex { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Primitive operations. /// </summary> public partial interface IPrimitive { /// <summary> /// Get complex types with integer properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IntWrapper>> GetIntWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with integer properties /// </summary> /// <param name='complexBody'> /// Please put -1 and 2 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutIntWithHttpMessagesAsync(IntWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with long properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<LongWrapper>> GetLongWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with long properties /// </summary> /// <param name='complexBody'> /// Please put 1099511627775 and -999511627788 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutLongWithHttpMessagesAsync(LongWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with float properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<FloatWrapper>> GetFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with float properties /// </summary> /// <param name='complexBody'> /// Please put 1.05 and -0.003 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutFloatWithHttpMessagesAsync(FloatWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with double properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<DoubleWrapper>> GetDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with double properties /// </summary> /// <param name='complexBody'> /// Please put 3e-100 and /// -0.000000000000000000000000000000000000000000000000000000005 /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDoubleWithHttpMessagesAsync(DoubleWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with bool properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<BooleanWrapper>> GetBoolWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with bool properties /// </summary> /// <param name='complexBody'> /// Please put true and false /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBoolWithHttpMessagesAsync(BooleanWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with string properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<StringWrapper>> GetStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with string properties /// </summary> /// <param name='complexBody'> /// Please put 'goodrequest', '', and null /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutStringWithHttpMessagesAsync(StringWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with date properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<DateWrapper>> GetDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with date properties /// </summary> /// <param name='complexBody'> /// Please put '0001-01-01' and '2016-02-29' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateWithHttpMessagesAsync(DateWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with datetime properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<DatetimeWrapper>> GetDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with datetime properties /// </summary> /// <param name='complexBody'> /// Please put '0001-01-01T12:00:00-04:00' and /// '2015-05-18T11:38:00-08:00' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeWithHttpMessagesAsync(DatetimeWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get complex types with byte properties /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<ByteWrapper>> GetByteWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put complex types with byte properties /// </summary> /// <param name='complexBody'> /// Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6) /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutByteWithHttpMessagesAsync(ByteWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// UserSettings.cs // using System.Runtime.CompilerServices; namespace Xrm.Sdk { [ScriptNamespace("SparkleXrm.Sdk")] public class UserSettingsAttributes { public static string UserSettingsId = "usersettingsid"; public static string BusinessUnitId = "businessunitid"; public static string CalendarType = "calendartype"; public static string CurrencyDecimalPrecision = "currencydecimalprecision"; public static string CurrencyFormatCode = "currencyformatcode"; public static string CurrencySymbol = "currencysymbol"; public static string DateFormatCode = "dateformatcode"; public static string DateFormatString = "dateformatstring"; public static string DateSeparator = "dateseparator"; public static string DecimalSymbol = "decimalsymbol"; public static string DefaultCalendarView = "defaultcalendarview"; public static string DefaultDashboardId = "defaultdashboardid"; public static string LocaleId = "localeid"; public static string LongDateFormatCode = "longdateformatcode"; public static string NegativeCurrencyFormatCode = "negativecurrencyformatcode"; public static string NegativeFormatCode = "negativeformatcode"; public static string NumberGroupFormat = "numbergroupformat"; public static string NumberSeparator = "numberseparator"; public static string OfflineSyncInterval = "offlinesyncinterval"; public static string PricingDecimalPrecision = "pricingdecimalprecision"; public static string ShowWeekNumber = "showweeknumber"; public static string SystemUserId = "systemuserid"; public static string TimeFormatCodestring = "timeformatcodestring"; public static string TimeFormatString = "timeformatstring"; public static string TimeSeparator = "timeseparator"; public static string TimeZoneBias = "timezonebias"; public static string TimeZoneCode = "timezonecode"; public static string TimeZoneDaylightBias = "timezonedaylightbias"; public static string TimeZoneDaylightDay = "timezonedaylightday"; public static string TimeZoneDaylightDayOfWeek = "timezonedaylightdayofweek"; public static string TimeZoneDaylightHour = "timezonedaylighthour"; public static string TimeZoneDaylightMinute = "timezonedaylightminute"; public static string TimeZoneDaylightMonth = "timezonedaylightmonth"; public static string TimeZoneDaylightSecond = "timezonedaylightsecond"; public static string TimeZoneDaylightYear = "timezonedaylightyear"; public static string TimeZoneStandardBias = "timezonestandardbias"; public static string TimeZoneStandardDay = "timezonestandardday"; public static string TimeZoneStandardDayOfWeek = "timezonestandarddayofweek"; public static string TimeZoneStandardHour = "timezonestandardhour"; public static string TimeZoneStandardMinute = "timezonestandardminute"; public static string TimeZoneStandardMonth = "timezonestandardmonth"; public static string TimeZoneStandardSecond = "timezonestandardsecond"; public static string TimeZoneStandardYear = "timezonestandardyear"; public static string TransactionCurrencyId = "transactioncurrencyid"; public static string UILanguageId = "uilanguageid"; public static string WorkdayStartTime = "workdaystarttime"; public static string WorkdayStopTime = "workdaystoptime"; } [ScriptNamespace("SparkleXrm.Sdk")] public partial class UserSettings : Entity { public static string EntityLogicalName = "usersettings"; public UserSettings() : base(EntityLogicalName) { } [ScriptName("usersettingsid")] public Guid UserSettingsId; [ScriptName("businessunitid")] public Guid BusinessUnitId; [ScriptName("calendartype")] public int? CalendarType; [ScriptName("currencydecimalprecision")] public int? CurrencyDecimalPrecision; [ScriptName("currencyformatcode")] public int? CurrencyFormatCode; [ScriptName("currencysymbol")] public string CurrencySymbol; [ScriptName("dateformatcode")] public int? DateFormatCode; [ScriptName("dateformatstring")] public string DateFormatString; [ScriptName("dateseparator")] public string DateSeparator; [ScriptName("decimalsymbol")] public string DecimalSymbol; [ScriptName("defaultcalendarview")] public int? DefaultCalendarView; [ScriptName("defaultdashboardid")] public Guid DefaultDashboardId; [ScriptName("localeid")] public int? LocaleId; [ScriptName("longdateformatcode")] public int? LongDateFormatCode; [ScriptName("negativecurrencyformatcode")] public int? NegativeCurrencyFormatCode; [ScriptName("negativeformatcode")] public int? NegativeFormatCode; [ScriptName("numbergroupformat")] public string NumberGroupFormat; [ScriptName("numberseparator")] public string NumberSeparator; [ScriptName("offlinesyncinterval")] public int? OfflineSyncInterval; [ScriptName("pricingdecimalprecision")] public int? PricingDecimalPrecision; [ScriptName("showweeknumber")] public bool? ShowWeekNumber; [ScriptName("systemuserid")] public Guid SystemUserId; [ScriptName("timeformatcodestring")] public int? TimeFormatCodestring; [ScriptName("timeformatstring")] public string TimeFormatString; [ScriptName("timeseparator")] public string TimeSeparator; [ScriptName("timezonebias")] public int? TimeZoneBias; [ScriptName("timezonecode")] public int? TimeZoneCode; [ScriptName("timezonedaylightbias")] public int? TimeZoneDaylightBias; [ScriptName("timezonedaylightday")] public int? TimeZoneDaylightDay; [ScriptName("timezonedaylightdayofweek")] public int? TimeZoneDaylightDayOfWeek; [ScriptName("timezonedaylighthour")] public int? TimeZoneDaylightHour; [ScriptName("timezonedaylightminute")] public int? TimeZoneDaylightMinute; [ScriptName("timezonedaylightmonth")] public int? TimeZoneDaylightMonth; [ScriptName("timezonedaylightsecond")] public int? TimeZoneDaylightSecond; [ScriptName("timezonedaylightyear")] public int? TimeZoneDaylightYear; [ScriptName("timezonestandardbias")] public int? TimeZoneStandardBias; [ScriptName("timezonestandardday")] public int? TimeZoneStandardDay; [ScriptName("timezonestandarddayofweek")] public int? TimeZoneStandardDayOfWeek; [ScriptName("timezonestandardhour")] public int? TimeZoneStandardHour; [ScriptName("timezonestandardminute")] public int? TimeZoneStandardMinute; [ScriptName("timezonestandardmonth")] public int? TimeZoneStandardMonth; [ScriptName("timezonestandardsecond")] public int? TimeZoneStandardSecond; [ScriptName("timezonestandardyear")] public int? TimeZoneStandardYear; [ScriptName("transactioncurrencyid")] public EntityReference TransactionCurrencyId; [ScriptName("uilanguageid")] public int? UILanguageId; [ScriptName("workdaystarttime")] public string WorkdayStartTime; [ScriptName("workdaystoptime")] public string WorkdayStopTime; public string GetNumberFormatString(int decimalPlaces) { return "###,###,###.000"; } } }
// ZlibCodec.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-November-03 15:40:51> // // ------------------------------------------------------------------ // // This module defines a Codec for ZLIB compression and // decompression. This code extends code that was based the jzlib // implementation of zlib, but this code is completely novel. The codec // class is new, and encapsulates some behaviors that are new, and some // that were present in other classes in the jzlib code base. In // keeping with the license for jzlib, the copyright to the jzlib code // is included below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; using Interop=System.Runtime.InteropServices; namespace Ionic.Zlib { /// <summary> /// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951). /// </summary> /// /// <remarks> /// This class compresses and decompresses data according to the Deflate algorithm /// and optionally, the ZLIB format, as documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see /// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>. /// </remarks> #if !PCL [Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000D")] [Interop.ComVisible(true)] #if !NETCF [Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)] #endif #endif internal sealed class ZlibCodec { /// <summary> /// The buffer from which data is taken. /// </summary> public byte[] InputBuffer; /// <summary> /// An index into the InputBuffer array, indicating where to start reading. /// </summary> public int NextIn; /// <summary> /// The number of bytes available in the InputBuffer, starting at NextIn. /// </summary> /// <remarks> /// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesIn; /// <summary> /// Total number of bytes read so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesIn; /// <summary> /// Buffer to store output data. /// </summary> public byte[] OutputBuffer; /// <summary> /// An index into the OutputBuffer array, indicating where to start writing. /// </summary> public int NextOut; /// <summary> /// The number of bytes available in the OutputBuffer, starting at NextOut. /// </summary> /// <remarks> /// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesOut; /// <summary> /// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesOut; /// <summary> /// used for diagnostics, when something goes wrong! /// </summary> public System.String Message; internal DeflateManager dstate; internal InflateManager istate; internal uint _Adler32; /// <summary> /// The compression level to use in this codec. Useful only in compression mode. /// </summary> public CompressionLevel CompressLevel = CompressionLevel.Default; /// <summary> /// The number of Window Bits to use. /// </summary> /// <remarks> /// This gauges the size of the sliding window, and hence the /// compression effectiveness as well as memory consumption. It's best to just leave this /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies /// a 32k window. /// </remarks> public int WindowBits = ZlibConstants.WindowBitsDefault; /// <summary> /// The compression strategy to use. /// </summary> /// <remarks> /// This is only effective in compression. The theory offered by ZLIB is that different /// strategies could potentially produce significant differences in compression behavior /// for different data sets. Unfortunately I don't have any good recommendations for how /// to set it differently. When I tested changing the strategy I got minimally different /// compression performance. It's best to leave this property alone if you don't have a /// good feel for it. Or, you may want to produce a test harness that runs through the /// different strategy options and evaluates them on different file types. If you do that, /// let me know your results. /// </remarks> public CompressionStrategy Strategy = CompressionStrategy.Default; /// <summary> /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this. /// </summary> public int Adler32 { get { return (int)_Adler32; } } /// <summary> /// Create a ZlibCodec. /// </summary> /// <remarks> /// If you use this default constructor, you will later have to explicitly call /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress /// or decompress. /// </remarks> public ZlibCodec() { } /// <summary> /// Create a ZlibCodec that either compresses or decompresses. /// </summary> /// <param name="mode"> /// Indicates whether the codec should compress (deflate) or decompress (inflate). /// </param> public ZlibCodec(CompressionMode mode) { if (mode == CompressionMode.Compress) { int rc = InitializeDeflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate."); } else if (mode == CompressionMode.Decompress) { int rc = InitializeInflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate."); } else throw new ZlibException("Invalid ZlibStreamFlavor."); } /// <summary> /// Initialize the inflation state. /// </summary> /// <remarks> /// It is not necessary to call this before using the ZlibCodec to inflate data; /// It is implicitly called when you call the constructor. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate() { return InitializeInflate(this.WindowBits); } /// <summary> /// Initialize the inflation state with an explicit flag to /// govern the handling of RFC1950 header bytes. /// </summary> /// /// <remarks> /// By default, the ZLIB header defined in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If /// you want to read a zlib stream you should specify true for /// expectRfc1950Header. If you have a deflate stream, you will want to specify /// false. It is only necessary to invoke this initializer explicitly if you /// want to specify false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte /// pair when reading the stream of data to be inflated.</param> /// /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(bool expectRfc1950Header) { return InitializeInflate(this.WindowBits, expectRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for inflation, with the specified number of window bits. /// </summary> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeInflate(int windowBits) { this.WindowBits = windowBits; return InitializeInflate(windowBits, true); } /// <summary> /// Initialize the inflation state with an explicit flag to govern the handling of /// RFC1950 header bytes. /// </summary> /// /// <remarks> /// If you want to read a zlib stream you should specify true for /// expectRfc1950Header. In this case, the library will expect to find a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or /// GZIP stream, which does not have such a header, you will want to specify /// false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading /// the stream of data to be inflated.</param> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(int windowBits, bool expectRfc1950Header) { this.WindowBits = windowBits; if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); istate = new InflateManager(expectRfc1950Header); return istate.Initialize(this, windowBits); } /// <summary> /// Inflate the data in the InputBuffer, placing the result in the OutputBuffer. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and /// AvailableBytesOut before calling this method. /// </remarks> /// <example> /// <code> /// private void InflateBuffer() /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec decompressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length); /// MemoryStream ms = new MemoryStream(DecompressedBytes); /// /// int rc = decompressor.InitializeInflate(); /// /// decompressor.InputBuffer = CompressedBytes; /// decompressor.NextIn = 0; /// decompressor.AvailableBytesIn = CompressedBytes.Length; /// /// decompressor.OutputBuffer = buffer; /// /// // pass 1: inflate /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("inflating: " + decompressor.Message); /// /// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("inflating: " + decompressor.Message); /// /// if (buffer.Length - decompressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// decompressor.EndInflate(); /// } /// /// </code> /// </example> /// <param name="flush">The flush to use when inflating.</param> /// <returns>Z_OK if everything goes well.</returns> public int Inflate(FlushType flush) { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Inflate(flush); } /// <summary> /// Ends an inflation session. /// </summary> /// <remarks> /// Call this after successively calling Inflate(). This will cause all buffers to be flushed. /// After calling this you cannot call Inflate() without a intervening call to one of the /// InitializeInflate() overloads. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int EndInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); int ret = istate.End(); istate = null; return ret; } /// <summary> /// I don't know what this does! /// </summary> /// <returns>Z_OK if everything goes well.</returns> public int SyncInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Sync(); } /// <summary> /// Initialize the ZlibCodec for deflation operation. /// </summary> /// <remarks> /// The codec will use the MAX window bits and the default level of compression. /// </remarks> /// <example> /// <code> /// int bufferSize = 40000; /// byte[] CompressedBytes = new byte[bufferSize]; /// byte[] DecompressedBytes = new byte[bufferSize]; /// /// ZlibCodec compressor = new ZlibCodec(); /// /// compressor.InitializeDeflate(CompressionLevel.Default); /// /// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress); /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = compressor.InputBuffer.Length; /// /// compressor.OutputBuffer = CompressedBytes; /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = CompressedBytes.Length; /// /// while (compressor.TotalBytesIn != TextToCompress.Length &amp;&amp; compressor.TotalBytesOut &lt; bufferSize) /// { /// compressor.Deflate(FlushType.None); /// } /// /// while (true) /// { /// int rc= compressor.Deflate(FlushType.Finish); /// if (rc == ZlibConstants.Z_STREAM_END) break; /// } /// /// compressor.EndDeflate(); /// /// </code> /// </example> /// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns> public int InitializeDeflate() { return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified /// CompressionLevel. It will emit a ZLIB stream as it compresses. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level) { this.CompressLevel = level; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the explicit flag governing whether to emit an RFC1950 header byte pair. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified CompressionLevel. /// If you want to generate a zlib stream, you should specify true for /// wantRfc1950Header. In this case, the library will emit a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header) { this.CompressLevel = level; return _InternalInitializeDeflate(wantRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the specified number of window bits. /// </summary> /// <remarks> /// The codec will use the specified number of window bits and the specified CompressionLevel. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified /// CompressionLevel, the specified number of window bits, and the explicit flag /// governing whether to emit an RFC1950 header byte pair. /// </summary> /// /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(wantRfc1950Header); } private int _InternalInitializeDeflate(bool wantRfc1950Header) { if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate()."); dstate = new DeflateManager(); dstate.WantRfc1950HeaderBytes = wantRfc1950Header; return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy); } /// <summary> /// Deflate one batch of data. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer before calling this method. /// </remarks> /// <example> /// <code> /// private void DeflateBuffer(CompressionLevel level) /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec compressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length); /// MemoryStream ms = new MemoryStream(); /// /// int rc = compressor.InitializeDeflate(level); /// /// compressor.InputBuffer = UncompressedBytes; /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = UncompressedBytes.Length; /// /// compressor.OutputBuffer = buffer; /// /// // pass 1: deflate /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("deflating: " + compressor.Message); /// /// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("deflating: " + compressor.Message); /// /// if (buffer.Length - compressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// compressor.EndDeflate(); /// /// ms.Seek(0, SeekOrigin.Begin); /// CompressedBytes = new byte[compressor.TotalBytesOut]; /// ms.Read(CompressedBytes, 0, CompressedBytes.Length); /// } /// </code> /// </example> /// <param name="flush">whether to flush all data as you deflate. Generally you will want to /// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to /// flush everything. /// </param> /// <returns>Z_OK if all goes well.</returns> public int Deflate(FlushType flush) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.Deflate(flush); } /// <summary> /// End a deflation session. /// </summary> /// <remarks> /// Call this after making a series of one or more calls to Deflate(). All buffers are flushed. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public int EndDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this) //int ret = dstate.End(); dstate = null; return ZlibConstants.Z_OK; //ret; } /// <summary> /// Reset a codec for another deflation session. /// </summary> /// <remarks> /// Call this to reset the deflation state. For example if a thread is deflating /// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first /// block and before the next Deflate(None) of the second block. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public void ResetDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); dstate.Reset(); } /// <summary> /// Set the CompressionStrategy and CompressionLevel for a deflation session. /// </summary> /// <param name="level">the level of compression to use.</param> /// <param name="strategy">the strategy to use for compression.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.SetParams(level, strategy); } /// <summary> /// Set the dictionary to be used for either Inflation or Deflation. /// </summary> /// <param name="dictionary">The dictionary bytes to use.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDictionary(byte[] dictionary) { if (istate != null) return istate.SetDictionary(dictionary); if (dstate != null) return dstate.SetDictionary(dictionary); throw new ZlibException("No Inflate or Deflate state!"); } // Flush as much pending output as possible. All deflate() output goes // through this function so some applications may wish to modify it // to avoid allocating a large strm->next_out buffer and copying into it. // (See also read_buf()). internal void flush_pending() { int len = dstate.pendingCount; if (len > AvailableBytesOut) len = AvailableBytesOut; if (len == 0) return; if (dstate.pending.Length <= dstate.nextPending || OutputBuffer.Length <= NextOut || dstate.pending.Length < (dstate.nextPending + len) || OutputBuffer.Length < (NextOut + len)) { throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})", dstate.pending.Length, dstate.pendingCount)); } Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len); NextOut += len; dstate.nextPending += len; TotalBytesOut += len; AvailableBytesOut -= len; dstate.pendingCount -= len; if (dstate.pendingCount == 0) { dstate.nextPending = 0; } } // Read a new buffer from the current input stream, update the adler32 // and total number of bytes read. All deflate() input goes through // this function so some applications may wish to modify it to avoid // allocating a large strm->next_in buffer and copying from it. // (See also flush_pending()). internal int read_buf(byte[] buf, int start, int size) { int len = AvailableBytesIn; if (len > size) len = size; if (len == 0) return 0; AvailableBytesIn -= len; if (dstate.WantRfc1950HeaderBytes) { _Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len); } Array.Copy(InputBuffer, NextIn, buf, start, len); NextIn += len; TotalBytesIn += len; return len; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticbeanstalk-2010-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElasticBeanstalk.Model { /// <summary> /// Container for the parameters to the UpdateEnvironment operation. /// Updates the environment description, deploys a new application version, updates the /// configuration settings to an entirely new configuration template, or updates select /// configuration option values in the running environment. /// /// /// <para> /// Attempting to update both the release and configuration is not allowed and AWS Elastic /// Beanstalk returns an <code>InvalidParameterCombination</code> error. /// </para> /// /// <para> /// When updating the configuration settings to a new template or individual settings, /// a draft configuration is created and <a>DescribeConfigurationSettings</a> for this /// environment returns two setting descriptions with different <code>DeploymentStatus</code> /// values. /// </para> /// </summary> public partial class UpdateEnvironmentRequest : AmazonElasticBeanstalkRequest { private string _description; private string _environmentId; private string _environmentName; private List<ConfigurationOptionSetting> _optionSettings = new List<ConfigurationOptionSetting>(); private List<OptionSpecification> _optionsToRemove = new List<OptionSpecification>(); private string _solutionStackName; private string _templateName; private EnvironmentTier _tier; private string _versionLabel; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public UpdateEnvironmentRequest() { } /// <summary> /// Gets and sets the property Description. /// <para> /// If this parameter is specified, AWS Elastic Beanstalk updates the description of /// this environment. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property EnvironmentId. /// <para> /// The ID of the environment to update. /// </para> /// /// <para> /// If no environment with this ID exists, AWS Elastic Beanstalk returns an <code>InvalidParameterValue</code> /// error. /// </para> /// /// <para> /// Condition: You must specify either this or an EnvironmentName, or both. If you do /// not specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> /// error. /// </para> /// </summary> public string EnvironmentId { get { return this._environmentId; } set { this._environmentId = value; } } // Check to see if EnvironmentId property is set internal bool IsSetEnvironmentId() { return this._environmentId != null; } /// <summary> /// Gets and sets the property EnvironmentName. /// <para> /// The name of the environment to update. If no environment with this name exists, AWS /// Elastic Beanstalk returns an <code>InvalidParameterValue</code> error. /// </para> /// /// <para> /// Condition: You must specify either this or an EnvironmentId, or both. If you do not /// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> /// error. /// </para> /// </summary> public string EnvironmentName { get { return this._environmentName; } set { this._environmentName = value; } } // Check to see if EnvironmentName property is set internal bool IsSetEnvironmentName() { return this._environmentName != null; } /// <summary> /// Gets and sets the property OptionSettings. /// <para> /// If specified, AWS Elastic Beanstalk updates the configuration set associated with /// the running environment and sets the specified configuration options to the requested /// value. /// </para> /// </summary> public List<ConfigurationOptionSetting> OptionSettings { get { return this._optionSettings; } set { this._optionSettings = value; } } // Check to see if OptionSettings property is set internal bool IsSetOptionSettings() { return this._optionSettings != null && this._optionSettings.Count > 0; } /// <summary> /// Gets and sets the property OptionsToRemove. /// <para> /// A list of custom user-defined configuration options to remove from the configuration /// set for this environment. /// </para> /// </summary> public List<OptionSpecification> OptionsToRemove { get { return this._optionsToRemove; } set { this._optionsToRemove = value; } } // Check to see if OptionsToRemove property is set internal bool IsSetOptionsToRemove() { return this._optionsToRemove != null && this._optionsToRemove.Count > 0; } /// <summary> /// Gets and sets the property SolutionStackName. /// <para> /// This specifies the platform version that the environment will run after the environment /// is updated. /// </para> /// </summary> public string SolutionStackName { get { return this._solutionStackName; } set { this._solutionStackName = value; } } // Check to see if SolutionStackName property is set internal bool IsSetSolutionStackName() { return this._solutionStackName != null; } /// <summary> /// Gets and sets the property TemplateName. /// <para> /// If this parameter is specified, AWS Elastic Beanstalk deploys this configuration /// template to the environment. If no such configuration template is found, AWS Elastic /// Beanstalk returns an <code>InvalidParameterValue</code> error. /// </para> /// </summary> public string TemplateName { get { return this._templateName; } set { this._templateName = value; } } // Check to see if TemplateName property is set internal bool IsSetTemplateName() { return this._templateName != null; } /// <summary> /// Gets and sets the property Tier. /// <para> /// This specifies the tier to use to update the environment. /// </para> /// /// <para> /// Condition: At this time, if you change the tier version, name, or type, AWS Elastic /// Beanstalk returns <code>InvalidParameterValue</code> error. /// </para> /// </summary> public EnvironmentTier Tier { get { return this._tier; } set { this._tier = value; } } // Check to see if Tier property is set internal bool IsSetTier() { return this._tier != null; } /// <summary> /// Gets and sets the property VersionLabel. /// <para> /// If this parameter is specified, AWS Elastic Beanstalk deploys the named application /// version to the environment. If no such application version is found, returns an <code>InvalidParameterValue</code> /// error. /// </para> /// </summary> public string VersionLabel { get { return this._versionLabel; } set { this._versionLabel = value; } } // Check to see if VersionLabel property is set internal bool IsSetVersionLabel() { return this._versionLabel != null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Diagnostics.Contracts; using System.Net; using System.Net.Security; using System.Runtime; using System.Security.Authentication.ExtendedProtection; namespace System.ServiceModel.Channels { public class HttpTransportBindingElement : TransportBindingElement { private bool _allowCookies; private AuthenticationSchemes _authenticationScheme; private bool _decompressionEnabled; private HostNameComparisonMode _hostNameComparisonMode; private bool _keepAliveEnabled; private bool _inheritBaseAddressSettings; private int _maxBufferSize; private bool _maxBufferSizeInitialized; private string _method; private string _realm; private TimeSpan _requestInitializationTimeout; private TransferMode _transferMode; private bool _unsafeConnectionNtlmAuthentication; private bool _useDefaultWebProxy; private WebSocketTransportSettings _webSocketSettings; #if !FEATURE_NETNATIVE private ExtendedProtectionPolicy _extendedProtectionPolicy; #endif // !FEATURE_NETNATIVE private HttpMessageHandlerFactory _httpMessageHandlerFactory; private int _maxPendingAccepts; public HttpTransportBindingElement() : base() { _allowCookies = HttpTransportDefaults.AllowCookies; _authenticationScheme = HttpTransportDefaults.AuthenticationScheme; _decompressionEnabled = HttpTransportDefaults.DecompressionEnabled; _hostNameComparisonMode = HttpTransportDefaults.HostNameComparisonMode; _keepAliveEnabled = HttpTransportDefaults.KeepAliveEnabled; _maxBufferSize = TransportDefaults.MaxBufferSize; _maxPendingAccepts = HttpTransportDefaults.DefaultMaxPendingAccepts; _method = string.Empty; _realm = HttpTransportDefaults.Realm; _requestInitializationTimeout = HttpTransportDefaults.RequestInitializationTimeout; _transferMode = HttpTransportDefaults.TransferMode; _unsafeConnectionNtlmAuthentication = HttpTransportDefaults.UnsafeConnectionNtlmAuthentication; _useDefaultWebProxy = HttpTransportDefaults.UseDefaultWebProxy; _webSocketSettings = HttpTransportDefaults.GetDefaultWebSocketTransportSettings(); } protected HttpTransportBindingElement(HttpTransportBindingElement elementToBeCloned) : base(elementToBeCloned) { _allowCookies = elementToBeCloned._allowCookies; _authenticationScheme = elementToBeCloned._authenticationScheme; _decompressionEnabled = elementToBeCloned._decompressionEnabled; _hostNameComparisonMode = elementToBeCloned._hostNameComparisonMode; _inheritBaseAddressSettings = elementToBeCloned.InheritBaseAddressSettings; _keepAliveEnabled = elementToBeCloned._keepAliveEnabled; _maxBufferSize = elementToBeCloned._maxBufferSize; _maxBufferSizeInitialized = elementToBeCloned._maxBufferSizeInitialized; _maxPendingAccepts = elementToBeCloned._maxPendingAccepts; _method = elementToBeCloned._method; _realm = elementToBeCloned._realm; _requestInitializationTimeout = elementToBeCloned._requestInitializationTimeout; _transferMode = elementToBeCloned._transferMode; _unsafeConnectionNtlmAuthentication = elementToBeCloned._unsafeConnectionNtlmAuthentication; _useDefaultWebProxy = elementToBeCloned._useDefaultWebProxy; _webSocketSettings = elementToBeCloned._webSocketSettings.Clone(); #if !FEATURE_NETNATIVE _extendedProtectionPolicy = elementToBeCloned.ExtendedProtectionPolicy; #endif // !FEATURE_NETNATIVE this.MessageHandlerFactory = elementToBeCloned.MessageHandlerFactory; } [DefaultValue(HttpTransportDefaults.AllowCookies)] public bool AllowCookies { get { return _allowCookies; } set { _allowCookies = value; } } [DefaultValue(HttpTransportDefaults.AuthenticationScheme)] public AuthenticationSchemes AuthenticationScheme { get { return _authenticationScheme; } set { _authenticationScheme = value; } } [DefaultValue(HttpTransportDefaults.DecompressionEnabled)] public bool DecompressionEnabled { get { return _decompressionEnabled; } set { _decompressionEnabled = value; } } [DefaultValue(HttpTransportDefaults.HostNameComparisonMode)] public HostNameComparisonMode HostNameComparisonMode { get { return _hostNameComparisonMode; } set { HostNameComparisonModeHelper.Validate(value); _hostNameComparisonMode = value; } } public HttpMessageHandlerFactory MessageHandlerFactory { get { return _httpMessageHandlerFactory; } set { _httpMessageHandlerFactory = value; } } #if !FEATURE_NETNATIVE public ExtendedProtectionPolicy ExtendedProtectionPolicy { get { return _extendedProtectionPolicy; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value.PolicyEnforcement == PolicyEnforcement.Always && !System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy.OSSupportsExtendedProtection) { ExceptionHelper.PlatformNotSupported(SR.ExtendedProtectionNotSupported); } _extendedProtectionPolicy = value; } } #endif // !FEATURE_NETNATIVE // MB#26970: used by MEX to ensure that we don't conflict on base-address scoped settings internal bool InheritBaseAddressSettings { get { return _inheritBaseAddressSettings; } set { _inheritBaseAddressSettings = value; } } [DefaultValue(HttpTransportDefaults.KeepAliveEnabled)] public bool KeepAliveEnabled { get { return _keepAliveEnabled; } set { _keepAliveEnabled = value; } } // client // server [DefaultValue(TransportDefaults.MaxBufferSize)] public int MaxBufferSize { get { if (_maxBufferSizeInitialized || TransferMode != TransferMode.Buffered) return _maxBufferSize; long maxReceivedMessageSize = MaxReceivedMessageSize; if (maxReceivedMessageSize > int.MaxValue) return int.MaxValue; else return (int)maxReceivedMessageSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.ValueMustBePositive)); } _maxBufferSizeInitialized = true; _maxBufferSize = value; } } // server [DefaultValue(HttpTransportDefaults.DefaultMaxPendingAccepts)] public int MaxPendingAccepts { get { return _maxPendingAccepts; } set { if (value < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.ValueMustBeNonNegative)); } if (value > HttpTransportDefaults.MaxPendingAcceptsUpperLimit) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.Format(SR.HttpMaxPendingAcceptsTooLargeError, HttpTransportDefaults.MaxPendingAcceptsUpperLimit))); } _maxPendingAccepts = value; } } // string.Empty == wildcard internal string Method { get { return _method; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } _method = value; } } [DefaultValue(HttpTransportDefaults.Realm)] public string Realm { get { return _realm; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } _realm = value; } } [DefaultValue(typeof(TimeSpan), HttpTransportDefaults.RequestInitializationTimeoutString)] public TimeSpan RequestInitializationTimeout { get { return _requestInitializationTimeout; } set { if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRange0)); } if (TimeoutHelper.IsTooLarge(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.SFxTimeoutOutOfRangeTooBig)); } _requestInitializationTimeout = value; } } public override string Scheme { get { return "http"; } } // client // server [DefaultValue(HttpTransportDefaults.TransferMode)] public TransferMode TransferMode { get { return _transferMode; } set { TransferModeHelper.Validate(value); _transferMode = value; } } public WebSocketTransportSettings WebSocketSettings { get { return _webSocketSettings; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } _webSocketSettings = value; } } internal virtual bool GetSupportsClientAuthenticationImpl(AuthenticationSchemes effectiveAuthenticationSchemes) { return effectiveAuthenticationSchemes != AuthenticationSchemes.None && effectiveAuthenticationSchemes.IsNotSet(AuthenticationSchemes.Anonymous); } internal virtual bool GetSupportsClientWindowsIdentityImpl(AuthenticationSchemes effectiveAuthenticationSchemes) { return effectiveAuthenticationSchemes != AuthenticationSchemes.None && effectiveAuthenticationSchemes.IsNotSet(AuthenticationSchemes.Anonymous); } [DefaultValue(HttpTransportDefaults.UnsafeConnectionNtlmAuthentication)] public bool UnsafeConnectionNtlmAuthentication { get { return _unsafeConnectionNtlmAuthentication; } set { _unsafeConnectionNtlmAuthentication = value; } } public bool UseDefaultWebProxy { get { return _useDefaultWebProxy; } } internal string GetWsdlTransportUri(bool useWebSocketTransport) { if (useWebSocketTransport) { return TransportPolicyConstants.WebSocketTransportUri; } return TransportPolicyConstants.HttpTransportUri; } public override BindingElement Clone() { return new HttpTransportBindingElement(this); } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (typeof(T) == typeof(ISecurityCapabilities)) { AuthenticationSchemes effectiveAuthenticationSchemes = this.AuthenticationScheme; // Desktop: HttpTransportBindingElement.GetEffectiveAuthenticationSchemes(this.AuthenticationScheme, context.BindingParameters); return (T)(object)new SecurityCapabilities(this.GetSupportsClientAuthenticationImpl(effectiveAuthenticationSchemes), effectiveAuthenticationSchemes == AuthenticationSchemes.Negotiate, this.GetSupportsClientWindowsIdentityImpl(effectiveAuthenticationSchemes), ProtectionLevel.None, ProtectionLevel.None); } else if (typeof(T) == typeof(IBindingDeliveryCapabilities)) { return (T)(object)new BindingDeliveryCapabilitiesHelper(); } else if (typeof(T) == typeof(TransferMode)) { return (T)(object)this.TransferMode; } #if !FEATURE_NETNATIVE else if (typeof(T) == typeof(ExtendedProtectionPolicy)) { return (T)(object)this.ExtendedProtectionPolicy; } #endif //!FEATURE_NETNATIVE else if (typeof(T) == typeof(ITransportCompressionSupport)) { return (T)(object)new TransportCompressionSupportHelper(); } else { Contract.Assert(context.BindingParameters != null); if (context.BindingParameters.Find<MessageEncodingBindingElement>() == null) { context.BindingParameters.Add(new TextMessageEncodingBindingElement()); } return base.GetProperty<T>(context); } } public override bool CanBuildChannelFactory<TChannel>(BindingContext context) { if (typeof(TChannel) == typeof(IRequestChannel)) { return this.WebSocketSettings.TransportUsage != WebSocketTransportUsage.Always; } else if (typeof(TChannel) == typeof(IDuplexSessionChannel)) { return this.WebSocketSettings.TransportUsage != WebSocketTransportUsage.Never; } return false; } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (this.MessageHandlerFactory != null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(SR.HttpPipelineNotSupportedOnClientSide, "MessageHandlerFactory"))); } if (!this.CanBuildChannelFactory<TChannel>(context)) { Contract.Assert(context.Binding != null); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.Format(SR.CouldnTCreateChannelForChannelType2, context.Binding.Name, typeof(TChannel))); } if (_authenticationScheme == AuthenticationSchemes.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpAuthSchemeCannotBeNone, _authenticationScheme)); } else if (!_authenticationScheme.IsSingleton()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme, _authenticationScheme)); } return (IChannelFactory<TChannel>)(object)new HttpChannelFactory<TChannel>(this, context); } internal override bool IsMatch(BindingElement b) { if (!base.IsMatch(b)) return false; HttpTransportBindingElement http = b as HttpTransportBindingElement; if (http == null) return false; if (_allowCookies != http._allowCookies) return false; if (_authenticationScheme != http._authenticationScheme) return false; if (_decompressionEnabled != http._decompressionEnabled) return false; if (_hostNameComparisonMode != http._hostNameComparisonMode) return false; if (_inheritBaseAddressSettings != http._inheritBaseAddressSettings) return false; if (_keepAliveEnabled != http._keepAliveEnabled) return false; if (_maxBufferSize != http._maxBufferSize) return false; if (_method != http._method) return false; if (_realm != http._realm) return false; if (_transferMode != http._transferMode) return false; if (_unsafeConnectionNtlmAuthentication != http._unsafeConnectionNtlmAuthentication) return false; if (_useDefaultWebProxy != http._useDefaultWebProxy) return false; if (!this.WebSocketSettings.Equals(http.WebSocketSettings)) return false; return true; } private MessageEncodingBindingElement FindMessageEncodingBindingElement(BindingElementCollection bindingElements, out bool createdNew) { createdNew = false; MessageEncodingBindingElement encodingBindingElement = bindingElements.Find<MessageEncodingBindingElement>(); if (encodingBindingElement == null) { createdNew = true; encodingBindingElement = new TextMessageEncodingBindingElement(); } return encodingBindingElement; } private class BindingDeliveryCapabilitiesHelper : IBindingDeliveryCapabilities { internal BindingDeliveryCapabilitiesHelper() { } bool IBindingDeliveryCapabilities.AssuresOrderedDelivery { get { return false; } } bool IBindingDeliveryCapabilities.QueuedDelivery { get { return false; } } } private class TransportCompressionSupportHelper : ITransportCompressionSupport { public bool IsCompressionFormatSupported(CompressionFormat compressionFormat) { return true; } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G06Level111 (editable child object).<br/> /// This is a generated base class of <see cref="G06Level111"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="G07Level1111Objects"/> of type <see cref="G07Level1111Coll"/> (1:M relation to <see cref="G08Level1111"/>)<br/> /// This class is an item of <see cref="G05Level111Coll"/> collection. /// </remarks> [Serializable] public partial class G06Level111 : BusinessBase<G06Level111> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] private byte[] _rowVersion = new byte[] {}; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Level_1_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_1_ID, "Level_1_1_1 ID"); /// <summary> /// Gets the Level_1_1_1 ID. /// </summary> /// <value>The Level_1_1_1 ID.</value> public int Level_1_1_1_ID { get { return GetProperty(Level_1_1_1_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Name, "Level_1_1_1 Name"); /// <summary> /// Gets or sets the Level_1_1_1 Name. /// </summary> /// <value>The Level_1_1_1 Name.</value> public string Level_1_1_1_Name { get { return GetProperty(Level_1_1_1_NameProperty); } set { SetProperty(Level_1_1_1_NameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="MarentID1"/> property. /// </summary> public static readonly PropertyInfo<int> MarentID1Property = RegisterProperty<int>(p => p.MarentID1, "Marent ID1"); /// <summary> /// Gets or sets the Marent ID1. /// </summary> /// <value>The Marent ID1.</value> public int MarentID1 { get { return GetProperty(MarentID1Property); } set { SetProperty(MarentID1Property, value); } } /// <summary> /// Maintains metadata about child <see cref="G07Level1111SingleObject"/> property. /// </summary> public static readonly PropertyInfo<G07Level1111Child> G07Level1111SingleObjectProperty = RegisterProperty<G07Level1111Child>(p => p.G07Level1111SingleObject, "A7 Level1111 Single Object", RelationshipTypes.Child); /// <summary> /// Gets the G07 Level1111 Single Object ("self load" child property). /// </summary> /// <value>The G07 Level1111 Single Object.</value> public G07Level1111Child G07Level1111SingleObject { get { return GetProperty(G07Level1111SingleObjectProperty); } private set { LoadProperty(G07Level1111SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G07Level1111ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<G07Level1111ReChild> G07Level1111ASingleObjectProperty = RegisterProperty<G07Level1111ReChild>(p => p.G07Level1111ASingleObject, "A7 Level1111 ASimple Object", RelationshipTypes.Child); /// <summary> /// Gets the G07 Level1111 ASingle Object ("self load" child property). /// </summary> /// <value>The G07 Level1111 ASingle Object.</value> public G07Level1111ReChild G07Level1111ASingleObject { get { return GetProperty(G07Level1111ASingleObjectProperty); } private set { LoadProperty(G07Level1111ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="G07Level1111Objects"/> property. /// </summary> public static readonly PropertyInfo<G07Level1111Coll> G07Level1111ObjectsProperty = RegisterProperty<G07Level1111Coll>(p => p.G07Level1111Objects, "A7 Level1111 Objects", RelationshipTypes.Child); /// <summary> /// Gets the G07 Level1111 Objects ("self load" child property). /// </summary> /// <value>The G07 Level1111 Objects.</value> public G07Level1111Coll G07Level1111Objects { get { return GetProperty(G07Level1111ObjectsProperty); } private set { LoadProperty(G07Level1111ObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G06Level111"/> object. /// </summary> /// <returns>A reference to the created <see cref="G06Level111"/> object.</returns> internal static G06Level111 NewG06Level111() { return DataPortal.CreateChild<G06Level111>(); } /// <summary> /// Factory method. Loads a <see cref="G06Level111"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="G06Level111"/> object.</returns> internal static G06Level111 GetG06Level111(SafeDataReader dr) { G06Level111 obj = new G06Level111(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G06Level111"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private G06Level111() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G06Level111"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Level_1_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(G07Level1111SingleObjectProperty, DataPortal.CreateChild<G07Level1111Child>()); LoadProperty(G07Level1111ASingleObjectProperty, DataPortal.CreateChild<G07Level1111ReChild>()); LoadProperty(G07Level1111ObjectsProperty, DataPortal.CreateChild<G07Level1111Coll>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G06Level111"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_IDProperty, dr.GetInt32("Level_1_1_1_ID")); LoadProperty(Level_1_1_1_NameProperty, dr.GetString("Level_1_1_1_Name")); LoadProperty(MarentID1Property, dr.GetInt32("MarentID1")); _rowVersion = (dr.GetValue("RowVersion")) as byte[]; var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(G07Level1111SingleObjectProperty, G07Level1111Child.GetG07Level1111Child(Level_1_1_1_ID)); LoadProperty(G07Level1111ASingleObjectProperty, G07Level1111ReChild.GetG07Level1111ReChild(Level_1_1_1_ID)); LoadProperty(G07Level1111ObjectsProperty, G07Level1111Coll.GetG07Level1111Coll(Level_1_1_1_ID)); } /// <summary> /// Inserts a new <see cref="G06Level111"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG06Level111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", ReadProperty(Level_1_1_1_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Level_1_1_1_Name", ReadProperty(Level_1_1_1_NameProperty)).DbType = DbType.String; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; LoadProperty(Level_1_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_1_ID"].Value); } FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="G06Level111"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG06Level111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", ReadProperty(Level_1_1_1_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_Name", ReadProperty(Level_1_1_1_NameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@MarentID1", ReadProperty(MarentID1Property)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); _rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value; } FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="G06Level111"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteG06Level111", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", ReadProperty(Level_1_1_1_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(G07Level1111SingleObjectProperty, DataPortal.CreateChild<G07Level1111Child>()); LoadProperty(G07Level1111ASingleObjectProperty, DataPortal.CreateChild<G07Level1111ReChild>()); LoadProperty(G07Level1111ObjectsProperty, DataPortal.CreateChild<G07Level1111Coll>()); } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
namespace StockSharp.Algo.Strategies { using System; using System.Collections.Generic; using StockSharp.BusinessEntities; using StockSharp.Messages; partial class Strategy { private IMarketDataProvider MarketDataProvider => SafeGetConnector(); /// <inheritdoc /> public event Action<Security, IEnumerable<KeyValuePair<Level1Fields, object>>, DateTimeOffset, DateTimeOffset> ValuesChanged; /// <inheritdoc /> [Obsolete("Use MarketDepthReceived event.")] public MarketDepth GetMarketDepth(Security security) => MarketDataProvider.GetMarketDepth(security); /// <inheritdoc /> public object GetSecurityValue(Security security, Level1Fields field) => MarketDataProvider.GetSecurityValue(security, field); /// <inheritdoc /> public IEnumerable<Level1Fields> GetLevel1Fields(Security security) => MarketDataProvider.GetLevel1Fields(security); /// <inheritdoc /> [Obsolete("Use TickTradeReceived event.")] public event Action<Trade> NewTrade { add => MarketDataProvider.NewTrade += value; remove => MarketDataProvider.NewTrade -= value; } /// <inheritdoc /> [Obsolete("Use SecurityReceived event.")] public event Action<Security> NewSecurity { add => MarketDataProvider.NewSecurity += value; remove => MarketDataProvider.NewSecurity -= value; } /// <inheritdoc /> [Obsolete("Use SecurityReceived event.")] public event Action<Security> SecurityChanged { add => MarketDataProvider.SecurityChanged += value; remove => MarketDataProvider.SecurityChanged -= value; } /// <inheritdoc /> [Obsolete("Use OrderBookReceived event.")] public event Action<MarketDepth> NewMarketDepth { add => MarketDataProvider.NewMarketDepth += value; remove => MarketDataProvider.NewMarketDepth -= value; } /// <inheritdoc /> [Obsolete("Use OrderBookReceived event.")] public event Action<MarketDepth> MarketDepthChanged { add => MarketDataProvider.MarketDepthChanged += value; remove => MarketDataProvider.MarketDepthChanged -= value; } /// <inheritdoc /> [Obsolete("Use MarketDepthReceived event.")] public event Action<MarketDepth> FilteredMarketDepthChanged { add => MarketDataProvider.FilteredMarketDepthChanged += value; remove => MarketDataProvider.FilteredMarketDepthChanged -= value; } /// <inheritdoc /> [Obsolete("Use OrderLogItemReceived event.")] public event Action<OrderLogItem> NewOrderLogItem { add => MarketDataProvider.NewOrderLogItem += value; remove => MarketDataProvider.NewOrderLogItem -= value; } /// <inheritdoc /> [Obsolete("Use NewsReceived event.")] public event Action<News> NewNews { add => MarketDataProvider.NewNews += value; remove => MarketDataProvider.NewNews -= value; } /// <inheritdoc /> [Obsolete("Use NewsReceived event.")] public event Action<News> NewsChanged { add => MarketDataProvider.NewsChanged += value; remove => MarketDataProvider.NewsChanged -= value; } /// <inheritdoc /> public event Action<SecurityLookupMessage, IEnumerable<Security>, Exception> LookupSecuritiesResult { add => MarketDataProvider.LookupSecuritiesResult += value; remove => MarketDataProvider.LookupSecuritiesResult -= value; } /// <inheritdoc /> public event Action<SecurityLookupMessage, IEnumerable<Security>, IEnumerable<Security>, Exception> LookupSecuritiesResult2 { add => MarketDataProvider.LookupSecuritiesResult2 += value; remove => MarketDataProvider.LookupSecuritiesResult2 -= value; } /// <inheritdoc /> public event Action<BoardLookupMessage, IEnumerable<ExchangeBoard>, Exception> LookupBoardsResult { add => MarketDataProvider.LookupBoardsResult += value; remove => MarketDataProvider.LookupBoardsResult -= value; } /// <inheritdoc /> public event Action<BoardLookupMessage, IEnumerable<ExchangeBoard>, IEnumerable<ExchangeBoard>, Exception> LookupBoardsResult2 { add => MarketDataProvider.LookupBoardsResult2 += value; remove => MarketDataProvider.LookupBoardsResult2 -= value; } /// <inheritdoc /> public event Action<TimeFrameLookupMessage, IEnumerable<TimeSpan>, Exception> LookupTimeFramesResult { add => MarketDataProvider.LookupTimeFramesResult += value; remove => MarketDataProvider.LookupTimeFramesResult -= value; } /// <inheritdoc /> public event Action<TimeFrameLookupMessage, IEnumerable<TimeSpan>, IEnumerable<TimeSpan>, Exception> LookupTimeFramesResult2 { add => MarketDataProvider.LookupTimeFramesResult2 += value; remove => MarketDataProvider.LookupTimeFramesResult2 -= value; } /// <inheritdoc /> public event Action<Security, MarketDataMessage> MarketDataSubscriptionSucceeded { add => MarketDataProvider.MarketDataSubscriptionSucceeded += value; remove => MarketDataProvider.MarketDataSubscriptionSucceeded -= value; } /// <inheritdoc /> public event Action<Security, MarketDataMessage, Exception> MarketDataSubscriptionFailed { add => MarketDataProvider.MarketDataSubscriptionFailed += value; remove => MarketDataProvider.MarketDataSubscriptionFailed -= value; } /// <inheritdoc /> public event Action<Security, MarketDataMessage, SubscriptionResponseMessage> MarketDataSubscriptionFailed2 { add => MarketDataProvider.MarketDataSubscriptionFailed2 += value; remove => MarketDataProvider.MarketDataSubscriptionFailed2 -= value; } /// <inheritdoc /> public event Action<Security, MarketDataMessage> MarketDataUnSubscriptionSucceeded { add => MarketDataProvider.MarketDataUnSubscriptionSucceeded += value; remove => MarketDataProvider.MarketDataUnSubscriptionSucceeded -= value; } /// <inheritdoc /> public event Action<Security, MarketDataMessage, Exception> MarketDataUnSubscriptionFailed { add => MarketDataProvider.MarketDataUnSubscriptionFailed += value; remove => MarketDataProvider.MarketDataUnSubscriptionFailed -= value; } /// <inheritdoc /> public event Action<Security, MarketDataMessage, SubscriptionResponseMessage> MarketDataUnSubscriptionFailed2 { add => MarketDataProvider.MarketDataUnSubscriptionFailed2 += value; remove => MarketDataProvider.MarketDataUnSubscriptionFailed2 -= value; } /// <inheritdoc /> public event Action<Security, SubscriptionFinishedMessage> MarketDataSubscriptionFinished { add => MarketDataProvider.MarketDataSubscriptionFinished += value; remove => MarketDataProvider.MarketDataSubscriptionFinished -= value; } /// <inheritdoc /> public event Action<Security, MarketDataMessage, Exception> MarketDataUnexpectedCancelled { add => MarketDataProvider.MarketDataUnexpectedCancelled += value; remove => MarketDataProvider.MarketDataUnexpectedCancelled -= value; } /// <inheritdoc /> public event Action<Security, MarketDataMessage> MarketDataSubscriptionOnline { add => MarketDataProvider.MarketDataSubscriptionOnline += value; remove => MarketDataProvider.MarketDataSubscriptionOnline -= value; } /// <inheritdoc /> [Obsolete("Use MarketDepthReceived event.")] public MarketDepth GetFilteredMarketDepth(Security security) => MarketDataProvider.GetFilteredMarketDepth(security); } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Imported.PeanutButter.Utils; using NExpect.Exceptions; using NExpect.Implementations; using NExpect.Implementations.Collections; using NExpect.Implementations.Strings; using NExpect.Interfaces; using NExpect.Shims; // ReSharper disable UnusedMember.Global [assembly: InternalsVisibleTo("NExpect.Matchers.NSubstitute")] [assembly: InternalsVisibleTo("NExpect.Matchers.Xml")] namespace NExpect { /// <summary> /// Provides the basic Expect() method. You should import this statically /// into your test fixture class file. /// </summary> public static class Expectations { internal const string METADATA_KEY = "__ExpectationContext__"; internal const string KEY_COMPARER = "key-comparer"; /// <summary> /// Starts an expectation with a value. Usually used to /// check for equality or null. /// </summary> /// <param name="value">Value to start with.</param> /// <typeparam name="T">Type of the value.</typeparam> /// <returns>IExpectation&lt;T&gt;</returns> public static IExpectation<T> Expect<T>(T value) { return new Expectation<T>(value); } /// <summary> /// Starts an expectation with sbyte value and up casts to long. Usually used to /// check for equality. /// </summary> /// <param name="value">SByte value to start with.</param> /// <returns>IExpectation&lt;longT&gt;</returns> public static IExpectation<long> Expect(sbyte value) { return new Expectation<long>(value); } /// <summary> /// Starts an expectation with short value and up casts to long. Usually used to /// check for equality. /// </summary> /// <param name="value">Short value to start with.</param> /// <returns>IExpectation&lt;longT&gt;</returns> public static IExpectation<long> Expect(short value) { return new Expectation<long>(value); } /// <summary> /// Starts an expectation with integer value and up casts to long. Usually used to /// check for equality. /// </summary> /// <param name="value">Int value to start with.</param> /// <returns>IExpectation&lt;longT&gt;</returns> public static IExpectation<long> Expect(int value) { return new Expectation<long>(value); } /// <summary> /// Starts an expectation with integer value and up casts to long. Usually used to /// check for equality. /// </summary> /// <param name="value">Int value to start with.</param> /// <returns>IExpectation&lt;longT&gt;</returns> public static IExpectation<long> Expect(long value) { return new Expectation<long>(value); } /// <summary> /// Starts an expectation with decimal value. Usually used to check for equality. /// </summary> /// <param name="value">Int value to start with.</param> /// <returns>IExpectation&lt;longT&gt;</returns> public static IExpectation<decimal> Expect(decimal value) { return new Expectation<decimal>(value); } /// <summary> /// Starts an expectation with byte value and up casts to long. Usually used to /// check for equality. /// </summary> /// <param name="value">Byte value to start with.</param> /// <returns>IExpectation&lt;long&gt;</returns> public static IExpectation<long> Expect(byte value) { return new Expectation<long>(value); } /// <summary> /// Starts an expectation with unsigned short value and up casts to long. Usually used to /// check for equality. /// </summary> /// <param name="value">UShort value to start with.</param> /// <returns>IExpectation&lt;long&gt;</returns> public static IExpectation<long> Expect(ushort value) { return new Expectation<long>(value); } /// <summary> /// Starts an expectation with unsigned integer value and up casts to long. Usually used to /// check for equality. /// </summary> /// <param name="value">UInt value to start with.</param> /// <returns>IExpectation&lt;long&gt;</returns> public static IExpectation<long> Expect(uint value) { return new Expectation<long>(value); } /// <summary> /// Starts an expectation with float value and up casts to double. Usually used to /// check for equality. /// </summary> /// <param name="value">Float value to start with.</param> /// <returns>IExpectation&lt;double&gt;</returns> public static IExpectation<double> Expect(float value) { return new Expectation<double>(value); } /// <summary> /// Starts a string-specific expectation /// </summary> /// <param name="value">Actual value to test</param> /// <returns></returns> public static IStringExpectation Expect(string value) { return new StringExpectation(value); } /// <summary> /// Start an expectation with an action. Usually used to check /// if said action throws an exception /// </summary> /// <param name="action">Action to start with</param> /// <returns>IExpectation&lt;Action&gt;</returns> public static IActionExpectation Expect(Action action) { return new ActionExpectation(action); } /// <summary> /// Start an expectation with a Func. Usually to check /// if said action throws an exception /// </summary> /// <param name="func">Func to start the expectation with</param> /// <typeparam name="T">Return type of the Func (discarded)</typeparam> /// <returns>IExpectation&lt;Action&gt;</returns> public static IExpectation<Action> Expect<T>(Func<T> func) { return new Expectation<Action>(() => { var result = func(); if (!(result is Task taskResult)) return; taskResult.ConfigureAwait(false); try { var maxWait = NExpectEnvironment.TaskTimeoutMs; var waitCompleted = taskResult.Wait(maxWait); if (!waitCompleted) { throw new UnmetExpectationException(new[] { $"Waited {maxWait}ms for task to complete.", "If this is too short, consider adjusing environment ", $"variable {NExpectEnvironment.Variables.TASK_TIMEOUT_MS} to suit your needs. ", "If this doesn't help, please log a bug: async/await can", "be fickle" }.JoinWith(" ")); } } catch (AggregateException ex) { throw ex.InnerExceptions.First(); } }); } /// <summary> /// Starts an expectation on an IEnumerable&lt;T&gt; /// </summary> /// <param name="collection">Collection to start with</param> /// <typeparam name="T">Item type of the array</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( IEnumerable<T> collection ) { return new CollectionExpectation<T>(collection); } /// <summary> /// Starts an expectation on an IOrderedEnumerable&lt;T&gt; /// </summary> /// <param name="collection">Collection to start with</param> /// <typeparam name="T">Item type of the array</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( IOrderedEnumerable<T> collection ) { return new CollectionExpectation<T>(collection); } // Have to provide collection-specific overloads because // the Expect<T> above will be selected in preference // to any non-explicitly supported collection type /// <summary> /// Start an expectation on an Array /// </summary> /// <param name="array">Array to start with</param> /// <typeparam name="T">Item type of the array</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( T[] array ) { return new CollectionExpectation<T>(array); } /// <summary> /// Starts an expectation on a concrete List&lt;T&gt; /// </summary> /// <param name="list">List to start with</param> /// <typeparam name="T">Item type of the list</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( List<T> list ) { return new CollectionExpectation<T>(list); } /// <summary> /// Starts an expectation on an IList&lt;T&gt; /// </summary> /// <param name="list">List to start with</param> /// <typeparam name="T">Item type of the list</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( IList<T> list ) { return new CollectionExpectation<T>(list); } /// <summary> /// Starts an expectation on an IList&lt;T&gt; /// </summary> /// <param name="collection">List to start with</param> /// <typeparam name="T">Item type of the list</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( ICollection<T> collection ) { return new CollectionExpectation<T>(collection); } /// <summary> /// Starts an expectation on a concrete Queue&lt;T&gt; /// </summary> /// <param name="collection">Queue to start with</param> /// <typeparam name="T">Item type of the queue</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( Queue<T> collection ) { return new CollectionExpectation<T>(collection); } /// <summary> /// Starts an expectation on a concrete Stack&lt;T&gt; /// </summary> /// <param name="stack">Stack to start with</param> /// <typeparam name="T">Item type of the stack</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( Stack<T> stack ) { return new CollectionExpectation<T>(stack); } /// <summary> /// Starts an expectation on a concrete HashSet&lt;T&gt; /// </summary> /// <param name="hashSet">HashSet to start with</param> /// <typeparam name="T">Item type of the HashSet</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<T> Expect<T>( HashSet<T> hashSet ) { return new CollectionExpectation<T>(hashSet); } /// <summary> /// Starts an expectation on any ISet&lt;T&gt; /// </summary> /// <param name="set"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static ICollectionExpectation<T> Expect<T>( ISet<T> set ) { return new CollectionExpectation<T>(set); } /// <summary> /// Starts an expectation on a concrete KeyCollection from a Dictionary /// </summary> /// <param name="keys">KeyCollection to start with</param> /// <typeparam name="TKey">Key type of the dictionary</typeparam> /// <typeparam name="TValue">Value type of the dictionary</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<TKey> Expect<TKey, TValue>( Dictionary<TKey, TValue>.KeyCollection keys ) { return new CollectionExpectation<TKey>(keys.ToArray()); } /// <summary> /// Starts an expectation on a concrete KeyCollection from a Dictionary /// </summary> /// <param name="values">KeyCollection to start with</param> /// <typeparam name="TKey">Key type of the dictionary</typeparam> /// <typeparam name="TValue">Value type of the dictionary</typeparam> /// <returns>ICollectionExpectation&lt;T&gt;</returns> public static ICollectionExpectation<TValue> Expect<TKey, TValue>( Dictionary<TKey, TValue>.ValueCollection values ) { return new CollectionExpectation<TValue>(values.ToArray()); } /// <summary> /// Starts an expectation on a concrete Dictionary /// </summary> /// <param name="dictionary">Dictionary to start with</param> /// <typeparam name="TKey">Key type of the dictionary</typeparam> /// <typeparam name="TValue">Value type of the dictionary</typeparam> /// <returns></returns> public static ICollectionExpectation<KeyValuePair<TKey, TValue>> Expect<TKey, TValue>(Dictionary<TKey, TValue> dictionary) { dictionary?.SetMetadata(KEY_COMPARER, dictionary.Comparer); return new CollectionExpectation<KeyValuePair<TKey, TValue>>(dictionary); } /// <summary> /// Starts an expectation on a concrete Dictionary /// </summary> /// <param name="dictionary">Dictionary to start with</param> /// <typeparam name="TKey">Key type of the dictionary</typeparam> /// <typeparam name="TValue">Value type of the dictionary</typeparam> /// <returns></returns> public static ICollectionExpectation<KeyValuePair<TKey, TValue>> Expect<TKey, TValue>(SortedDictionary<TKey, TValue> dictionary) { return new CollectionExpectation<KeyValuePair<TKey, TValue>>(dictionary); } /// <summary> /// Starts an expectation on a concrete Dictionary /// </summary> /// <param name="dictionary">Dictionary to start with</param> /// <typeparam name="TKey">Key type of the dictionary</typeparam> /// <typeparam name="TValue">Value type of the dictionary</typeparam> /// <returns></returns> public static ICollectionExpectation<KeyValuePair<TKey, TValue>> Expect<TKey, TValue>(ConcurrentDictionary<TKey, TValue> dictionary) { return new CollectionExpectation<KeyValuePair<TKey, TValue>>(dictionary); } /// <summary> /// Starts an expectation on a concrete Dictionary /// </summary> /// <param name="dictionary">Dictionary to start with</param> /// <typeparam name="TKey">Key type of the dictionary</typeparam> /// <typeparam name="TValue">Value type of the dictionary</typeparam> /// <returns></returns> public static ICollectionExpectation<KeyValuePair<TKey, TValue>> Expect<TKey, TValue>(IDictionary<TKey, TValue> dictionary) { return new CollectionExpectation<KeyValuePair<TKey, TValue>>( dictionary ); } /// <summary> /// Starts an expectation on a NameValueCollection /// <param name="collection">NameValueCollection to start with</param> /// </summary> /// <returns></returns> public static ICollectionExpectation<KeyValuePair<string, string>> Expect(NameValueCollection collection) { return new CollectionExpectation<KeyValuePair<string, string>>( new DictionaryShim(collection) ); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using System.Xml.Linq; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class SDMSamplesTests : XLinqTestCase { public partial class SDM_XName : XLinqTestCase { /// <summary> /// Gets an XML qualified name for an XName, for interop. /// </summary> /// <param name="name">XName.</param> /// <returns>XmlQualifiedName.</returns> internal static XmlQualifiedName GetQName(XName name) { return new XmlQualifiedName(name.LocalName, name.Namespace.NamespaceName); } /// <summary> /// Tests trying to use an invalid name with XName.Get. /// </summary> /// <param name="contextValue"></param> /// <returns></returns> //[Variation(Desc = "NameGetInvalId")] public void NameGetInvalid() { try { XName.Get(null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } try { XName.Get(null, "foo"); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } try { XName.Get(string.Empty, "foo"); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } try { XName.Get(string.Empty); Validate.ExpectedThrow(typeof(ArgumentException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentException)); } try { XName.Get("{}"); Validate.ExpectedThrow(typeof(ArgumentException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentException)); } try { XName.Get("{foo}"); Validate.ExpectedThrow(typeof(ArgumentException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentException)); } } /// <summary> /// Tests the operators on XName. /// </summary> /// <param name="contextValue"></param> /// <returns></returns> //[Variation(Desc = "NameOperators")] public void NameOperators() { // Implicit conversion from string. XName name = (XName)(string)null; Validate.IsNull(name); name = (XName)"foo"; Validate.String(name.Namespace.NamespaceName, ""); Validate.String(name.LocalName, "foo"); name = (XName)"{bar}foo"; Validate.String(name.Namespace.NamespaceName, "bar"); Validate.String(name.LocalName, "foo"); // Conversion to XmlQualifiedName XmlQualifiedName qname = GetQName(name); Validate.String(qname.Namespace, "bar"); Validate.String(qname.Name, "foo"); // Equality, which should be based on reference equality. XName ns1 = (XName)"foo"; XName ns2 = (XName)"foo"; XName ns3 = (XName)"bar"; XName ns4 = null; Validate.IsReferenceEqual(ns1, ns2); Validate.IsNotReferenceEqual(ns1, ns3); Validate.IsNotReferenceEqual(ns2, ns3); bool b1 = ns1 == ns2; // equal bool b2 = ns1 == ns3; // not equal bool b3 = ns1 == ns4; // not equal Validate.IsEqual(b1, true); Validate.IsEqual(b2, false); Validate.IsEqual(b3, false); b1 = ns1 != ns2; // false b2 = ns1 != ns3; // true b3 = ns1 != ns4; // true Validate.IsEqual(b1, false); Validate.IsEqual(b2, true); Validate.IsEqual(b3, true); } /// <summary> /// Tests trying to use an invalid name with XNamespace.Get. /// </summary> /// <param name="contextValue"></param> /// <returns></returns> //[Variation(Desc = "NamespaceGetNull")] public void NamespaceGetNull() { try { XNamespace.Get(null); Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } } /// <summary> /// Tests the operators on XNamespace. /// </summary> /// <param name="contextValue"></param> /// <returns></returns> //[Variation(Desc = "NamespaceOperators")] public void NamespaceOperators() { // Implicit conversion from string. XNamespace ns = (XNamespace)(string)null; Validate.IsNull(ns); ns = (XNamespace)"foo"; Validate.String(ns.NamespaceName, "foo"); // Operator + XName name; try { name = (XNamespace)null + "localname"; Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } try { name = ns + (string)null; Validate.ExpectedThrow(typeof(ArgumentNullException)); } catch (Exception ex) { Validate.Catch(ex, typeof(ArgumentNullException)); } name = ns + "localname"; Validate.String(name.LocalName, "localname"); Validate.String(name.Namespace.NamespaceName, "foo"); // Equality, which should be based on reference equality. XNamespace ns1 = (XNamespace)"foo"; XNamespace ns2 = (XNamespace)"foo"; XNamespace ns3 = (XNamespace)"bar"; XNamespace ns4 = null; Validate.IsReferenceEqual(ns1, ns2); Validate.IsNotReferenceEqual(ns1, ns3); Validate.IsNotReferenceEqual(ns2, ns3); bool b1 = ns1 == ns2; // equal bool b2 = ns1 == ns3; // not equal bool b3 = ns1 == ns4; // not equal Validate.IsEqual(b1, true); Validate.IsEqual(b2, false); Validate.IsEqual(b3, false); b1 = ns1 != ns2; // false b2 = ns1 != ns3; // true b3 = ns1 != ns4; // true Validate.IsEqual(b1, false); Validate.IsEqual(b2, true); Validate.IsEqual(b3, true); } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/duration.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class DurationReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/duration.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static DurationReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90", "b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIg", "ASgFQnwKE2NvbS5nb29nbGUucHJvdG9idWZCDUR1cmF0aW9uUHJvdG9QAVoq", "Z2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYvcHR5cGVzL2R1cmF0aW9uoAEB", "ogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90", "bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Duration), global::Google.Protobuf.WellKnownTypes.Duration.Parser, new[]{ "Seconds", "Nanos" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// A Duration represents a signed, fixed-length span of time represented /// as a count of seconds and fractions of seconds at nanosecond /// resolution. It is independent of any calendar and concepts like "day" /// or "month". It is related to Timestamp in that the difference between /// two Timestamp values is a Duration and it can be added or subtracted /// from a Timestamp. Range is approximately +-10,000 years. /// /// Example 1: Compute Duration from two Timestamps in pseudo code. /// /// Timestamp start = ...; /// Timestamp end = ...; /// Duration duration = ...; /// /// duration.seconds = end.seconds - start.seconds; /// duration.nanos = end.nanos - start.nanos; /// /// if (duration.seconds &lt; 0 &amp;&amp; duration.nanos > 0) { /// duration.seconds += 1; /// duration.nanos -= 1000000000; /// } else if (durations.seconds > 0 &amp;&amp; duration.nanos &lt; 0) { /// duration.seconds -= 1; /// duration.nanos += 1000000000; /// } /// /// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. /// /// Timestamp start = ...; /// Duration duration = ...; /// Timestamp end = ...; /// /// end.seconds = start.seconds + duration.seconds; /// end.nanos = start.nanos + duration.nanos; /// /// if (end.nanos &lt; 0) { /// end.seconds -= 1; /// end.nanos += 1000000000; /// } else if (end.nanos >= 1000000000) { /// end.seconds += 1; /// end.nanos -= 1000000000; /// } /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Duration : pb::IMessage<Duration> { private static readonly pb::MessageParser<Duration> _parser = new pb::MessageParser<Duration>(() => new Duration()); public static pb::MessageParser<Duration> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Duration() { OnConstruction(); } partial void OnConstruction(); public Duration(Duration other) : this() { seconds_ = other.seconds_; nanos_ = other.nanos_; } public Duration Clone() { return new Duration(this); } /// <summary>Field number for the "seconds" field.</summary> public const int SecondsFieldNumber = 1; private long seconds_; /// <summary> /// Signed seconds of the span of time. Must be from -315,576,000,000 /// to +315,576,000,000 inclusive. /// </summary> public long Seconds { get { return seconds_; } set { seconds_ = value; } } /// <summary>Field number for the "nanos" field.</summary> public const int NanosFieldNumber = 2; private int nanos_; /// <summary> /// Signed fractions of a second at nanosecond resolution of the span /// of time. Durations less than one second are represented with a 0 /// `seconds` field and a positive or negative `nanos` field. For durations /// of one second or more, a non-zero value for the `nanos` field must be /// of the same sign as the `seconds` field. Must be from -999,999,999 /// to +999,999,999 inclusive. /// </summary> public int Nanos { get { return nanos_; } set { nanos_ = value; } } public override bool Equals(object other) { return Equals(other as Duration); } public bool Equals(Duration other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Seconds != other.Seconds) return false; if (Nanos != other.Nanos) return false; return true; } public override int GetHashCode() { int hash = 1; if (Seconds != 0L) hash ^= Seconds.GetHashCode(); if (Nanos != 0) hash ^= Nanos.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Seconds != 0L) { output.WriteRawTag(8); output.WriteInt64(Seconds); } if (Nanos != 0) { output.WriteRawTag(16); output.WriteInt32(Nanos); } } public int CalculateSize() { int size = 0; if (Seconds != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds); } if (Nanos != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos); } return size; } public void MergeFrom(Duration other) { if (other == null) { return; } if (other.Seconds != 0L) { Seconds = other.Seconds; } if (other.Nanos != 0) { Nanos = other.Nanos; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Seconds = input.ReadInt64(); break; } case 16: { Nanos = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/price_update_request.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Supply { /// <summary>Holder for reflection information generated from supply/price_update_request.proto</summary> public static partial class PriceUpdateRequestReflection { #region Descriptor /// <summary>File descriptor for supply/price_update_request.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PriceUpdateRequestReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiFzdXBwbHkvcHJpY2VfdXBkYXRlX3JlcXVlc3QucHJvdG8SEmhvbG1zLnR5", "cGVzLnN1cHBseRorc3VwcGx5L3Jvb21fdHlwZXMvcm9vbV90eXBlX2luZGlj", "YXRvci5wcm90bxofcHJpbWl0aXZlL21vbmV0YXJ5X2Ftb3VudC5wcm90bxod", "cHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUucHJvdG8iywEKElByaWNlVXBkYXRl", "UmVxdWVzdBIwCgRkYXRlGAEgASgLMiIuaG9sbXMudHlwZXMucHJpbWl0aXZl", "LlBiTG9jYWxEYXRlEkMKCXJvb21fdHlwZRgCIAEoCzIwLmhvbG1zLnR5cGVz", "LnN1cHBseS5yb29tX3R5cGVzLlJvb21UeXBlSW5kaWNhdG9yEj4KD21vbmV0", "YXJ5X2Ftb3VudBgDIAEoCzIlLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5Nb25l", "dGFyeUFtb3VudEIdWgZzdXBwbHmqAhJIT0xNUy5UeXBlcy5TdXBwbHliBnBy", "b3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.PriceUpdateRequest), global::HOLMS.Types.Supply.PriceUpdateRequest.Parser, new[]{ "Date", "RoomType", "MonetaryAmount" }, null, null, null) })); } #endregion } #region Messages public sealed partial class PriceUpdateRequest : pb::IMessage<PriceUpdateRequest> { private static readonly pb::MessageParser<PriceUpdateRequest> _parser = new pb::MessageParser<PriceUpdateRequest>(() => new PriceUpdateRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PriceUpdateRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.PriceUpdateRequestReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceUpdateRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceUpdateRequest(PriceUpdateRequest other) : this() { Date = other.date_ != null ? other.Date.Clone() : null; RoomType = other.roomType_ != null ? other.RoomType.Clone() : null; MonetaryAmount = other.monetaryAmount_ != null ? other.MonetaryAmount.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PriceUpdateRequest Clone() { return new PriceUpdateRequest(this); } /// <summary>Field number for the "date" field.</summary> public const int DateFieldNumber = 1; private global::HOLMS.Types.Primitive.PbLocalDate date_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate Date { get { return date_; } set { date_ = value; } } /// <summary>Field number for the "room_type" field.</summary> public const int RoomTypeFieldNumber = 2; private global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator roomType_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator RoomType { get { return roomType_; } set { roomType_ = value; } } /// <summary>Field number for the "monetary_amount" field.</summary> public const int MonetaryAmountFieldNumber = 3; private global::HOLMS.Types.Primitive.MonetaryAmount monetaryAmount_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount MonetaryAmount { get { return monetaryAmount_; } set { monetaryAmount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PriceUpdateRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PriceUpdateRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Date, other.Date)) return false; if (!object.Equals(RoomType, other.RoomType)) return false; if (!object.Equals(MonetaryAmount, other.MonetaryAmount)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (date_ != null) hash ^= Date.GetHashCode(); if (roomType_ != null) hash ^= RoomType.GetHashCode(); if (monetaryAmount_ != null) hash ^= MonetaryAmount.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (date_ != null) { output.WriteRawTag(10); output.WriteMessage(Date); } if (roomType_ != null) { output.WriteRawTag(18); output.WriteMessage(RoomType); } if (monetaryAmount_ != null) { output.WriteRawTag(26); output.WriteMessage(MonetaryAmount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (date_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date); } if (roomType_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType); } if (monetaryAmount_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MonetaryAmount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PriceUpdateRequest other) { if (other == null) { return; } if (other.date_ != null) { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } Date.MergeFrom(other.Date); } if (other.roomType_ != null) { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator(); } RoomType.MergeFrom(other.RoomType); } if (other.monetaryAmount_ != null) { if (monetaryAmount_ == null) { monetaryAmount_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } MonetaryAmount.MergeFrom(other.MonetaryAmount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(date_); break; } case 18: { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator(); } input.ReadMessage(roomType_); break; } case 26: { if (monetaryAmount_ == null) { monetaryAmount_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(monetaryAmount_); break; } } } } } #endregion } #endregion Designer generated code
// 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.Linq; using Xunit; namespace System.IO.Tests { public class FileStream_Read : FileSystemTest { [Fact] public void NullArrayThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { AssertExtensions.Throws<ArgumentNullException>("array", () => fs.Read(null, 0, 1)); } } [Fact] public void NegativeReadRootThrows() { Assert.Throws<UnauthorizedAccessException>(() => new FileStream(Path.GetPathRoot(Directory.GetCurrentDirectory()), FileMode.Open, FileAccess.Read)); } [Fact] public void NegativeOffsetThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => fs.Read(new byte[1], -1, 1)); // array is checked first AssertExtensions.Throws<ArgumentNullException>("array", () => fs.Read(null, -1, 1)); } } [Fact] public void NegativeCountThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => fs.Read(new byte[1], 0, -1)); // offset is checked before count AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => fs.Read(new byte[1], -1, -1)); // array is checked first AssertExtensions.Throws<ArgumentNullException>("array", () => fs.Read(null, -1, -1)); } } [Fact] public void ArrayOutOfBoundsThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { // offset out of bounds Assert.Throws<ArgumentException>(null, () => fs.Read(new byte[1], 1, 1)); // offset out of bounds for 0 count read Assert.Throws<ArgumentException>(null, () => fs.Read(new byte[1], 2, 0)); // offset out of bounds even for 0 length buffer Assert.Throws<ArgumentException>(null, () => fs.Read(new byte[0], 1, 0)); // combination offset and count out of bounds Assert.Throws<ArgumentException>(null, () => fs.Read(new byte[2], 1, 2)); // edges Assert.Throws<ArgumentException>(null, () => fs.Read(new byte[0], int.MaxValue, 0)); Assert.Throws<ArgumentException>(null, () => fs.Read(new byte[0], int.MaxValue, int.MaxValue)); } } [Fact] public void ReadDisposedThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Dispose(); Assert.Throws<ObjectDisposedException>(() => fs.Read(new byte[1], 0, 1)); // even for noop read Assert.Throws<ObjectDisposedException>(() => fs.Read(new byte[1], 0, 0)); // out of bounds checking happens first Assert.Throws<ArgumentException>(null, () => fs.Read(new byte[2], 1, 2)); // count is checked prior AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => fs.Read(new byte[1], 0, -1)); // offset is checked prior AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => fs.Read(new byte[1], -1, -1)); // array is checked first AssertExtensions.Throws<ArgumentNullException>("array", () => fs.Read(null, -1, -1)); } } [Fact] public void WriteOnlyThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<NotSupportedException>(() => fs.Read(new byte[1], 0, 1)); fs.Dispose(); // Disposed checking happens first Assert.Throws<ObjectDisposedException>(() => fs.Read(new byte[1], 0, 1)); // out of bounds checking happens first Assert.Throws<ArgumentException>(null, () => fs.Read(new byte[2], 1, 2)); // count is checked prior AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => fs.Read(new byte[1], 0, -1)); // offset is checked prior AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => fs.Read(new byte[1], -1, -1)); // array is checked first AssertExtensions.Throws<ArgumentNullException>("array", () => fs.Read(null, -1, -1)); } } [Fact] public void NoopReadsSucceed() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.Equal(0, fs.Read(new byte[0], 0, 0)); Assert.Equal(0, fs.Read(new byte[1], 0, 0)); // even though offset is out of bounds of array, this is still allowed // for the last element Assert.Equal(0, fs.Read(new byte[1], 1, 0)); Assert.Equal(0, fs.Read(new byte[2], 1, 0)); } } [Fact] public void EmptyFileReadsSucceed() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { byte[] buffer = new byte[TestBuffer.Length]; // use a recognizable pattern TestBuffer.CopyTo(buffer, 0); Assert.Equal(0, fs.Read(buffer, 0, 1)); Assert.Equal(TestBuffer, buffer); Assert.Equal(0, fs.Read(buffer, 0, buffer.Length)); Assert.Equal(TestBuffer, buffer); Assert.Equal(0, fs.Read(buffer, buffer.Length - 1, 1)); Assert.Equal(TestBuffer, buffer); Assert.Equal(0, fs.Read(buffer, buffer.Length / 2, buffer.Length - buffer.Length / 2)); Assert.Equal(TestBuffer, buffer); } } [Fact] public void ReadExistingFile() { string fileName = GetTestFilePath(); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); } using (FileStream fs = new FileStream(fileName, FileMode.Open)) { byte[] buffer = new byte[TestBuffer.Length]; Assert.Equal(TestBuffer.Length, fs.Read(buffer, 0, buffer.Length)); Assert.Equal(TestBuffer, buffer); // read with too large buffer at front of buffer fs.Position = 0; buffer = new byte[TestBuffer.Length * 2]; Assert.Equal(TestBuffer.Length, fs.Read(buffer, 0, buffer.Length)); Assert.Equal(TestBuffer, buffer.Take(TestBuffer.Length)); // Remainder of buffer should be untouched. Assert.Equal(new byte[buffer.Length - TestBuffer.Length], buffer.Skip(TestBuffer.Length)); // read with too large buffer in middle of buffer fs.Position = 0; buffer = new byte[TestBuffer.Length * 2]; Assert.Equal(TestBuffer.Length, fs.Read(buffer, 2, buffer.Length - 2)); Assert.Equal(TestBuffer, buffer.Skip(2).Take(TestBuffer.Length)); // Remainder of buffer should be untouched. Assert.Equal(new byte[2], buffer.Take(2)); Assert.Equal(new byte[buffer.Length - TestBuffer.Length - 2], buffer.Skip(2 + TestBuffer.Length)); } } } }
// // SCSharp.UI.OptionsDialog // // Authors: // Chris Toshok (toshok@gmail.com) // // Copyright 2006-2010 Chris Toshok // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Threading; using SdlDotNet.Core; using SdlDotNet.Graphics; using System.Drawing; namespace SCSharp.UI { public class SoundDialog : UIDialog { public SoundDialog (UIScreen parent, Mpq mpq) : base (parent, mpq, "glue\\Palmm", Builtins.rez_SndDlgBin) { background_path = null; } const int OK_ELEMENT_INDEX = 1; const int CANCEL_ELEMENT_INDEX = 2; protected override void ResourceLoader () { base.ResourceLoader (); for (int i = 0; i < Elements.Count; i ++) Console.WriteLine ("{0}: {1} '{2}'", i, Elements[i].Type, Elements[i].Text); Elements[OK_ELEMENT_INDEX].Activate += delegate () { if (Ok != null) Ok (); }; Elements[CANCEL_ELEMENT_INDEX].Activate += delegate () { if (Cancel != null) Cancel (); }; } public event DialogEvent Ok; public event DialogEvent Cancel; } public class SpeedDialog : UIDialog { public SpeedDialog (UIScreen parent, Mpq mpq) : base (parent, mpq, "glue\\Palmm", Builtins.rez_SpdDlgBin) { background_path = null; } const int OK_ELEMENT_INDEX = 1; const int CANCEL_ELEMENT_INDEX = 2; protected override void ResourceLoader () { base.ResourceLoader (); for (int i = 0; i < Elements.Count; i ++) Console.WriteLine ("{0}: {1} '{2}'", i, Elements[i].Type, Elements[i].Text); Elements[OK_ELEMENT_INDEX].Activate += delegate () { if (Ok != null) Ok (); }; Elements[CANCEL_ELEMENT_INDEX].Activate += delegate () { if (Cancel != null) Cancel (); }; } public event DialogEvent Ok; public event DialogEvent Cancel; } public class VideoDialog : UIDialog { public VideoDialog (UIScreen parent, Mpq mpq) : base (parent, mpq, "glue\\Palmm", Builtins.rez_VideoBin) { background_path = null; } const int OK_ELEMENT_INDEX = 1; const int CANCEL_ELEMENT_INDEX = 2; protected override void ResourceLoader () { base.ResourceLoader (); for (int i = 0; i < Elements.Count; i ++) Console.WriteLine ("{0}: {1} '{2}'", i, Elements[i].Type, Elements[i].Text); Elements[OK_ELEMENT_INDEX].Activate += delegate () { if (Ok != null) Ok (); }; Elements[CANCEL_ELEMENT_INDEX].Activate += delegate () { if (Cancel != null) Cancel (); }; } public event DialogEvent Ok; public event DialogEvent Cancel; } public class NetworkDialog : UIDialog { public NetworkDialog (UIScreen parent, Mpq mpq) : base (parent, mpq, "glue\\Palmm", Builtins.rez_NetDlgBin) { background_path = null; } const int OK_ELEMENT_INDEX = 1; const int CANCEL_ELEMENT_INDEX = 2; protected override void ResourceLoader () { base.ResourceLoader (); for (int i = 0; i < Elements.Count; i ++) Console.WriteLine ("{0}: {1} '{2}'", i, Elements[i].Type, Elements[i].Text); Elements[OK_ELEMENT_INDEX].Activate += delegate () { if (Ok != null) Ok (); }; Elements[CANCEL_ELEMENT_INDEX].Activate += delegate () { if (Cancel != null) Cancel (); }; } public event DialogEvent Ok; public event DialogEvent Cancel; } public class OptionsDialog : UIDialog { public OptionsDialog (UIScreen parent, Mpq mpq) : base (parent, mpq, "glue\\Palmm", Builtins.rez_OptionsBin) { background_path = null; } const int PREVIOUS_ELEMENT_INDEX = 1; const int SPEED_ELEMENT_INDEX = 2; const int SOUND_ELEMENT_INDEX = 3; const int VIDEO_ELEMENT_INDEX = 4; const int NETWORK_ELEMENT_INDEX = 5; protected override void ResourceLoader () { base.ResourceLoader (); Elements[SOUND_ELEMENT_INDEX].Activate += delegate () { SoundDialog d = new SoundDialog (this, mpq); d.Ok += delegate () { DismissDialog (); }; d.Cancel += delegate () { DismissDialog (); }; ShowDialog (d); }; Elements[SPEED_ELEMENT_INDEX].Activate += delegate () { SpeedDialog d = new SpeedDialog (this, mpq); d.Ok += delegate () { DismissDialog (); }; d.Cancel += delegate () { DismissDialog (); }; ShowDialog (d); }; Elements[VIDEO_ELEMENT_INDEX].Activate += delegate () { VideoDialog d = new VideoDialog (this, mpq); d.Ok += delegate () { DismissDialog (); }; d.Cancel += delegate () { DismissDialog (); }; ShowDialog (d); }; Elements[NETWORK_ELEMENT_INDEX].Activate += delegate () { NetworkDialog d = new NetworkDialog (this, mpq); d.Ok += delegate () { DismissDialog (); }; d.Cancel += delegate () { DismissDialog (); }; ShowDialog (d); }; Elements[PREVIOUS_ELEMENT_INDEX].Activate += delegate () { if (Previous != null) Previous (); }; for (int i = 0; i < Elements.Count; i ++) Console.WriteLine ("{0}: {1} '{2}'", i, Elements[i].Type, Elements[i].Text); } public event DialogEvent Previous; } }
// 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; namespace Internal.TypeSystem { public static class TypeSystemHelpers { public static bool IsWellKnownType(this TypeDesc type, WellKnownType wellKnownType) { return type == type.Context.GetWellKnownType(wellKnownType, false); } public static InstantiatedType MakeInstantiatedType(this MetadataType typeDef, Instantiation instantiation) { return typeDef.Context.GetInstantiatedType(typeDef, instantiation); } public static InstantiatedType MakeInstantiatedType(this MetadataType typeDef, params TypeDesc[] genericParameters) { return typeDef.Context.GetInstantiatedType(typeDef, new Instantiation(genericParameters)); } public static InstantiatedMethod MakeInstantiatedMethod(this MethodDesc methodDef, Instantiation instantiation) { return methodDef.Context.GetInstantiatedMethod(methodDef, instantiation); } public static InstantiatedMethod MakeInstantiatedMethod(this MethodDesc methodDef, params TypeDesc[] genericParameters) { return methodDef.Context.GetInstantiatedMethod(methodDef, new Instantiation(genericParameters)); } public static ArrayType MakeArrayType(this TypeDesc type) { return type.Context.GetArrayType(type); } /// <summary> /// Creates a multidimensional array type with the specified rank. /// To create a vector, use the <see cref="MakeArrayType(TypeDesc)"/> overload. /// </summary> public static ArrayType MakeArrayType(this TypeDesc type, int rank) { return type.Context.GetArrayType(type, rank); } public static ByRefType MakeByRefType(this TypeDesc type) { return type.Context.GetByRefType(type); } public static PointerType MakePointerType(this TypeDesc type) { return type.Context.GetPointerType(type); } public static TypeDesc GetParameterType(this TypeDesc type) { ParameterizedType paramType = (ParameterizedType) type; return paramType.ParameterType; } public static bool HasLayout(this MetadataType mdType) { return mdType.IsSequentialLayout || mdType.IsExplicitLayout; } public static LayoutInt GetElementSize(this TypeDesc type) { if (type.IsValueType) { return ((DefType)type).InstanceFieldSize; } else { return type.Context.Target.LayoutPointerSize; } } /// <summary> /// Gets the parameterless instance constructor on the specified type. To get the default constructor, use <see cref="TypeDesc.GetDefaultConstructor"/>. /// </summary> public static MethodDesc GetParameterlessConstructor(this TypeDesc type) { // TODO: Do we want check for specialname/rtspecialname? Maybe add another overload on GetMethod? var sig = new MethodSignature(0, 0, type.Context.GetWellKnownType(WellKnownType.Void), TypeDesc.EmptyTypes); return type.GetMethod(".ctor", sig); } public static bool HasExplicitOrImplicitDefaultConstructor(this TypeDesc type) { return type.IsValueType || type.GetDefaultConstructor() != null; } internal static MethodDesc FindMethodOnExactTypeWithMatchingTypicalMethod(this TypeDesc type, MethodDesc method) { MethodDesc methodTypicalDefinition = method.GetTypicalMethodDefinition(); var instantiatedType = type as InstantiatedType; if (instantiatedType != null) { Debug.Assert(instantiatedType.GetTypeDefinition() == methodTypicalDefinition.OwningType); return method.Context.GetMethodForInstantiatedType(methodTypicalDefinition, instantiatedType); } else if (type.IsArray) { Debug.Assert(method.OwningType.IsArray); return ((ArrayType)type).GetArrayMethod(((ArrayMethod)method).Kind); } else { Debug.Assert(type == methodTypicalDefinition.OwningType); return methodTypicalDefinition; } } /// <summary> /// Returns method as defined on a non-generic base class or on a base /// instantiation. /// For example, If Foo&lt;T&gt; : Bar&lt;T&gt; and overrides method M, /// if method is Bar&lt;string&gt;.M(), then this returns Bar&lt;T&gt;.M() /// but if Foo : Bar&lt;string&gt;, then this returns Bar&lt;string&gt;.M() /// </summary> /// <param name="targetType">A potentially derived type</param> /// <param name="method">A base class's virtual method</param> public static MethodDesc FindMethodOnTypeWithMatchingTypicalMethod(this TypeDesc targetType, MethodDesc method) { // If method is nongeneric and on a nongeneric type, then it is the matching method if (!method.HasInstantiation && !method.OwningType.HasInstantiation) { return method; } // Since method is an instantiation that may or may not be the same as typeExamine's hierarchy, // find a matching base class on an open type and then work from the instantiation in typeExamine's // hierarchy TypeDesc typicalTypeOfTargetMethod = method.GetTypicalMethodDefinition().OwningType; TypeDesc targetOrBase = targetType; do { TypeDesc openTargetOrBase = targetOrBase; if (openTargetOrBase is InstantiatedType) { openTargetOrBase = openTargetOrBase.GetTypeDefinition(); } if (openTargetOrBase == typicalTypeOfTargetMethod) { // Found an open match. Now find an equivalent method on the original target typeOrBase MethodDesc matchingMethod = targetOrBase.FindMethodOnExactTypeWithMatchingTypicalMethod(method); return matchingMethod; } targetOrBase = targetOrBase.BaseType; } while (targetOrBase != null); Debug.Fail("method has no related type in the type hierarchy of type"); return null; } /// <summary> /// Attempts to resolve constrained call to <paramref name="interfaceMethod"/> into a concrete non-unboxing /// method on <paramref name="constrainedType"/>. /// The ability to resolve constraint methods is affected by the degree of code sharing we are performing /// for generic code. /// </summary> /// <returns>The resolved method or null if the constraint couldn't be resolved.</returns> public static MethodDesc TryResolveConstraintMethodApprox(this TypeDesc constrainedType, TypeDesc interfaceType, MethodDesc interfaceMethod, out bool forceRuntimeLookup) { forceRuntimeLookup = false; // We can't resolve constraint calls effectively for reference types, and there's // not a lot of perf. benefit in doing it anyway. if (!constrainedType.IsValueType) { return null; } // Non-virtual methods called through constraints simply resolve to the specified method without constraint resolution. if (!interfaceMethod.IsVirtual) { return null; } MethodDesc method; MethodDesc genInterfaceMethod = interfaceMethod.GetMethodDefinition(); if (genInterfaceMethod.OwningType.IsInterface) { // Sometimes (when compiling shared generic code) // we don't have enough exact type information at JIT time // even to decide whether we will be able to resolve to an unboxed entry point... // To cope with this case we always go via the helper function if there's any // chance of this happening by checking for all interfaces which might possibly // be compatible with the call (verification will have ensured that // at least one of them will be) // Enumerate all potential interface instantiations // TODO: this code assumes no shared generics Debug.Assert(interfaceType == interfaceMethod.OwningType); method = constrainedType.ResolveInterfaceMethodToVirtualMethodOnType(genInterfaceMethod); } else if (genInterfaceMethod.IsVirtual) { method = constrainedType.FindVirtualFunctionTargetMethodOnObjectType(genInterfaceMethod); } else { // The method will be null if calling a non-virtual instance // methods on System.Object, i.e. when these are used as a constraint. method = null; } if (method == null) { // Fall back to VSD return null; } //#TryResolveConstraintMethodApprox_DoNotReturnParentMethod // Only return a method if the value type itself declares the method, // otherwise we might get a method from Object or System.ValueType if (!method.OwningType.IsValueType) { // Fall back to VSD return null; } // We've resolved the method, ignoring its generic method arguments // If the method is a generic method then go and get the instantiated descriptor if (interfaceMethod.HasInstantiation) { method = method.MakeInstantiatedMethod(interfaceMethod.Instantiation); } Debug.Assert(method != null); //assert(!pMD->IsUnboxingStub()); return method; } /// <summary> /// Retrieves the namespace qualified name of a <see cref="DefType"/>. /// </summary> public static string GetFullName(this DefType metadataType) { string ns = metadataType.Namespace; return ns.Length > 0 ? String.Concat(ns, ".", metadataType.Name) : metadataType.Name; } /// <summary> /// Retrieves all methods on a type, including the ones injected by the type system context. /// </summary> public static IEnumerable<MethodDesc> GetAllMethods(this TypeDesc type) { return type.Context.GetAllMethods(type); } public static IEnumerable<MethodDesc> EnumAllVirtualSlots(this TypeDesc type) { return type.Context.GetVirtualMethodAlgorithmForType(type).ComputeAllVirtualSlots(type); } /// <summary> /// Resolves interface method '<paramref name="interfaceMethod"/>' to a method on '<paramref name="type"/>' /// that implements the the method. /// </summary> public static MethodDesc ResolveInterfaceMethodToVirtualMethodOnType(this TypeDesc type, MethodDesc interfaceMethod) { return type.Context.GetVirtualMethodAlgorithmForType(type).ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod, type); } public static MethodDesc ResolveVariantInterfaceMethodToVirtualMethodOnType(this TypeDesc type, MethodDesc interfaceMethod) { return type.Context.GetVirtualMethodAlgorithmForType(type).ResolveVariantInterfaceMethodToVirtualMethodOnType(interfaceMethod, type); } /// <summary> /// Resolves a virtual method call. /// </summary> public static MethodDesc FindVirtualFunctionTargetMethodOnObjectType(this TypeDesc type, MethodDesc targetMethod) { return type.Context.GetVirtualMethodAlgorithmForType(type).FindVirtualFunctionTargetMethodOnObjectType(targetMethod, type); } /// <summary> /// Creates an open instantiation of a type. Given Foo&lt;T&gt;, returns Foo&lt;!0&gt;. /// If the type is not generic, returns the <paramref name="type"/>. /// </summary> public static TypeDesc InstantiateAsOpen(this TypeDesc type) { if (!type.IsGenericDefinition) { Debug.Assert(!type.HasInstantiation); return type; } TypeSystemContext context = type.Context; var inst = new TypeDesc[type.Instantiation.Length]; for (int i = 0; i < inst.Length; i++) { inst[i] = context.GetSignatureVariable(i, false); } return context.GetInstantiatedType((MetadataType)type, new Instantiation(inst)); } /// <summary> /// Creates an open instantiation of a field. Given Foo&lt;T&gt;.Field, returns /// Foo&lt;!0&gt;.Field. If the owning type is not generic, returns the <paramref name="field"/>. /// </summary> public static FieldDesc InstantiateAsOpen(this FieldDesc field) { Debug.Assert(field.GetTypicalFieldDefinition() == field); TypeDesc owner = field.OwningType; if (owner.HasInstantiation) { var instantiatedOwner = (InstantiatedType)owner.InstantiateAsOpen(); return field.Context.GetFieldForInstantiatedType(field, instantiatedOwner); } return field; } /// <summary> /// Creates an open instantiation of a method. Given Foo&lt;T&gt;.Method, returns /// Foo&lt;!0&gt;.Method. If the owning type is not generic, returns the <paramref name="method"/>. /// </summary> public static MethodDesc InstantiateAsOpen(this MethodDesc method) { Debug.Assert(method.IsMethodDefinition && !method.HasInstantiation); TypeDesc owner = method.OwningType; if (owner.HasInstantiation) { MetadataType instantiatedOwner = (MetadataType)owner.InstantiateAsOpen(); return method.Context.GetMethodForInstantiatedType(method, (InstantiatedType)instantiatedOwner); } return method; } /// <summary> /// Scan the type and its base types for an implementation of an interface method. Returns null if no /// implementation is found. /// </summary> public static MethodDesc ResolveInterfaceMethodTarget(this TypeDesc thisType, MethodDesc interfaceMethodToResolve) { Debug.Assert(interfaceMethodToResolve.OwningType.IsInterface); MethodDesc result = null; TypeDesc currentType = thisType; do { result = currentType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethodToResolve); currentType = currentType.BaseType; } while (result == null && currentType != null); return result; } public static bool ContainsSignatureVariables(this TypeDesc thisType) { switch (thisType.Category) { case TypeFlags.Array: case TypeFlags.SzArray: case TypeFlags.ByRef: case TypeFlags.Pointer: return ((ParameterizedType)thisType).ParameterType.ContainsSignatureVariables(); case TypeFlags.FunctionPointer: var fptr = (FunctionPointerType)thisType; if (fptr.Signature.ReturnType.ContainsSignatureVariables()) return true; for (int i = 0; i < fptr.Signature.Length; i++) { if (fptr.Signature[i].ContainsSignatureVariables()) return true; } return false; case TypeFlags.SignatureMethodVariable: case TypeFlags.SignatureTypeVariable: return true; case TypeFlags.GenericParameter: throw new ArgumentException(); default: Debug.Assert(thisType is DefType); foreach (TypeDesc arg in thisType.Instantiation) { if (arg.ContainsSignatureVariables()) return true; } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Add_Vector64_UInt16() { var test = new SimpleBinaryOpTest__Add_Vector64_UInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__Add_Vector64_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt16> _fld1; public Vector64<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Add_Vector64_UInt16 testClass) { var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Add_Vector64_UInt16 testClass) { fixed (Vector64<UInt16>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector64<UInt16> _clsVar1; private static Vector64<UInt16> _clsVar2; private Vector64<UInt16> _fld1; private Vector64<UInt16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Add_Vector64_UInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleBinaryOpTest__Add_Vector64_UInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Add( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Add( AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((UInt16*)(pClsVar1)), AdvSimd.LoadVector64((UInt16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Add_Vector64_UInt16(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__Add_Vector64_UInt16(); fixed (Vector64<UInt16>* pFld1 = &test._fld1) fixed (Vector64<UInt16>* pFld2 = &test._fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt16>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Add( AdvSimd.LoadVector64((UInt16*)(&test._fld1)), AdvSimd.LoadVector64((UInt16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt16> op1, Vector64<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((ushort)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ushort)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))] public sealed partial class CodeAccessorFunction : AbstractCodeElement, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2 { internal static EnvDTE.CodeFunction Create(CodeModelState state, AbstractCodeMember parent, MethodKind kind) { var newElement = new CodeAccessorFunction(state, parent, kind); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(newElement); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly MethodKind _kind; private CodeAccessorFunction(CodeModelState state, AbstractCodeMember parent, MethodKind kind) : base(state, parent.FileCodeModel) { Debug.Assert(kind == MethodKind.EventAdd || kind == MethodKind.EventRaise || kind == MethodKind.EventRemove || kind == MethodKind.PropertyGet || kind == MethodKind.PropertySet); _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _kind = kind; } private AbstractCodeMember ParentMember => _parentHandle.Value; private bool IsPropertyAccessor() => _kind == MethodKind.PropertyGet || _kind == MethodKind.PropertySet; internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } return CodeModelService.TryGetAutoPropertyExpressionBody(parentNode, out node) || CodeModelService.TryGetAccessorNode(parentNode, _kind, out node); } public override EnvDTE.vsCMElement Kind => EnvDTE.vsCMElement.vsCMElementFunction; public override object Parent => _parentHandle.Value; public override EnvDTE.CodeElements Children => EmptyCollection.Create(this.State, this); protected override string GetName() => this.ParentMember.Name; protected override void SetName(string value) => this.ParentMember.Name = value; protected override string GetFullName() => this.ParentMember.FullName; public EnvDTE.CodeElements Attributes => AttributeCollection.Create(this.State, this); public EnvDTE.vsCMAccess Access { get { var node = LookupNode(); return CodeModelService.GetAccess(node); } set { UpdateNode(FileCodeModel.UpdateAccess, value); } } public bool CanOverride { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public string Comment { get { throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public string DocComment { get { return string.Empty; } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.vsCMFunction FunctionKind { get { var methodSymbol = LookupSymbol() as IMethodSymbol; if (methodSymbol == null) { throw Exceptions.ThrowEUnexpected(); } return CodeModelService.GetFunctionKind(methodSymbol); } } public bool IsGeneric { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).IsGeneric; } else { return ((CodeEvent)this.ParentMember).IsGeneric; } } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).OverrideKind; } else { return ((CodeEvent)this.ParentMember).OverrideKind; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).OverrideKind = value; } else { ((CodeEvent)this.ParentMember).OverrideKind = value; } } } public bool IsOverloaded => false; public bool IsShared { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).IsShared; } else { return ((CodeEvent)this.ParentMember).IsShared; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).IsShared = value; } else { ((CodeEvent)this.ParentMember).IsShared = value; } } } public bool MustImplement { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).MustImplement; } else { return ((CodeEvent)this.ParentMember).MustImplement; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).MustImplement = value; } else { ((CodeEvent)this.ParentMember).MustImplement = value; } } } public EnvDTE.CodeElements Overloads => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElements Parameters { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).Parameters; } throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeTypeRef Type { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).Type; } throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } public EnvDTE.CodeParameter AddParameter(string name, object type, object position) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } public void RemoveParameter(object element) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } } }
// 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.Build.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; namespace Microsoft.DotNet.Build.Tasks { public class CreateFrameworkListFile : BuildTask { /// <summary> /// Files to extract basic information from and include in the list. /// </summary> [Required] public ITaskItem[] Files { get; set; } /// <summary> /// A list of assembly names with classification info such as Profile. A /// Profile="%(Profile)" attribute is included in the framework list for the matching Files /// item if %(Profile) contains text. /// /// If *any* FileClassifications are passed: /// /// *Every* file that ends up listed in the framework list must have a matching /// FileClassification. /// /// Additionally, every FileClassification must find exactly one File. /// /// This task fails if the conditions aren't met. This ensures the classification doesn't /// become out of date when the list of files changes. /// /// %(Identity): Assembly name (including ".dll"). /// %(Profile): List of profiles that apply, semicolon-delimited. /// %(ReferencedByDefault): Empty (default) or "true"/"false". Indicates whether this file /// should be referenced by default when the SDK uses this framework. /// </summary> public ITaskItem[] FileClassifications { get; set; } [Required] public string TargetFile { get; set; } public string[] TargetFilePrefixes { get; set; } /// <summary> /// Extra attributes to place on the root node. /// /// %(Identity): Attribute name. /// %(Value): Attribute value. /// </summary> public ITaskItem[] RootAttributes { get; set; } public override bool Execute() { XAttribute[] rootAttributes = RootAttributes ?.Select(item => new XAttribute(item.ItemSpec, item.GetMetadata("Value"))) .ToArray(); var frameworkManifest = new XElement("FileList", rootAttributes); Dictionary<string, ITaskItem> fileClassLookup = FileClassifications ?.ToDictionary( item => item.ItemSpec, item => item, StringComparer.OrdinalIgnoreCase); var usedFileClasses = new HashSet<string>(); foreach (var f in Files .Where(IsTargetPathIncluded) .Select(item => new { Item = item, Filename = Path.GetFileName(item.ItemSpec), TargetPath = item.GetMetadata("TargetPath"), AssemblyName = FileUtilities.GetAssemblyName(item.ItemSpec), FileVersion = FileUtilities.GetFileVersion(item.ItemSpec), IsNative = item.GetMetadata("IsNative") == "true", IsSymbolFile = item.GetMetadata("IsSymbolFile") == "true", IsResourceFile = item.ItemSpec .EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase) }) .Where(f => !f.IsSymbolFile && (f.Filename.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || f.IsNative)) // Remove duplicate files this task is given. .GroupBy(f => f.Item.ItemSpec) .Select(g => g.First()) // Make order stable between builds. .OrderBy(f => f.TargetPath, StringComparer.Ordinal) .ThenBy(f => f.Filename, StringComparer.Ordinal)) { string type = "Managed"; if (f.IsNative) { type = "Native"; } else if (f.IsResourceFile) { type = "Resources"; } string path = Path.Combine(f.TargetPath, f.Filename).Replace('\\', '/'); if (path.StartsWith("runtimes/")) { var pathParts = path.Split('/'); if (pathParts.Length > 1 && pathParts[1].Contains("_")) { // This file is a runtime file with a "rid" containing "_". This is assumed // to mean it's a cross-targeting tool and shouldn't be deployed in a // self-contained app. Leave it off the list. continue; } } var element = new XElement( "File", new XAttribute("Type", type), new XAttribute("Path", path)); if (f.IsResourceFile) { element.Add( new XAttribute("Culture", Path.GetFileName(Path.GetDirectoryName(path)))); } if (f.AssemblyName != null) { byte[] publicKeyToken = f.AssemblyName.GetPublicKeyToken(); string publicKeyTokenHex; if (publicKeyToken != null) { publicKeyTokenHex = BitConverter.ToString(publicKeyToken) .ToLowerInvariant() .Replace("-", ""); } else { Log.LogError($"No public key token found for assembly {f.Item.ItemSpec}"); publicKeyTokenHex = ""; } element.Add( new XAttribute("AssemblyName", f.AssemblyName.Name), new XAttribute("PublicKeyToken", publicKeyTokenHex), new XAttribute("AssemblyVersion", f.AssemblyName.Version)); } else if (!f.IsNative) { // This file isn't managed and isn't native. Leave it off the list. continue; } element.Add(new XAttribute("FileVersion", f.FileVersion)); if (fileClassLookup != null) { if (fileClassLookup.TryGetValue(f.Filename, out ITaskItem classItem)) { string profile = classItem.GetMetadata("Profile"); if (!string.IsNullOrEmpty(profile)) { element.Add(new XAttribute("Profile", profile)); } string referencedByDefault = classItem.GetMetadata("ReferencedByDefault"); if (!string.IsNullOrEmpty(referencedByDefault)) { element.Add(new XAttribute("ReferencedByDefault", referencedByDefault)); } usedFileClasses.Add(f.Filename); } else { Log.LogError($"File matches no classification: {f.Filename}"); } } frameworkManifest.Add(element); } foreach (var unused in fileClassLookup ?.Keys.Except(usedFileClasses).OrderBy(p => p) ?? Enumerable.Empty<string>()) { Log.LogError($"Classification matches no files: {unused}"); } Directory.CreateDirectory(Path.GetDirectoryName(TargetFile)); File.WriteAllText(TargetFile, frameworkManifest.ToString()); return !Log.HasLoggedErrors; } private bool IsTargetPathIncluded(ITaskItem item) { return TargetFilePrefixes ?.Any(prefix => item.GetMetadata("TargetPath")?.StartsWith(prefix) == true) ?? true; } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.IO; using System.Threading; using System.Collections; public enum Driver : int { D2XX = 0, // USB Direct driver USB = 0, VCP = 1, // Virtual COM Port }; namespace WeblinkCommunication { class Weblink { //DriverFTDI_D2XX UsbPort; DriverFTDI_VCP VcpPort; public IDLspecs IdatalinkModuleInfo; private Driver driver; public bool detected; /// <summary> /// For communication with the weblink via the Virtual COM Port (VCP) or the direct USB driver (D2XX) /// </summary> public Weblink(uint BaudRate, bool VCP) { IdatalinkModuleInfo = new IDLspecs(); if (VCP) { VcpPort = new DriverFTDI_VCP(BaudRate, IdatalinkModuleInfo.getInstance()); driver = Driver.VCP; } /* else { UsbPort = new DriverFTDI_D2XX(BaudRate, IdatalinkModuleInfo.getInstance()); driver = Driver.D2XX; } * */ } /// <summary> /// For communication with the weblink via the Virtual COM Port (VCP) or the direct USB driver (D2XX) /// </summary> public Weblink(uint BaudRate) { IdatalinkModuleInfo = new IDLspecs(); // config ComPort driver and USB driver (to use the both) VcpPort = new DriverFTDI_VCP(BaudRate, IdatalinkModuleInfo.getInstance()); //UsbPort = new DriverFTDI_D2XX(BaudRate, IdatalinkModuleInfo.getInstance()); driver = Driver.VCP; } /// <summary> /// Detect Com port and init communication with module (D2XX or VCP) /// return true if no module is detected /// </summary> public bool Init() { detected = false; // try with direct USB driver first // driver = Driver.D2XX; // detected = UsbPort.Init(); // Thread.Sleep(10); // try with Virtual Com Port if (!detected) { driver = Driver.VCP; detected = VcpPort.Init(); } // If not yet detected if (!detected) { return true; } return false; } /// <summary> /// Init communication with module on the port USB or VCP /// return true if no module is detected /// </summary> public bool Init(Driver d) { driver = d; /*if (d == Driver.D2XX) { detected = UsbPort.Init(); }*/ if (d == Driver.VCP) { detected = VcpPort.Init(); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } // If not yet detected if (!detected) { return true; } return false; } /// <summary> /// This function try to start a communication with idatalink device on the weblink /// </summary> /// <returns>true: if a communication success with the device</returns> /// <returns>false: if a error occur during the communication</returns> public bool InitModule() { /*if (driver == Driver.D2XX) { return UsbPort.InitModule(); }*/ if (driver == Driver.VCP) { return VcpPort.InitModule(); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public void WriteByte(byte[] buffer, uint timeout) { /* if (driver == Driver.D2XX) { UsbPort.WriteByte(buffer, timeout); } * */ if (driver == Driver.VCP) { VcpPort.WriteByte(buffer, (int)timeout); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public void WriteLine(string text, uint timeout) { /*if (driver == Driver.D2XX) { UsbPort.WriteLine(text, timeout); }*/ if (driver == Driver.VCP) { VcpPort.WriteLine(text, timeout); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public byte ReadByte(uint timeout) { /*if (driver == Driver.D2XX) { return UsbPort.ReadByte(timeout); }*/ if (driver == Driver.VCP) { return VcpPort.ReadByte((int)timeout); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } private string ReadLine(uint timeout) { /*if (driver == Driver.D2XX) { return UsbPort.ReadLine(timeout); }*/ if (driver == Driver.VCP) { return VcpPort.ReadLine((int)timeout); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } private void KeepModuleAlive() { /*if (driver == Driver.D2XX) { UsbPort.KeepModuleAlive(); }*/ if (driver == Driver.VCP) { VcpPort.KeepModuleAlive(); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } // Read Eeprom page public byte[] ReadEepromPage(byte page) { /*if (driver == Driver.D2XX) { return UsbPort.ReadEepromPage(page); }*/ if (driver == Driver.VCP) { return VcpPort.ReadEepromPage(page); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } /// <summary> /// Close all the SerialPort and running thread for device communication /// </summary> public void Close() { /*if (UsbPort != null) { UsbPort.Close(); }*/ VcpPort.Close(); } public void ChangeSpeed(IdlSpeed speed) { /*if (driver == Driver.D2XX) { UsbPort.ChangeSpeed(speed); }*/ if (driver == Driver.VCP) { VcpPort.ChangeSpeed(speed); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } #region LogReader /// <summary> /// Init communication for LogReader application only /// </summary> public void InitLogReader(IdlSpeed speed) { /*if (driver == Driver.D2XX) { UsbPort.InitLogReader(speed); }*/ if (driver == Driver.VCP) { VcpPort.InitLogReader(speed); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public List<byte> ReadLogBankInfo(byte Bank) { //if (driver == Driver.D2XX) { // return UsbPort.ReadLogBankInfo(Bank); } //else if (driver == Driver.VCP) { return VcpPort.ReadLogBankInfo(Bank); } // else { // throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public void EraseLogBankInfo(byte Bank) { /*if (driver == Driver.D2XX) { UsbPort.EraseLogBankInfo(Bank); }*/ if (driver == Driver.VCP) { VcpPort.EraseLogBankInfo(Bank); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public byte ReadLog2PageSize() { /*if (driver == Driver.D2XX) { return UsbPort.ReadLog2PageSize(); }*/ if (driver == Driver.VCP) { return VcpPort.ReadLog2PageSize(); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public byte ReadNbPagePerBuffer() { /*if (driver == Driver.D2XX) { return UsbPort.ReadNbPagePerBuffer(); }*/ if (driver == Driver.VCP) { return VcpPort.ReadNbPagePerBuffer(); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public List<byte> ReadFlashBuffer(byte Bank, uint BufferSize) { //if (driver == Driver.D2XX) { //return UsbPort.ReadFlashBuffer(Bank, BufferSize); } //else if (driver == Driver.VCP) { return VcpPort.ReadFlashBuffer(Bank, BufferSize); } //else { // throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public byte ReadNbBank() { /*if (driver == Driver.D2XX) { return UsbPort.ReadNbBank(); }*/ if (driver == Driver.VCP) { return VcpPort.ReadNbBank(); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public void ClearCaptureData() { VcpPort.ClearCaptureData(); } public void ExitLogMode() { /*if (driver == Driver.D2XX) { UsbPort.ExitLogMode(); }*/ if (driver == Driver.VCP) { VcpPort.ExitLogMode(); } else { throw new Exception("Invalid driver choice, must be Driver.D2XX or Driver.VCP"); } } public uint Crc_CCITT_update (uint crc, char data) { data ^= (char)(crc); data ^= (char)(data << 4); return ((((uint)data << 8) | (char)(crc>>8)) ^ (char)(data >> 4) ^ ((uint)data << 3)); } #endregion Log Reader #region LogReaderFilter public void LogReader_SetHeaderFilter(byte[] mask, byte[] tag, byte ide) { VcpPort.LogReader_SetHeaderFilter(mask, tag, ide); } public void LogReader_SetHeaderFilter(byte[] mask, byte[] tag) { VcpPort.LogReader_SetHeaderFilter(mask, tag); } public void LogReader_SetHeaderFilterOff() { VcpPort.LogReader_SetHeaderFilterOff(); } public void LogReader_SetDataFilter(byte[] mask, byte[] tag) { VcpPort.LogReader_SetDataFilter(mask, tag); } public void LogReader_SetDataFilterOff() { VcpPort.LogReader_SetDataFilterOff(); } public void LogReader_SetHeaderOnly() { VcpPort.LogReader_SetHeaderOnly(); } public byte GetProtocol() { return VcpPort.GetProtocol(); } #endregion LogReaderFilter // getter/setter // public void SetDriverType(Driver d) { this.driver = d; } public bool Detected { get { return detected; } } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using Irony.Ast; namespace Irony.Parsing { [Flags] public enum StringOptions : short { None = 0, IsChar = 0x01, AllowsDoubledQuote = 0x02, //Convert doubled start/end symbol to a single symbol; for ex. in SQL, '' -> ' AllowsLineBreak = 0x04, IsTemplate = 0x08, //Can include embedded expressions that should be evaluated on the fly; ex in Ruby: "hello #{name}" NoEscapes = 0x10, AllowsUEscapes = 0x20, AllowsXEscapes = 0x40, AllowsOctalEscapes = 0x80, AllowsAllEscapes = AllowsUEscapes | AllowsXEscapes | AllowsOctalEscapes, } //Container for settings of tempate string parser, to interpet strings having embedded values or expressions // like in Ruby: // "Hello, #{name}" // Default values match settings for Ruby strings public class StringTemplateSettings { public string StartTag = "#{"; public string EndTag = "}"; public NonTerminal ExpressionRoot; } public class StringLiteral : CompoundTerminalBase { public enum StringFlagsInternal : short { HasEscapes = 0x100, } #region StringSubType class StringSubType { internal readonly string Start, End; internal readonly StringOptions Flags; internal readonly byte Index; internal StringSubType(string start, string end, StringOptions flags, byte index) { Start = start; End = end; Flags = flags; Index = index; } internal static int LongerStartFirst(StringSubType x, StringSubType y) { try {//in case any of them is null if (x.Start.Length > y.Start.Length) return -1; } catch { } return 0; } } class StringSubTypeList : List<StringSubType> { internal void Add(string start, string end, StringOptions flags) { base.Add(new StringSubType(start, end, flags, (byte) this.Count)); } } #endregion #region constructors and initialization public StringLiteral(string name): base(name) { base.SetFlag(TermFlags.IsLiteral); } public StringLiteral(string name, string startEndSymbol, StringOptions options) : this(name) { _subtypes.Add(startEndSymbol, startEndSymbol, options); } public StringLiteral(string name, string startEndSymbol) : this(name, startEndSymbol, StringOptions.None) { } public StringLiteral(string name, string startEndSymbol, StringOptions options, Type astNodeType) : this(name, startEndSymbol, options) { base.AstConfig.NodeType = astNodeType; } public StringLiteral(string name, string startEndSymbol, StringOptions options, AstNodeCreator astNodeCreator) : this(name, startEndSymbol, options) { base.AstConfig.NodeCreator = astNodeCreator; } public void AddStartEnd(string startEndSymbol, StringOptions stringOptions) { AddStartEnd(startEndSymbol, startEndSymbol, stringOptions); } public void AddStartEnd(string startSymbol, string endSymbol, StringOptions stringOptions) { _subtypes.Add(startSymbol, endSymbol, stringOptions); } public void AddPrefix(string prefix, StringOptions flags) { base.AddPrefixFlag(prefix, (short)flags); } #endregion #region Properties/Fields private readonly StringSubTypeList _subtypes = new StringSubTypeList(); string _startSymbolsFirsts; //first chars of start-end symbols #endregion #region overrides: Init, GetFirsts, ReadBody, etc... public override void Init(GrammarData grammarData) { base.Init(grammarData); _startSymbolsFirsts = string.Empty; if (_subtypes.Count == 0) { grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrInvStrDef, this.Name); //"Error in string literal [{0}]: No start/end symbols specified." return; } //collect all start-end symbols in lists and create strings of first chars var allStartSymbols = new StringSet(); //to detect duplicate start symbols _subtypes.Sort(StringSubType.LongerStartFirst); bool isTemplate = false; foreach (StringSubType subType in _subtypes) { if (allStartSymbols.Contains(subType.Start)) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrDupStartSymbolStr, subType.Start, this.Name); //"Duplicate start symbol {0} in string literal [{1}]." allStartSymbols.Add(subType.Start); _startSymbolsFirsts += subType.Start[0].ToString(); if ((subType.Flags & StringOptions.IsTemplate) != 0) isTemplate = true; } if (!CaseSensitivePrefixesSuffixes) _startSymbolsFirsts = _startSymbolsFirsts.ToLower() + _startSymbolsFirsts.ToUpper(); //Set multiline flag foreach (StringSubType info in _subtypes) { if ((info.Flags & StringOptions.AllowsLineBreak) != 0) { SetFlag(TermFlags.IsMultiline); break; } } //For templates only if(isTemplate) { //Check that template settings object is provided var templateSettings = this.AstConfig.Data as StringTemplateSettings; if(templateSettings == null) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplNoSettings, this.Name); //"Error in string literal [{0}]: IsTemplate flag is set, but TemplateSettings is not provided." else if (templateSettings.ExpressionRoot == null) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplMissingExprRoot, this.Name); //"" else if(!Grammar.SnippetRoots.Contains(templateSettings.ExpressionRoot)) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplExprNotRoot, this.Name); //"" }//if //Create editor info if (this.EditorInfo == null) this.EditorInfo = new TokenEditorInfo(TokenType.String, TokenColor.String, TokenTriggers.None); }//method public override IList<string> GetFirsts() { StringList result = new StringList(); result.AddRange(Prefixes); //we assume that prefix is always optional, so string can start with start-end symbol foreach (char ch in _startSymbolsFirsts) result.Add(ch.ToString()); return result; } protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) { if (!details.PartialContinues) { if (!ReadStartSymbol(source, details)) return false; } return CompleteReadBody(source, details); } private bool CompleteReadBody(ISourceStream source, CompoundTokenDetails details) { bool escapeEnabled = !details.IsSet((short) StringOptions.NoEscapes); int start = source.PreviewPosition; string endQuoteSymbol = details.EndSymbol; string endQuoteDoubled = endQuoteSymbol + endQuoteSymbol; //doubled quote symbol bool lineBreakAllowed = details.IsSet((short) StringOptions.AllowsLineBreak); //1. Find the string end // first get the position of the next line break; we are interested in it to detect malformed string, // therefore do it only if linebreak is NOT allowed; if linebreak is allowed, set it to -1 (we don't care). int nlPos = lineBreakAllowed ? -1 : source.Text.IndexOf('\n', source.PreviewPosition); //fix by ashmind for EOF right after opening symbol while (true) { int endPos = source.Text.IndexOf(endQuoteSymbol, source.PreviewPosition); //Check for partial token in line-scanning mode if (endPos < 0 && details.PartialOk && lineBreakAllowed) { ProcessPartialBody(source, details); return true; } //Check for malformed string: either EndSymbol not found, or LineBreak is found before EndSymbol bool malformed = endPos < 0 || nlPos >= 0 && nlPos < endPos; if (malformed) { //Set source position for recovery: move to the next line if linebreak is not allowed. if (nlPos > 0) endPos = nlPos; if (endPos > 0) source.PreviewPosition = endPos + 1; details.Error = Resources.ErrBadStrLiteral;// "Mal-formed string literal - cannot find termination symbol."; return true; //we did find start symbol, so it is definitely string, only malformed }//if malformed if (source.EOF()) return true; //We found EndSymbol - check if it is escaped; if yes, skip it and continue search if (escapeEnabled && IsEndQuoteEscaped(source.Text, endPos)) { source.PreviewPosition = endPos + endQuoteSymbol.Length; continue; //searching for end symbol } //Check if it is doubled end symbol source.PreviewPosition = endPos; if (details.IsSet((short)StringOptions.AllowsDoubledQuote) && source.MatchSymbol(endQuoteDoubled)) { source.PreviewPosition = endPos + endQuoteDoubled.Length; continue; }//checking for doubled end symbol //Ok, this is normal endSymbol that terminates the string. // Advance source position and get out from the loop details.Body = source.Text.Substring(start, endPos - start); source.PreviewPosition = endPos + endQuoteSymbol.Length; return true; //if we come here it means we're done - we found string end. } //end of loop to find string end; } private void ProcessPartialBody(ISourceStream source, CompoundTokenDetails details) { int from = source.PreviewPosition; source.PreviewPosition = source.Text.Length; details.Body = source.Text.Substring(from, source.PreviewPosition - from); details.IsPartial = true; } protected override void InitDetails(ParsingContext context, CompoundTerminalBase.CompoundTokenDetails details) { base.InitDetails(context, details); if (context.VsLineScanState.Value != 0) { //we are continuing partial string on the next line details.Flags = context.VsLineScanState.TerminalFlags; details.SubTypeIndex = context.VsLineScanState.TokenSubType; var stringInfo = _subtypes[context.VsLineScanState.TokenSubType]; details.StartSymbol = stringInfo.Start; details.EndSymbol = stringInfo.End; } } protected override void ReadSuffix(ISourceStream source, CompoundTerminalBase.CompoundTokenDetails details) { base.ReadSuffix(source, details); //"char" type can be identified by suffix (like VB where c suffix identifies char) // in this case we have details.TypeCodes[0] == char and we need to set the IsChar flag if (details.TypeCodes != null && details.TypeCodes[0] == TypeCode.Char) details.Flags |= (int)StringOptions.IsChar; else //we may have IsChar flag set (from startEndSymbol, like in c# single quote identifies char) // in this case set type code if (details.IsSet((short) StringOptions.IsChar)) details.TypeCodes = new TypeCode[] { TypeCode.Char }; } private bool IsEndQuoteEscaped(string text, int quotePosition) { bool escaped = false; int p = quotePosition - 1; while (p > 0 && text[p] == EscapeChar) { escaped = !escaped; p--; } return escaped; } private bool ReadStartSymbol(ISourceStream source, CompoundTokenDetails details) { if (_startSymbolsFirsts.IndexOf(source.PreviewChar) < 0) return false; foreach (StringSubType subType in _subtypes) { if (!source.MatchSymbol(subType.Start)) continue; //We found start symbol details.StartSymbol = subType.Start; details.EndSymbol = subType.End; details.Flags |= (short) subType.Flags; details.SubTypeIndex = subType.Index; source.PreviewPosition += subType.Start.Length; return true; }//foreach return false; }//method //Extract the string content from lexeme, adjusts the escaped and double-end symbols protected override bool ConvertValue(CompoundTokenDetails details, ParsingContext context) { string value = details.Body; bool escapeEnabled = !details.IsSet((short)StringOptions.NoEscapes); //Fix all escapes if (escapeEnabled && value.IndexOf(EscapeChar) >= 0) { details.Flags |= (int) StringFlagsInternal.HasEscapes; string[] arr = value.Split(EscapeChar); bool ignoreNext = false; //we skip the 0 element as it is not preceeded by "\" for (int i = 1; i < arr.Length; i++) { if (ignoreNext) { ignoreNext = false; continue; } string s = arr[i]; if (string.IsNullOrEmpty(s)) { //it is "\\" - escaped escape symbol. arr[i] = @"\"; ignoreNext = true; continue; } //The char is being escaped is the first one; replace it with char in Escapes table char first = s[0]; char newFirst; if (Escapes.TryGetValue(first, out newFirst)) arr[i] = newFirst + s.Substring(1); else { arr[i] = HandleSpecialEscape(arr[i], details); }//else }//for i value = string.Join(string.Empty, arr); }// if EscapeEnabled //Check for doubled end symbol string endSymbol = details.EndSymbol; if (details.IsSet((short)StringOptions.AllowsDoubledQuote) && value.IndexOf(endSymbol) >= 0) value = value.Replace(endSymbol + endSymbol, endSymbol); if (details.IsSet((short)StringOptions.IsChar)) { if (value.Length != 1) { details.Error = Resources.ErrBadChar; //"Invalid length of char literal - should be a single character."; return false; } details.Value = value[0]; } else { details.TypeCodes = new TypeCode[] { TypeCode.String }; details.Value = value; } return true; } //Should support: \Udddddddd, \udddd, \xdddd, \N{name}, \0, \ddd (octal), protected virtual string HandleSpecialEscape(string segment, CompoundTokenDetails details) { if (string.IsNullOrEmpty(segment)) return string.Empty; int len, p; string digits; char ch; string result; char first = segment[0]; switch (first) { case 'u': case 'U': if (details.IsSet((short)StringOptions.AllowsUEscapes)) { len = (first == 'u' ? 4 : 8); if (segment.Length < len + 1) { details.Error = string.Format(Resources.ErrBadUnEscape, segment.Substring(len + 1), len);// "Invalid unicode escape ({0}), expected {1} hex digits." return segment; } digits = segment.Substring(1, len); ch = (char) Convert.ToUInt32(digits, 16); result = ch + segment.Substring(len + 1); return result; }//if break; case 'x': if (details.IsSet((short)StringOptions.AllowsXEscapes)) { //x-escape allows variable number of digits, from one to 4; let's count them p = 1; //current position while (p < 5 && p < segment.Length) { if (Strings.HexDigits.IndexOf(segment[p]) < 0) break; p++; } //p now point to char right after the last digit if (p <= 1) { details.Error = Resources.ErrBadXEscape; // @"Invalid \x escape, at least one digit expected."; return segment; } digits = segment.Substring(1, p - 1); ch = (char) Convert.ToUInt32(digits, 16); result = ch + segment.Substring(p); return result; }//if break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (details.IsSet((short)StringOptions.AllowsOctalEscapes)) { //octal escape allows variable number of digits, from one to 3; let's count them p = 0; //current position while (p < 3 && p < segment.Length) { if (Strings.OctalDigits.IndexOf(segment[p]) < 0) break; p++; } //p now point to char right after the last digit digits = segment.Substring(0, p); ch = (char)Convert.ToUInt32(digits, 8); result = ch + segment.Substring(p); return result; }//if break; }//switch details.Error = string.Format(Resources.ErrInvEscape, segment); //"Invalid escape sequence: \{0}" return segment; }//method #endregion }//class }//namespace
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Security { using System; using System.ServiceModel; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Security.Tokens; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net.Mail; using System.Xml; using System.Runtime.Serialization; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.Security.Principal; static class SctClaimSerializer { static void SerializeSid(SecurityIdentifier sid, SctClaimDictionary dictionary, XmlDictionaryWriter writer) { byte[] sidBytes = new byte[sid.BinaryLength]; sid.GetBinaryForm(sidBytes, 0); writer.WriteBase64(sidBytes, 0, sidBytes.Length); } static void WriteRightAttribute(Claim claim, SctClaimDictionary dictionary, XmlDictionaryWriter writer) { if (Rights.PossessProperty.Equals(claim.Right)) return; writer.WriteAttributeString(dictionary.Right, dictionary.EmptyString, claim.Right); } static string ReadRightAttribute(XmlDictionaryReader reader, SctClaimDictionary dictionary) { string right = reader.GetAttribute(dictionary.Right, dictionary.EmptyString); return String.IsNullOrEmpty(right) ? Rights.PossessProperty : right; } static void WriteSidAttribute(SecurityIdentifier sid, SctClaimDictionary dictionary, XmlDictionaryWriter writer) { byte[] sidBytes = new byte[sid.BinaryLength]; sid.GetBinaryForm(sidBytes, 0); writer.WriteAttributeString(dictionary.Sid, dictionary.EmptyString, Convert.ToBase64String(sidBytes)); } static SecurityIdentifier ReadSidAttribute(XmlDictionaryReader reader, SctClaimDictionary dictionary) { byte[] sidBytes = Convert.FromBase64String(reader.GetAttribute(dictionary.Sid, dictionary.EmptyString)); return new SecurityIdentifier(sidBytes, 0); } public static void SerializeClaim(Claim claim, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer) { // the order in which known claim types are checked is optimized for use patterns if (claim == null) { writer.WriteElementString(dictionary.NullValue, dictionary.EmptyString, string.Empty); return; } else if (ClaimTypes.Sid.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.WindowsSidClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); SerializeSid((SecurityIdentifier)claim.Resource, dictionary, writer); writer.WriteEndElement(); return; } else if (ClaimTypes.DenyOnlySid.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.DenyOnlySidClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); SerializeSid((SecurityIdentifier)claim.Resource, dictionary, writer); writer.WriteEndElement(); return; } else if (ClaimTypes.X500DistinguishedName.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.X500DistinguishedNameClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); byte[] rawData = ((X500DistinguishedName)claim.Resource).RawData; writer.WriteBase64(rawData, 0, rawData.Length); writer.WriteEndElement(); return; } else if (ClaimTypes.Thumbprint.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.X509ThumbprintClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); byte[] thumbprint = (byte[])claim.Resource; writer.WriteBase64(thumbprint, 0, thumbprint.Length); writer.WriteEndElement(); return; } else if (ClaimTypes.Name.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.NameClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); writer.WriteString((string)claim.Resource); writer.WriteEndElement(); return; } else if (ClaimTypes.Dns.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.DnsClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); writer.WriteString((string)claim.Resource); writer.WriteEndElement(); return; } else if (ClaimTypes.Rsa.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.RsaClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); writer.WriteString(((RSA)claim.Resource).ToXmlString(false)); writer.WriteEndElement(); return; } else if (ClaimTypes.Email.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.MailAddressClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); writer.WriteString(((MailAddress)claim.Resource).Address); writer.WriteEndElement(); return; } else if (claim == Claim.System) { writer.WriteElementString(dictionary.SystemClaim, dictionary.EmptyString, string.Empty); return; } else if (ClaimTypes.Hash.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.HashClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); byte[] hash = (byte[])claim.Resource; writer.WriteBase64(hash, 0, hash.Length); writer.WriteEndElement(); return; } else if (ClaimTypes.Spn.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.SpnClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); writer.WriteString((string)claim.Resource); writer.WriteEndElement(); return; } else if (ClaimTypes.Upn.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.UpnClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); writer.WriteString((string)claim.Resource); writer.WriteEndElement(); return; } else if (ClaimTypes.Uri.Equals(claim.ClaimType)) { writer.WriteStartElement(dictionary.UrlClaim, dictionary.EmptyString); WriteRightAttribute(claim, dictionary, writer); writer.WriteString(((Uri)claim.Resource).AbsoluteUri); writer.WriteEndElement(); return; } else { // this is an extensible claim... need to delegate to xml object serializer serializer.WriteObject(writer, claim); } } public static void SerializeClaimSet(ClaimSet claimSet, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer, XmlObjectSerializer claimSerializer) { if (claimSet is X509CertificateClaimSet) { X509CertificateClaimSet x509ClaimSet = (X509CertificateClaimSet)claimSet; writer.WriteStartElement(dictionary.X509CertificateClaimSet, dictionary.EmptyString); byte[] rawData = x509ClaimSet.X509Certificate.RawData; writer.WriteBase64(rawData, 0, rawData.Length); writer.WriteEndElement(); } else if (claimSet == ClaimSet.System) { writer.WriteElementString(dictionary.SystemClaimSet, dictionary.EmptyString, String.Empty); } else if (claimSet == ClaimSet.Windows) { writer.WriteElementString(dictionary.WindowsClaimSet, dictionary.EmptyString, String.Empty); } else if (claimSet == ClaimSet.Anonymous) { writer.WriteElementString(dictionary.AnonymousClaimSet, dictionary.EmptyString, String.Empty); } else if (claimSet is WindowsClaimSet || claimSet is DefaultClaimSet) { writer.WriteStartElement(dictionary.ClaimSet, dictionary.EmptyString); writer.WriteStartElement(dictionary.PrimaryIssuer, dictionary.EmptyString); if (claimSet.Issuer == claimSet) { writer.WriteElementString(dictionary.NullValue, dictionary.EmptyString, string.Empty); } else { SerializeClaimSet(claimSet.Issuer, dictionary, writer, serializer, claimSerializer); } writer.WriteEndElement(); foreach (Claim claim in claimSet) { writer.WriteStartElement(dictionary.Claim, dictionary.EmptyString); SerializeClaim(claim, dictionary, writer, claimSerializer); writer.WriteEndElement(); } writer.WriteEndElement(); } else { serializer.WriteObject(writer, claimSet); } } public static Claim DeserializeClaim(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer) { if (reader.IsStartElement(dictionary.NullValue, dictionary.EmptyString)) { reader.ReadElementString(); return null; } else if (reader.IsStartElement(dictionary.WindowsSidClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); byte[] sidBytes = reader.ReadContentAsBase64(); reader.ReadEndElement(); return new Claim(ClaimTypes.Sid, new SecurityIdentifier(sidBytes, 0), right); } else if (reader.IsStartElement(dictionary.DenyOnlySidClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); byte[] sidBytes = reader.ReadContentAsBase64(); reader.ReadEndElement(); return new Claim(ClaimTypes.DenyOnlySid, new SecurityIdentifier(sidBytes, 0), right); } else if (reader.IsStartElement(dictionary.X500DistinguishedNameClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); byte[] rawData = reader.ReadContentAsBase64(); reader.ReadEndElement(); return new Claim(ClaimTypes.X500DistinguishedName, new X500DistinguishedName(rawData), right); } else if (reader.IsStartElement(dictionary.X509ThumbprintClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); byte[] thumbprint = reader.ReadContentAsBase64(); reader.ReadEndElement(); return new Claim(ClaimTypes.Thumbprint, thumbprint, right); } else if (reader.IsStartElement(dictionary.NameClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); string name = reader.ReadString(); reader.ReadEndElement(); return new Claim(ClaimTypes.Name, name, right); } else if (reader.IsStartElement(dictionary.DnsClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); string dns = reader.ReadString(); reader.ReadEndElement(); return new Claim(ClaimTypes.Dns, dns, right); } else if (reader.IsStartElement(dictionary.RsaClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); string rsaXml = reader.ReadString(); reader.ReadEndElement(); System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(rsaXml); return new Claim(ClaimTypes.Rsa, rsa, right); } else if (reader.IsStartElement(dictionary.MailAddressClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); string address = reader.ReadString(); reader.ReadEndElement(); return new Claim(ClaimTypes.Email, new System.Net.Mail.MailAddress(address), right); } else if (reader.IsStartElement(dictionary.SystemClaim, dictionary.EmptyString)) { reader.ReadElementString(); return Claim.System; } else if (reader.IsStartElement(dictionary.HashClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); byte[] hash = reader.ReadContentAsBase64(); reader.ReadEndElement(); return new Claim(ClaimTypes.Hash, hash, right); } else if (reader.IsStartElement(dictionary.SpnClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); string spn = reader.ReadString(); reader.ReadEndElement(); return new Claim(ClaimTypes.Spn, spn, right); } else if (reader.IsStartElement(dictionary.UpnClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); string upn = reader.ReadString(); reader.ReadEndElement(); return new Claim(ClaimTypes.Upn, upn, right); } else if (reader.IsStartElement(dictionary.UrlClaim, dictionary.EmptyString)) { string right = ReadRightAttribute(reader, dictionary); reader.ReadStartElement(); string url = reader.ReadString(); reader.ReadEndElement(); return new Claim(ClaimTypes.Uri, new Uri(url), right); } else { return (Claim)serializer.ReadObject(reader); } } public static ClaimSet DeserializeClaimSet(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer, XmlObjectSerializer claimSerializer) { if (reader.IsStartElement(dictionary.NullValue, dictionary.EmptyString)) { reader.ReadElementString(); return null; } else if (reader.IsStartElement(dictionary.X509CertificateClaimSet, dictionary.EmptyString)) { reader.ReadStartElement(); byte[] rawData = reader.ReadContentAsBase64(); reader.ReadEndElement(); return new X509CertificateClaimSet(new X509Certificate2(rawData), false); } else if (reader.IsStartElement(dictionary.SystemClaimSet, dictionary.EmptyString)) { reader.ReadElementString(); return ClaimSet.System; } else if (reader.IsStartElement(dictionary.WindowsClaimSet, dictionary.EmptyString)) { reader.ReadElementString(); return ClaimSet.Windows; } else if (reader.IsStartElement(dictionary.AnonymousClaimSet, dictionary.EmptyString)) { reader.ReadElementString(); return ClaimSet.Anonymous; } else if (reader.IsStartElement(dictionary.ClaimSet, dictionary.EmptyString)) { ClaimSet issuer = null; List<Claim> claims = new List<Claim>(); reader.ReadStartElement(); if (reader.IsStartElement(dictionary.PrimaryIssuer, dictionary.EmptyString)) { reader.ReadStartElement(); issuer = DeserializeClaimSet(reader, dictionary, serializer, claimSerializer); reader.ReadEndElement(); } while (reader.IsStartElement()) { reader.ReadStartElement(); claims.Add(DeserializeClaim(reader, dictionary, claimSerializer)); reader.ReadEndElement(); } reader.ReadEndElement(); return issuer != null ? new DefaultClaimSet(issuer, claims) : new DefaultClaimSet(claims); } else { return (ClaimSet)serializer.ReadObject(reader); } } public static void SerializeIdentities(AuthorizationContext authContext, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer) { object obj; IList<IIdentity> identities; if (authContext.Properties.TryGetValue(SecurityUtils.Identities, out obj)) { identities = obj as IList<IIdentity>; if (identities != null && identities.Count > 0) { writer.WriteStartElement(dictionary.Identities, dictionary.EmptyString); for (int i = 0; i < identities.Count; ++i) { SerializePrimaryIdentity(identities[i], dictionary, writer, serializer); } writer.WriteEndElement(); } } } static void SerializePrimaryIdentity(IIdentity identity, SctClaimDictionary dictionary, XmlDictionaryWriter writer, XmlObjectSerializer serializer) { if (identity != null && identity != SecurityUtils.AnonymousIdentity) { writer.WriteStartElement(dictionary.PrimaryIdentity, dictionary.EmptyString); if (identity is WindowsIdentity) { WindowsIdentity wid = (WindowsIdentity)identity; writer.WriteStartElement(dictionary.WindowsSidIdentity, dictionary.EmptyString); WriteSidAttribute(wid.User, dictionary, writer); // This is to work around WOW64 bug Windows OS 1491447 string authenticationType = null; using (WindowsIdentity self = WindowsIdentity.GetCurrent()) { // is owner or admin? AuthenticationType could throw un-authorized exception if ((self.User == wid.Owner) || (wid.Owner != null && self.Groups.Contains(wid.Owner)) || (wid.Owner != SecurityUtils.AdministratorsSid && self.Groups.Contains(SecurityUtils.AdministratorsSid))) { authenticationType = wid.AuthenticationType; } } if (!String.IsNullOrEmpty(authenticationType)) writer.WriteAttributeString(dictionary.AuthenticationType, dictionary.EmptyString, authenticationType); writer.WriteString(wid.Name); writer.WriteEndElement(); } else if (identity is WindowsSidIdentity) { WindowsSidIdentity wsid = (WindowsSidIdentity)identity; writer.WriteStartElement(dictionary.WindowsSidIdentity, dictionary.EmptyString); WriteSidAttribute(wsid.SecurityIdentifier, dictionary, writer); if (!String.IsNullOrEmpty(wsid.AuthenticationType)) writer.WriteAttributeString(dictionary.AuthenticationType, dictionary.EmptyString, wsid.AuthenticationType); writer.WriteString(wsid.Name); writer.WriteEndElement(); } else if (identity is GenericIdentity) { GenericIdentity genericIdentity = (GenericIdentity)identity; writer.WriteStartElement(dictionary.GenericIdentity, dictionary.EmptyString); if (!String.IsNullOrEmpty(genericIdentity.AuthenticationType)) writer.WriteAttributeString(dictionary.AuthenticationType, dictionary.EmptyString, genericIdentity.AuthenticationType); writer.WriteString(genericIdentity.Name); writer.WriteEndElement(); } else { serializer.WriteObject(writer, identity); } writer.WriteEndElement(); } } public static IList<IIdentity> DeserializeIdentities(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer) { List<IIdentity> identities = null; if (reader.IsStartElement(dictionary.Identities, dictionary.EmptyString)) { identities = new List<IIdentity>(); reader.ReadStartElement(); while (reader.IsStartElement(dictionary.PrimaryIdentity, dictionary.EmptyString)) { IIdentity identity = DeserializePrimaryIdentity(reader, dictionary, serializer); if (identity != null && identity != SecurityUtils.AnonymousIdentity) { identities.Add(identity); } } reader.ReadEndElement(); } return identities; } static IIdentity DeserializePrimaryIdentity(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer) { IIdentity identity = null; if (reader.IsStartElement(dictionary.PrimaryIdentity, dictionary.EmptyString)) { reader.ReadStartElement(); if (reader.IsStartElement(dictionary.WindowsSidIdentity, dictionary.EmptyString)) { SecurityIdentifier sid = ReadSidAttribute(reader, dictionary); string authenticationType = reader.GetAttribute(dictionary.AuthenticationType, dictionary.EmptyString); reader.ReadStartElement(); string name = reader.ReadContentAsString(); identity = new WindowsSidIdentity(sid, name, authenticationType ?? String.Empty); reader.ReadEndElement(); } else if (reader.IsStartElement(dictionary.GenericIdentity, dictionary.EmptyString)) { string authenticationType = reader.GetAttribute(dictionary.AuthenticationType, dictionary.EmptyString); reader.ReadStartElement(); string name = reader.ReadContentAsString(); identity = SecurityUtils.CreateIdentity(name, authenticationType ?? String.Empty); reader.ReadEndElement(); } else { identity = (IIdentity)serializer.ReadObject(reader); } reader.ReadEndElement(); } return identity; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { public enum CCProgressTimerType { Radial, // Radial Counter-Clockwise Bar, // Bar } /** @brief CCProgresstimer is a subclass of CCNode. It renders the inner sprite according to the percentage. The progress can be Radial, Horizontal or vertical. @since v0.99.1 */ public class CCProgressTimer : CCNode { const int ProgressTextureCoordsCount = 4; const uint ProgressTextureCoords = 0x4b; // ProgressTextureCoords holds points {0,1} {0,0} {1,0} {1,1} we can represent it as bits // ivars bool reverseDirection; CCProgressTimerType type; float percentage; CCSprite sprite; CCPoint midpoint; CCV3F_C4B_T2F[] vertexData; short[] vertexIndices; #region Properties public CCPoint BarChangeRate { get; set; } public CCProgressTimerType Type { get { return type; } set { if (value != type) { type = value; vertexData = null; RefreshVertexIndices(); } } } public float Percentage { get { return percentage; } set { if (percentage != value) { percentage = MathHelper.Clamp(value, 0, 100); UpdateProgress(); } } } public CCSprite Sprite { get { return sprite; } set { if (sprite != value) { sprite = value; ContentSize = value.ContentSize; vertexData = null; } } } public bool ReverseDirection { get { return reverseDirection; } set { if (reverseDirection != value) { reverseDirection = value; vertexData = null; } } } public CCPoint Midpoint { get { return midpoint; } set { midpoint.X = MathHelper.Clamp(value.X, 0, 1); midpoint.Y = MathHelper.Clamp(value.Y, 0, 1); } } // Overriden properties public override CCColor3B Color { get { return Sprite.Color; } set { Sprite.Color = value; UpdateColor(); } } public override byte Opacity { get { return Sprite.Opacity; } set { Sprite.Opacity = value; UpdateColor(); } } public override bool IsColorModifiedByOpacity { get { return false; } set { } } #endregion Properties #region Constructors public CCProgressTimer(string fileName) : this(new CCSprite(fileName)) { } public CCProgressTimer(CCSprite sp) { AnchorPoint = new CCPoint(0.5f, 0.5f); Type = CCProgressTimerType.Radial; Midpoint = new CCPoint(0.5f, 0.5f); BarChangeRate = new CCPoint(1, 1); Sprite = sp; UpdateProgress(); } #endregion Constructors #region Drawing protected override void Draw() { if (vertexData != null && sprite != null) { Window.DrawManager.BindTexture(Sprite.Texture); Window.DrawManager.BlendFunc(Sprite.BlendFunc); Window.DrawManager.DrawIndexedPrimitives(PrimitiveType.TriangleList, vertexData, 0, vertexData.Length, vertexIndices, 0, vertexData.Length - 2); } } #endregion Drawing #region Vertex data CCTex2F TextureCoordFromAlphaPoint(CCPoint alpha) { CCTex2F ret = new CCTex2F(0.0f, 0.0f); if (Sprite != null) { CCV3F_C4B_T2F_Quad quad = Sprite.Quad; CCPoint min = new CCPoint (quad.BottomLeft.TexCoords.U, quad.BottomLeft.TexCoords.V); CCPoint max = new CCPoint (quad.TopRight.TexCoords.U, quad.TopRight.TexCoords.V); // Fix bug #1303 so that progress timer handles sprite frame texture rotation if (Sprite.IsTextureRectRotated) { float tmp = alpha.X; alpha.X = alpha.Y; alpha.Y = tmp; } ret = new CCTex2F(min.X * (1f - alpha.X) + max.X * alpha.X, min.Y * (1f - alpha.Y) + max.Y * alpha.Y); } return ret; } CCVertex3F VertexFromAlphaPoint(CCPoint alpha) { CCVertex3F ret = new CCVertex3F(0.0f, 0.0f, 0.0f); if (Sprite != null) { CCV3F_C4B_T2F_Quad quad = Sprite.Quad; CCPoint min = new CCPoint(quad.BottomLeft.Vertices.X, quad.BottomLeft.Vertices.Y); CCPoint max = new CCPoint(quad.TopRight.Vertices.X, quad.TopRight.Vertices.Y); ret.X = min.X * (1f - alpha.X) + max.X * alpha.X; ret.Y = min.Y * (1f - alpha.Y) + max.Y * alpha.Y; } return ret; } CCPoint BoundaryTexCoord(int index) { if (index < ProgressTextureCoordsCount) { if (ReverseDirection) { return new CCPoint((ProgressTextureCoords >> (7 - (index << 1))) & 1, (ProgressTextureCoords >> (7 - ((index << 1) + 1))) & 1); } return new CCPoint((ProgressTextureCoords >> ((index << 1) + 1)) & 1, (ProgressTextureCoords >> (index << 1)) & 1); } return CCPoint.Zero; } void UpdateProgress() { switch(Type) { case CCProgressTimerType.Radial: UpdateRadial(); RefreshVertexIndices(); UpdateColor(); break; case CCProgressTimerType.Bar: UpdateBar(); RefreshVertexIndices(); UpdateColor(); break; default: break; } } void RefreshVertexIndices() { if (vertexData != null) { int count = (vertexData.Length - 2); int i3; vertexIndices = new short[count * 3]; if (Type == CCProgressTimerType.Radial) { // Fan for (int i = 0; i < count; i++) { i3 = i * 3; vertexIndices [i3 + 0] = 0; vertexIndices [i3 + 1] = (short)(i + 1); vertexIndices [i3 + 2] = (short)(i + 2); } } else if (Type == CCProgressTimerType.Bar) { // Triangle strip for (int i = 0; i < count; i++) { i3 = i * 3; vertexIndices [i3 + 0] = (short)(i + 0); vertexIndices [i3 + 1] = (short)(i + 1); vertexIndices [i3 + 2] = (short)(i + 2); } } } } public override void UpdateColor() { if (Sprite != null && vertexData != null) { CCColor4B sc = Sprite.Quad.TopLeft.Colors; for (int i = 0; i < vertexData.Length; ++i) { vertexData[i].Colors = sc; } } } void UpdateBar() { if (Sprite == null) { return; } float alpha = Percentage / 100.0f; CCPoint alphaOffset = new CCPoint(1.0f * (1.0f - BarChangeRate.X) + alpha * BarChangeRate.X, 1.0f * (1.0f - BarChangeRate.Y) + alpha * BarChangeRate.Y) * 0.5f; CCPoint min = Midpoint - alphaOffset; CCPoint max = Midpoint + alphaOffset; if (min.X < 0f) { max.X += -min.X; min.X = 0f; } if (max.X > 1f) { min.X -= max.X - 1f; max.X = 1f; } if (min.Y < 0f) { max.Y += -min.Y; min.Y = 0f; } if (max.Y > 1f) { min.Y -= max.Y - 1f; max.Y = 1f; } if (!ReverseDirection) { if (vertexData == null) { vertexData = new CCV3F_C4B_T2F[4]; } // TOPLEFT vertexData[0].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(min.X, max.Y)); vertexData[0].Vertices = VertexFromAlphaPoint(new CCPoint(min.X, max.Y)); // BOTLEFT vertexData[1].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(min.X, min.Y)); vertexData[1].Vertices = VertexFromAlphaPoint(new CCPoint(min.X, min.Y)); // TOPRIGHT vertexData[2].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(max.X, max.Y)); vertexData[2].Vertices = VertexFromAlphaPoint(new CCPoint(max.X, max.Y)); // BOTRIGHT vertexData[3].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(max.X, min.Y)); vertexData[3].Vertices = VertexFromAlphaPoint(new CCPoint(max.X, min.Y)); } else { if (vertexData == null) { vertexData = new CCV3F_C4B_T2F[8]; // TOPLEFT 1 vertexData[0].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(0, 1)); vertexData[0].Vertices = VertexFromAlphaPoint(new CCPoint(0, 1)); // BOTLEFT 1 vertexData[1].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(0, 0)); vertexData[1].Vertices = VertexFromAlphaPoint(new CCPoint(0, 0)); // TOPRIGHT 2 vertexData[6].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(1, 1)); vertexData[6].Vertices = VertexFromAlphaPoint(new CCPoint(1, 1)); // BOTRIGHT 2 vertexData[7].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(1, 0)); vertexData[7].Vertices = VertexFromAlphaPoint(new CCPoint(1, 0)); } // TOPRIGHT 1 vertexData[2].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(min.X, max.Y)); vertexData[2].Vertices = VertexFromAlphaPoint(new CCPoint(min.X, max.Y)); // BOTRIGHT 1 vertexData[3].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(min.X, min.Y)); vertexData[3].Vertices = VertexFromAlphaPoint(new CCPoint(min.X, min.Y)); // TOPLEFT 2 vertexData[4].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(max.X, max.Y)); vertexData[4].Vertices = VertexFromAlphaPoint(new CCPoint(max.X, max.Y)); // BOTLEFT 2 vertexData[5].TexCoords = TextureCoordFromAlphaPoint(new CCPoint(max.X, min.Y)); vertexData[5].Vertices = VertexFromAlphaPoint(new CCPoint(max.X, min.Y)); } } /// // Update does the work of mapping the texture onto the triangles // It now doesn't occur the cost of free/alloc data every update cycle. // It also only changes the percentage point but no other points if they have not // been modified. // // It now deals with flipped texture. If you run into this problem, just use the // sprite property and enable the methods flipX, flipY. /// void UpdateRadial() { if (Sprite == null) { return; } float alpha = Percentage / 100f; float angle = 2f * (MathHelper.Pi) * (ReverseDirection ? alpha : 1.0f - alpha); // We find the vector to do a hit detection based on the percentage // We know the first vector is the one @ 12 o'clock (top,mid) so we rotate // from that by the progress angle around the m_tMidpoint pivot var topMid = new CCPoint(Midpoint.X, 1f); CCPoint percentagePt = CCPoint.RotateByAngle(topMid, Midpoint, angle); int index = 0; CCPoint hit; if (alpha == 0f) { // More efficient since we don't always need to check intersection // If the alpha is zero then the hit point is top mid and the index is 0. hit = topMid; index = 0; } else if (alpha == 1f) { // More efficient since we don't always need to check intersection // If the alpha is one then the hit point is top mid and the index is 4. hit = topMid; index = 4; } else { // We run a for loop checking the edges of the texture to find the // intersection point // We loop through five points since the top is split in half float min_t = float.MaxValue; for (int i = 0; i <= ProgressTextureCoordsCount; ++i) { int pIndex = (i + (ProgressTextureCoordsCount - 1)) % ProgressTextureCoordsCount; CCPoint edgePtA = BoundaryTexCoord(i % ProgressTextureCoordsCount); CCPoint edgePtB = BoundaryTexCoord(pIndex); // Remember that the top edge is split in half for the 12 o'clock position // Let's deal with that here by finding the correct endpoints if (i == 0) { edgePtB = CCPoint.Lerp(edgePtA, edgePtB, 1 - Midpoint.X); } else if (i == 4) { edgePtA = CCPoint.Lerp(edgePtA, edgePtB, 1 - Midpoint.X); } // s and t are returned by ccpLineIntersect float s = 0, t = 0; if (CCPoint.LineIntersect(edgePtA, edgePtB, Midpoint, percentagePt, ref s, ref t)) { // Since our hit test is on rays we have to deal with the top edge // being in split in half so we have to test as a segment if ((i == 0 || i == 4)) { // s represents the point between edgePtA--edgePtB if (!(0f <= s && s <= 1f)) { continue; } } // As long as our t isn't negative we are at least finding a // correct hitpoint from m_tMidpoint to percentagePt. if (t >= 0f) { // Because the percentage line and all the texture edges are // rays we should only account for the shortest intersection if (t < min_t) { min_t = t; index = i; } } } } // Now that we have the minimum magnitude we can use that to find our intersection hit = Midpoint + ((percentagePt - Midpoint) * min_t); } // The size of the vertex data is the index from the hitpoint // the 3 is for the m_tMidpoint, 12 o'clock point and hitpoint position. bool sameIndexCount = true; if (vertexData != null && vertexData.Length != index + 3) { sameIndexCount = false; vertexData = null; } if (vertexData == null) { vertexData = new CCV3F_C4B_T2F[index + 3]; } if (!sameIndexCount) { // First we populate the array with the m_tMidpoint, then all // vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint vertexData[0].TexCoords = TextureCoordFromAlphaPoint(Midpoint); vertexData[0].Vertices = VertexFromAlphaPoint(Midpoint); vertexData[1].TexCoords = TextureCoordFromAlphaPoint(topMid); vertexData[1].Vertices = VertexFromAlphaPoint(topMid); for (int i = 0; i < index; ++i) { CCPoint alphaPoint = BoundaryTexCoord(i); vertexData[i + 2].TexCoords = TextureCoordFromAlphaPoint(alphaPoint); vertexData[i + 2].Vertices = VertexFromAlphaPoint(alphaPoint); } } // hitpoint will go last vertexData[vertexData.Length - 1].TexCoords = TextureCoordFromAlphaPoint(hit); vertexData[vertexData.Length - 1].Vertices = VertexFromAlphaPoint(hit); } #endregion Vertex data } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using NLog.Common; using NLog.Conditions; using NLog.Internal; /// <summary> /// Causes a flush on a wrapped target if LogEvent satisfies the <see cref="Condition"/>. /// If condition isn't set, flushes on each write. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/AutoFlushWrapper-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/AutoFlushWrapper/NLog.config" /> /// <p> /// The above examples assume just one target and a single rule. See below for /// a programmatic configuration that's equivalent to the above config file: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/AutoFlushWrapper/Simple/Example.cs" /> /// </example> [Target("AutoFlushWrapper", IsWrapper = true)] public class AutoFlushTargetWrapper : WrapperTargetBase { /// <summary> /// Gets or sets the condition expression. Log events who meet this condition will cause /// a flush on the wrapped target. /// </summary> /// <docgen category='General Options' order='10' /> public ConditionExpression Condition { get; set; } /// <summary> /// Delay the flush until the LogEvent has been confirmed as written /// </summary> /// <remarks>If not explicitly set, then disabled by default for <see cref="BufferingTargetWrapper"/> and AsyncTaskTarget /// </remarks> /// <docgen category='General Options' order='10' /> public bool AsyncFlush { get => _asyncFlush ?? true; set => _asyncFlush = value; } private bool? _asyncFlush; /// <summary> /// Only flush when LogEvent matches condition. Ignore explicit-flush, config-reload-flush and shutdown-flush /// </summary> /// <docgen category='General Options' order='10' /> public bool FlushOnConditionOnly { get; set; } private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter(); /// <summary> /// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public AutoFlushTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="name">Name of the target</param> public AutoFlushTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public AutoFlushTargetWrapper(Target wrappedTarget) { WrappedTarget = wrappedTarget; } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); if (!_asyncFlush.HasValue && !TargetSupportsAsyncFlush(WrappedTarget)) { AsyncFlush = false; // Disable AsyncFlush, so the intended trigger works } } private static bool TargetSupportsAsyncFlush(Target wrappedTarget) { if (wrappedTarget is BufferingTargetWrapper) return false; #if !NET3_5 && !SILVERLIGHT4 if (wrappedTarget is AsyncTaskTarget) return false; #endif return true; } /// <summary> /// Forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write() /// and calls <see cref="Target.Flush(AsyncContinuation)"/> on it if LogEvent satisfies /// the flush condition or condition is null. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected override void Write(AsyncLogEventInfo logEvent) { if (Condition == null || Condition.Evaluate(logEvent.LogEvent).Equals(true)) { if (AsyncFlush) { AsyncContinuation currentContinuation = logEvent.Continuation; AsyncContinuation wrappedContinuation = (ex) => { if (ex == null) FlushOnCondition(); _pendingManualFlushList.CompleteOperation(ex); currentContinuation(ex); }; _pendingManualFlushList.BeginOperation(); WrappedTarget.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(wrappedContinuation)); } else { WrappedTarget.WriteAsyncLogEvent(logEvent); FlushOnCondition(); } } else { WrappedTarget.WriteAsyncLogEvent(logEvent); } } /// <summary> /// Schedules a flush operation, that triggers when all pending flush operations are completed (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { if (FlushOnConditionOnly) asyncContinuation(null); else FlushWrappedTarget(asyncContinuation); } private void FlushOnCondition() { if (FlushOnConditionOnly) FlushWrappedTarget((e) => { }); else FlushAsync((e) => { }); } private void FlushWrappedTarget(AsyncContinuation asyncContinuation) { var wrappedContinuation = _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation); WrappedTarget.Flush(wrappedContinuation); } /// <summary> /// Closes the target. /// </summary> protected override void CloseTarget() { _pendingManualFlushList.Clear(); // Maybe consider to wait a short while if pending requests? base.CloseTarget(); } } }
//--------------------------------------------------------------------- // <copyright file="DmlSqlGenerator.cs" company="Microsoft"> // Portions of this file copyright (c) Microsoft Corporation // and are released under the Microsoft Pulic License. See // http://archive.msdn.microsoft.com/EFSampleProvider/Project/License.aspx // or License.txt for details. // All rights reserved. // </copyright> //--------------------------------------------------------------------- namespace System.Data.SQLite { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Data; using System.Data.Common; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Core.Common.CommandTrees; /// <summary> /// Class generating SQL for a DML command tree. /// </summary> internal static class DmlSqlGenerator { private static readonly int s_commandTextBuilderInitialCapacity = 256; internal static string GenerateUpdateSql(DbUpdateCommandTree tree, out List<DbParameter> parameters) { StringBuilder commandText = new StringBuilder(s_commandTextBuilderInitialCapacity); ExpressionTranslator translator = new ExpressionTranslator(commandText, tree, null != tree.Returning, "UpdateFunction"); // update [schemaName].[tableName] commandText.Append("UPDATE "); tree.Target.Expression.Accept(translator); commandText.AppendLine(); // set c1 = ..., c2 = ..., ... bool first = true; commandText.Append("SET "); foreach (DbSetClause setClause in tree.SetClauses) { if (first) { first = false; } else { commandText.Append(", "); } setClause.Property.Accept(translator); commandText.Append(" = "); setClause.Value.Accept(translator); } if (first) { // If first is still true, it indicates there were no set // clauses. Introduce a fake set clause so that: // - we acquire the appropriate locks // - server-gen columns (e.g. timestamp) get recomputed // // We use the following pattern: // // update Foo // set @i = 0 // where ... DbParameter parameter = translator.CreateParameter(default(Int32), DbType.Int32); commandText.Append(parameter.ParameterName); commandText.Append(" = 0"); } commandText.AppendLine(); // where c1 = ..., c2 = ... commandText.Append("WHERE "); tree.Predicate.Accept(translator); commandText.AppendLine(";"); // generate returning sql GenerateReturningSql(commandText, tree, translator, tree.Returning); parameters = translator.Parameters; return commandText.ToString(); } internal static string GenerateDeleteSql(DbDeleteCommandTree tree, out List<DbParameter> parameters) { StringBuilder commandText = new StringBuilder(s_commandTextBuilderInitialCapacity); ExpressionTranslator translator = new ExpressionTranslator(commandText, tree, false, "DeleteFunction"); // delete [schemaName].[tableName] commandText.Append("DELETE FROM "); tree.Target.Expression.Accept(translator); commandText.AppendLine(); // where c1 = ... AND c2 = ... commandText.Append("WHERE "); tree.Predicate.Accept(translator); parameters = translator.Parameters; commandText.AppendLine(";"); return commandText.ToString(); } internal static string GenerateInsertSql(DbInsertCommandTree tree, out List<DbParameter> parameters) { StringBuilder commandText = new StringBuilder(s_commandTextBuilderInitialCapacity); ExpressionTranslator translator = new ExpressionTranslator(commandText, tree, null != tree.Returning, "InsertFunction"); // insert [schemaName].[tableName] commandText.Append("INSERT INTO "); tree.Target.Expression.Accept(translator); if (tree.SetClauses.Count > 0) { // (c1, c2, c3, ...) commandText.Append("("); bool first = true; foreach (DbSetClause setClause in tree.SetClauses) { if (first) { first = false; } else { commandText.Append(", "); } setClause.Property.Accept(translator); } commandText.AppendLine(")"); // values c1, c2, ... first = true; commandText.Append(" VALUES ("); foreach (DbSetClause setClause in tree.SetClauses) { if (first) { first = false; } else { commandText.Append(", "); } setClause.Value.Accept(translator); translator.RegisterMemberValue(setClause.Property, setClause.Value); } commandText.AppendLine(");"); } else // No columns specified. Insert an empty row containing default values by inserting null into the rowid { commandText.AppendLine(" DEFAULT VALUES;"); } // generate returning sql GenerateReturningSql(commandText, tree, translator, tree.Returning); parameters = translator.Parameters; return commandText.ToString(); } // Generates T-SQL describing a member // Requires: member must belong to an entity type (a safe requirement for DML // SQL gen, where we only access table columns) private static string GenerateMemberTSql(EdmMember member) { return SqlGenerator.QuoteIdentifier(member.Name); } /// <summary> /// Generates SQL fragment returning server-generated values. /// Requires: translator knows about member values so that we can figure out /// how to construct the key predicate. /// <code> /// Sample SQL: /// /// select IdentityValue /// from dbo.MyTable /// where @@ROWCOUNT > 0 and IdentityValue = scope_identity() /// /// or /// /// select TimestamptValue /// from dbo.MyTable /// where @@ROWCOUNT > 0 and Id = 1 /// /// Note that we filter on rowcount to ensure no rows are returned if no rows were modified. /// </code> /// </summary> /// <param name="commandText">Builder containing command text</param> /// <param name="tree">Modification command tree</param> /// <param name="translator">Translator used to produce DML SQL statement /// for the tree</param> /// <param name="returning">Returning expression. If null, the method returns /// immediately without producing a SELECT statement.</param> private static void GenerateReturningSql(StringBuilder commandText, DbModificationCommandTree tree, ExpressionTranslator translator, DbExpression returning) { // Nothing to do if there is no Returning expression if (null == returning) { return; } // select commandText.Append("SELECT "); returning.Accept(translator); commandText.AppendLine(); // from commandText.Append("FROM "); tree.Target.Expression.Accept(translator); commandText.AppendLine(); // where #if USE_INTEROP_DLL && INTEROP_EXTENSION_FUNCTIONS commandText.Append("WHERE last_rows_affected() > 0"); #else commandText.Append("WHERE changes() > 0"); #endif EntitySetBase table = ((DbScanExpression)tree.Target.Expression).Target; bool identity = false; foreach (EdmMember keyMember in table.ElementType.KeyMembers) { commandText.Append(" AND "); commandText.Append(GenerateMemberTSql(keyMember)); commandText.Append(" = "); // retrieve member value sql. the translator remembers member values // as it constructs the DML statement (which precedes the "returning" // SQL) DbParameter value; if (translator.MemberValues.TryGetValue(keyMember, out value)) { commandText.Append(value.ParameterName); } else { // if no value is registered for the key member, it means it is an identity // which can be retrieved using the scope_identity() function if (identity) { // there can be only one server generated key throw new NotSupportedException(string.Format("Server generated keys are only supported for identity columns. More than one key column is marked as server generated in table '{0}'.", table.Name)); } commandText.AppendLine("last_insert_rowid();"); identity = true; } } } /// <summary> /// Lightweight expression translator for DML expression trees, which have constrained /// scope and support. /// </summary> private class ExpressionTranslator : DbExpressionVisitor { /// <summary> /// Initialize a new expression translator populating the given string builder /// with command text. Command text builder and command tree must not be null. /// </summary> /// <param name="commandText">Command text with which to populate commands</param> /// <param name="commandTree">Command tree generating SQL</param> /// <param name="preserveMemberValues">Indicates whether the translator should preserve /// member values while compiling t-SQL (only needed for server generation)</param> /// <param name="kind"></param> internal ExpressionTranslator(StringBuilder commandText, DbModificationCommandTree commandTree, bool preserveMemberValues, string kind) { Debug.Assert(null != commandText); Debug.Assert(null != commandTree); _kind = kind; _commandText = commandText; _commandTree = commandTree; _parameters = new List<DbParameter>(); _memberValues = preserveMemberValues ? new Dictionary<EdmMember, DbParameter>() : null; } private readonly StringBuilder _commandText; private readonly DbModificationCommandTree _commandTree; private readonly List<DbParameter> _parameters; private readonly Dictionary<EdmMember, DbParameter> _memberValues; private int parameterNameCount = 0; private string _kind; internal List<DbParameter> Parameters { get { return _parameters; } } internal Dictionary<EdmMember, DbParameter> MemberValues { get { return _memberValues; } } // generate parameter (name based on parameter ordinal) internal SQLiteParameter CreateParameter(object value, TypeUsage type) { PrimitiveTypeKind primitiveType = MetadataHelpers.GetPrimitiveTypeKind(type); DbType dbType = MetadataHelpers.GetDbType(primitiveType); return CreateParameter(value, dbType); } // Creates a new parameter for a value in this expression translator internal SQLiteParameter CreateParameter(object value, DbType dbType) { string parameterName = string.Concat("@p", parameterNameCount.ToString(CultureInfo.InvariantCulture)); parameterNameCount++; SQLiteParameter parameter = new SQLiteParameter(parameterName, value); parameter.DbType = dbType; _parameters.Add(parameter); return parameter; } #region Basics public override void Visit(DbApplyExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionBindingPre(expression.Input); if (expression.Apply != null) { VisitExpression(expression.Apply.Expression); } VisitExpressionBindingPost(expression.Input); } public override void Visit(DbArithmeticExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionList(expression.Arguments); } public override void Visit(DbCaseExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionList(expression.When); VisitExpressionList(expression.Then); VisitExpression(expression.Else); } public override void Visit(DbCastExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbCrossJoinExpression expression) { if (expression == null) throw new ArgumentException("expression"); foreach (DbExpressionBinding binding in expression.Inputs) { VisitExpressionBindingPre(binding); } foreach (DbExpressionBinding binding2 in expression.Inputs) { VisitExpressionBindingPost(binding2); } } public override void Visit(DbDerefExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbDistinctExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbElementExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbEntityRefExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbExceptExpression expression) { VisitBinary(expression); } protected virtual void VisitBinary(DbBinaryExpression expression) { if (expression == null) throw new ArgumentException("expression"); this.VisitExpression(expression.Left); this.VisitExpression(expression.Right); } public override void Visit(DbExpression expression) { if (expression == null) throw new ArgumentException("expression"); throw new NotSupportedException("DbExpression"); } public override void Visit(DbFilterExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionBindingPre(expression.Input); VisitExpression(expression.Predicate); VisitExpressionBindingPost(expression.Input); } public override void Visit(DbFunctionExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionList(expression.Arguments); //if (expression.IsLambda) //{ // VisitLambdaFunctionPre(expression.Function, expression.LambdaBody); // VisitExpression(expression.LambdaBody); // VisitLambdaFunctionPost(expression.Function, expression.LambdaBody); //} } public override void Visit(DbGroupByExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitGroupExpressionBindingPre(expression.Input); VisitExpressionList(expression.Keys); VisitGroupExpressionBindingMid(expression.Input); VisitAggregateList(expression.Aggregates); VisitGroupExpressionBindingPost(expression.Input); } public override void Visit(DbIntersectExpression expression) { VisitBinary(expression); } public override void Visit(DbIsEmptyExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbIsOfExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbJoinExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionBindingPre(expression.Left); VisitExpressionBindingPre(expression.Right); VisitExpression(expression.JoinCondition); VisitExpressionBindingPost(expression.Left); VisitExpressionBindingPost(expression.Right); } public override void Visit(DbLikeExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpression(expression.Argument); VisitExpression(expression.Pattern); VisitExpression(expression.Escape); } public override void Visit(DbLimitExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpression(expression.Argument); VisitExpression(expression.Limit); } public override void Visit(DbOfTypeExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbParameterReferenceExpression expression) { if (expression == null) throw new ArgumentException("expression"); } public override void Visit(DbProjectExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionBindingPre(expression.Input); VisitExpression(expression.Projection); VisitExpressionBindingPost(expression.Input); } public override void Visit(DbQuantifierExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionBindingPre(expression.Input); VisitExpression(expression.Predicate); VisitExpressionBindingPost(expression.Input); } public override void Visit(DbRefExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbRefKeyExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbRelationshipNavigationExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpression(expression.NavigationSource); } public override void Visit(DbSkipExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionBindingPre(expression.Input); foreach (DbSortClause clause in expression.SortOrder) { VisitExpression(clause.Expression); } VisitExpressionBindingPost(expression.Input); VisitExpression(expression.Count); } public override void Visit(DbSortExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpressionBindingPre(expression.Input); for (int i = 0; i < expression.SortOrder.Count; i++) { VisitExpression(expression.SortOrder[i].Expression); } VisitExpressionBindingPost(expression.Input); } public override void Visit(DbTreatExpression expression) { VisitUnaryExpression(expression); } public override void Visit(DbUnionAllExpression expression) { VisitBinary(expression); } public override void Visit(DbVariableReferenceExpression expression) { if (expression == null) throw new ArgumentException("expression"); } public virtual void VisitAggregate(DbAggregate aggregate) { if (aggregate == null) throw new ArgumentException("aggregate"); VisitExpressionList(aggregate.Arguments); } public virtual void VisitAggregateList(IList<DbAggregate> aggregates) { if (aggregates == null) throw new ArgumentException("aggregates"); for (int i = 0; i < aggregates.Count; i++) { VisitAggregate(aggregates[i]); } } public virtual void VisitExpression(DbExpression expression) { if (expression == null) throw new ArgumentException("expression"); expression.Accept(this); } protected virtual void VisitExpressionBindingPost(DbExpressionBinding binding) { } protected virtual void VisitExpressionBindingPre(DbExpressionBinding binding) { if (binding == null) throw new ArgumentException("binding"); VisitExpression(binding.Expression); } public virtual void VisitExpressionList(IList<DbExpression> expressionList) { if (expressionList == null) throw new ArgumentException("expressionList"); for (int i = 0; i < expressionList.Count; i++) { VisitExpression(expressionList[i]); } } protected virtual void VisitGroupExpressionBindingMid(DbGroupExpressionBinding binding) { } protected virtual void VisitGroupExpressionBindingPost(DbGroupExpressionBinding binding) { } protected virtual void VisitGroupExpressionBindingPre(DbGroupExpressionBinding binding) { if (binding == null) throw new ArgumentException("binding"); VisitExpression(binding.Expression); } protected virtual void VisitLambdaFunctionPost(EdmFunction function, DbExpression body) { } protected virtual void VisitLambdaFunctionPre(EdmFunction function, DbExpression body) { if (function == null) throw new ArgumentException("function"); if (body == null) throw new ArgumentException("body"); } //internal virtual void VisitRelatedEntityReference(DbRelatedEntityRef relatedEntityRef) //{ // VisitExpression(relatedEntityRef.TargetEntityReference); //} //internal virtual void VisitRelatedEntityReferenceList(IList<DbRelatedEntityRef> relatedEntityReferences) //{ // for (int i = 0; i < relatedEntityReferences.Count; i++) // { // VisitRelatedEntityReference(relatedEntityReferences[i]); // } //} protected virtual void VisitUnaryExpression(DbUnaryExpression expression) { if (expression == null) throw new ArgumentException("expression"); VisitExpression(expression.Argument); } #endregion public override void Visit(DbAndExpression expression) { VisitBinary(expression, " AND "); } public override void Visit(DbOrExpression expression) { VisitBinary(expression, " OR "); } public override void Visit(DbComparisonExpression expression) { Debug.Assert(expression.ExpressionKind == DbExpressionKind.Equals, "only equals comparison expressions are produced in DML command trees in V1"); VisitBinary(expression, " = "); RegisterMemberValue(expression.Left, expression.Right); } /// <summary> /// Call this method to register a property value pair so the translator "remembers" /// the values for members of the row being modified. These values can then be used /// to form a predicate for server-generation (based on the key of the row) /// </summary> /// <param name="propertyExpression">DbExpression containing the column reference (property expression).</param> /// <param name="value">DbExpression containing the value of the column.</param> internal void RegisterMemberValue(DbExpression propertyExpression, DbExpression value) { if (null != _memberValues) { // register the value for this property Debug.Assert(propertyExpression.ExpressionKind == DbExpressionKind.Property, "DML predicates and setters must be of the form property = value"); // get name of left property EdmMember property = ((DbPropertyExpression)propertyExpression).Property; // don't track null values if (value.ExpressionKind != DbExpressionKind.Null) { Debug.Assert(value.ExpressionKind == DbExpressionKind.Constant, "value must either constant or null"); // retrieve the last parameter added (which describes the parameter) _memberValues[property] = _parameters[_parameters.Count - 1]; } } } public override void Visit(DbIsNullExpression expression) { expression.Argument.Accept(this); _commandText.Append(" IS NULL"); } public override void Visit(DbNotExpression expression) { _commandText.Append("NOT ("); expression.Accept(this); _commandText.Append(")"); } public override void Visit(DbConstantExpression expression) { SQLiteParameter parameter = CreateParameter(expression.Value, expression.ResultType); _commandText.Append(parameter.ParameterName); } public override void Visit(DbScanExpression expression) { string definingQuery = MetadataHelpers.TryGetValueForMetadataProperty<string>(expression.Target, "DefiningQuery"); if (definingQuery != null) { throw new NotSupportedException(String.Format("Unable to update the EntitySet '{0}' because it has a DefiningQuery and no <{1}> element exists in the <ModificationFunctionMapping> element to support the current operation.", expression.Target.Name, _kind)); } _commandText.Append(SqlGenerator.GetTargetTSql(expression.Target)); } public override void Visit(DbPropertyExpression expression) { _commandText.Append(GenerateMemberTSql(expression.Property)); } public override void Visit(DbNullExpression expression) { _commandText.Append("NULL"); } public override void Visit(DbNewInstanceExpression expression) { // assumes all arguments are self-describing (no need to use aliases // because no renames are ever used in the projection) bool first = true; foreach (DbExpression argument in expression.Arguments) { if (first) { first = false; } else { _commandText.Append(", "); } argument.Accept(this); } } public override void Visit(DbInExpression expression) { base.Visit(expression); } private void VisitBinary(DbBinaryExpression expression, string separator) { _commandText.Append("("); expression.Left.Accept(this); _commandText.Append(separator); expression.Right.Accept(this); _commandText.Append(")"); } } } }
/************************************************************************ * * * KinectSDK-Unity3D C# Wrapper: * * Attach to a GameObject * * * * Author: Andrew DeVine * * University of Central Florida ISUE Lab * * 2012 * * (see included BSD license for licensing information) * ************************************************************************/ using UnityEngine; using System; using System.Text; using System.Runtime.InteropServices; using System.Collections; /// <summary> /// Kinect method access /// </summary> public class KUInterface : MonoBehaviour { //public variables /// <summary> /// scales all joint positions by given amount. Do not set to zero. /// </summary> public int scaleFactor = 1000; /// <summary> /// set to true to track two skeletons /// </summary> public bool twoPlayer = false; /// <summary> /// set to false to optimize performance if RGB camera is not being used /// </summary> public bool useRGB = false; /// <summary> /// set to false to optimize performance if depth camera is not being used /// </summary> public bool useDepth = false; /// <summary> /// displays joint position data on screen /// </summary> public bool displayJointInformation = false; /// <summary> /// displays RGB texture image on screen /// </summary> public bool displayTextureImage = false; /// <summary> /// displays depth image on screen /// </summary> public bool displayDepthImage = false; //constants private const int IM_W = 640; private const int IM_H = 480; //private variables private bool NUIisReady = false; private float lastCameraAngleChange = -30.0f; private byte[] seqTex; private Color32[] cols; private Texture2D texture; private byte[] seqDepth; private Color32[] dcols; private Texture2D depthImg; private short[][] depth; /******************************************************************************** * USER METHODS -> Call these methods from your scripts * ******************************************************************************/ /// <summary> /// main joint position get function /// </summary> /// <param name="player">player number (1,2)</param> /// <param name="joint">KinectWrapper.Joints enum</param> /// <returns>position of given joint for given player</returns> public Vector3 GetJointPos(int player, KinectWrapper.Joints joint) { KinectWrapper.SkeletonTransform trans = new KinectWrapper.SkeletonTransform(); if (NUIisReady && (player == 1 || player == 2)) { KinectWrapper.GetSkeletonTransform(player, (int)joint, ref trans); return new Vector3(trans.x * scaleFactor, trans.y * scaleFactor, trans.z * scaleFactor); } else { return Vector3.zero; } } /// <summary> /// one-player overload of joint position get function /// </summary> /// <param name="joint">KinectWrapper.Joints enum</param> /// <returns>position of given joint</returns> public Vector3 GetJointPos(KinectWrapper.Joints joint) { return GetJointPos(1, joint); } /// <summary> /// gets color texture image from Kinect RGB camera /// </summary> /// <returns>RGB image</returns> public Texture2D GetTextureImage() { return this.texture; } /// <summary> /// gets depth data from Kinect depth camera /// </summary> /// <returns>2D array of pixel depths as bytes</returns> /// <remarks>depth[x=0][y=0] corresponds to top-left corner of image</remarks> public short[][] GetDepthData() { return this.depth; } /// <summary> /// returns current Kinect camera angle from horizontal /// </summary> /// <returns>camera angle from horizontal</returns> public float GetCameraAngle() { float cameraAngle = 0; KinectWrapper.GetCameraAngle(ref cameraAngle); return cameraAngle; } /// <summary> /// sets Kinect camera angle /// </summary> /// <param name="angle">range: -27 -> 27</param> /// <returns>returns true if successful</returns> /// <remarks>do not change angle more than once every 30 sec</remarks> public bool SetCameraAngle(int angle) { /* DO NOT CHANGE CAMERA ANGLE MORE OFTEN THAN ONCE * EVERY 30 SECONDS, IT COULD DAMAGE THE KINECT * SENSOR (SEE KINECT SDK DOCUMENTATION). */ if (Time.time - lastCameraAngleChange > 30 && NUIisReady) { lastCameraAngleChange = Time.time; return KinectWrapper.SetCameraAngle(angle); } else { return false; } } /******************************************************************************** * DEVICE MANAGEMENT -> initialize, uninitialize, and update sensor * ******************************************************************************/ //called on application start private void Start() { NUIisReady = false; //initialize Kinect sensor NUIisReady = KinectWrapper.NuiContextInit(twoPlayer); //display messages if (NUIisReady) Debug.Log("Sensor Initialized."); else Debug.Log("Could Not Initialize Sensor."); if (scaleFactor == 0) Debug.Log("WARNING: KUInterface.scaleFactor is set to zero. All joint positions will be the zero vector."); //set up image memory seqTex = new byte[IM_W * IM_H * 4]; cols = new Color32[IM_W * IM_H]; texture = new Texture2D(IM_W, IM_H); seqDepth = new byte[IM_W * IM_H * 2]; dcols = new Color32[IM_W * IM_H]; depthImg = new Texture2D(IM_W, IM_H); depth = new short[IM_W][]; for (int i = 0; i < depth.Length; i++) { depth[i] = new short[IM_H]; } } //called on application stop private void OnApplicationQuit() { NUIisReady = false; KinectWrapper.NuiContextUnInit(); Debug.Log("Sensor Off."); } //called every Unity frame (frame-rate dependent) private void Update() { if (NUIisReady) { //update Kinect KinectWrapper.NuiUpdate(); //update RGB texture if (useRGB) UpdateTextureImage(); //update Depth data if (useDepth) UpdateDepth(); } } //update RGB texture private void UpdateTextureImage() { int size = 0; //copy pixel data from unmanaged memory IntPtr ptr = KinectWrapper.GetTextureImage(ref size); if (ptr != IntPtr.Zero) { Marshal.Copy(ptr, seqTex, 0, size); //Debug.Log(size.ToString()); //create color matrix for (int i = 0; i < (IM_W * IM_H * 4); i += 4) { cols[(IM_W * IM_H) - (i / 4) - 1] = new Color32(seqTex[i + 2], seqTex[i + 1], seqTex[i], 255); } //set texture texture.SetPixels32(cols); texture.Apply(); } } //update Depth array and texture private void UpdateDepth() { int size = 0; //copy pixel data from unmanaged memory IntPtr ptr = KinectWrapper.GetDepthImage(ref size); if (ptr != IntPtr.Zero) { Marshal.Copy(ptr, seqDepth, 0, size); //create depth array for (int x = 0; x < IM_W; x++) { for (int y = 0; y < IM_H; y++) { depth[IM_W - x - 1][IM_H - y - 1] = BitConverter.ToInt16(seqDepth, (x*2)+(y*IM_W*2)); } } if (displayDepthImage) { //create color matrix as bytes (loops resolution) for (int x = 0; x < IM_W; x++) { for (int y = 0; y < IM_H; y++) { dcols[x + (y * IM_W)] = new Color32((byte)depth[x][y], (byte)depth[x][y], (byte)depth[x][y], 255); } } //set texture depthImg.SetPixels32(dcols); depthImg.Apply(); } } } //update function for GUI (if enabled) private void OnGUI() { if (displayJointInformation && NUIisReady) { //display joint info in upper-left corner if (twoPlayer) { for (int i = 0; i < (int)KinectWrapper.Joints.COUNT; i++) { DisplayPlayerData(1, i); DisplayPlayerData(2, i); } } else { for (int i = 0; i < (int)KinectWrapper.Joints.COUNT; i++) { DisplayPlayerData(1, i); } } } if (displayTextureImage && useRGB && NUIisReady) { //scaled to half-res GUI.DrawTexture(new Rect(600, 50, IM_W / 2, IM_H / 2), texture, ScaleMode.ScaleToFit, false); } if (displayDepthImage && useDepth && NUIisReady) { //scaled to half-res GUI.DrawTexture(new Rect(600, 300, IM_W / 2, IM_H / 2), depthImg, ScaleMode.ScaleToFit, false); } } //displays joint position data in GUI (if enabled) private void DisplayPlayerData(int player, int place) { Vector3 joint = GetJointPos(player, (KinectWrapper.Joints)place); GUI.Label(new Rect((player - 1) * 300, place * 30, 200, 30), joint.ToString()); } } //------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------ /// <summary> /// KUInterface.dll wrapper /// </summary> public class KinectWrapper { /// <summary> /// defines Kinect skeleton /// </summary> public enum Joints { HIP_CENTER = 0, SPINE, SHOULDER_CENTER, HEAD, SHOULDER_LEFT, ELBOW_LEFT, WRIST_LEFT, HAND_LEFT, SHOULDER_RIGHT, ELBOW_RIGHT, WRIST_RIGHT, HAND_RIGHT, HIP_LEFT, KNEE_LEFT, ANKLE_LEFT, FOOT_LEFT, HIP_RIGHT, KNEE_RIGHT, ANKLE_RIGHT, FOOT_RIGHT, COUNT }; [StructLayout(LayoutKind.Sequential)] public struct SkeletonTransform { public float x, y, z, w; } //NUI Context Management [DllImport("/Assets/Plugins/KUInterface.dll")] public static extern bool NuiContextInit(bool twoPlayer); [DllImport("/Assets/Plugins/KUInterface.dll")] public static extern void NuiUpdate(); [DllImport("/Assets/Plugins/KUInterface.dll")] public static extern void NuiContextUnInit(); //Get Methods [DllImport("/Assets/Plugins/KUInterface.dll")] public static extern void GetSkeletonTransform(int player, int joint, ref SkeletonTransform trans); [DllImport("/Assets/Plugins/KUInterface.dll")] public static extern IntPtr GetTextureImage(ref int size); [DllImport("/Assets/Plugins/KUInterface.dll")] public static extern IntPtr GetDepthImage(ref int size); [DllImport("/Assets/Plugins/KUInterface.dll")] public static extern void GetCameraAngle(ref float angle); //Set Methods [DllImport("/Assets/Plugins/KUInterface.dll")] public static extern bool SetCameraAngle(int angle); }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace MsgPack.Serialization.CollectionSerializers { /// <summary> /// Provides basic features for non-dictionary generic collection serializers. /// </summary> /// <typeparam name="TCollection">The type of the collection.</typeparam> /// <typeparam name="TItem">The type of the item of the collection.</typeparam> /// <remarks> /// This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility. /// If you cannot use this class, you can implement your own serializer which inherits <see cref="MessagePackSerializer{T}"/> and implements <see cref="ICollectionInstanceFactory"/>. /// </remarks> public abstract class EnumerableMessagePackSerializerBase<TCollection, TItem> : MessagePackSerializer<TCollection>, ICollectionInstanceFactory where TCollection : IEnumerable<TItem> { private readonly MessagePackSerializer<TItem> _itemSerializer; internal MessagePackSerializer<TItem> ItemSerializer { get { return this._itemSerializer; } } /// <summary> /// Initializes a new instance of the <see cref="EnumerableMessagePackSerializerBase{TCollection, TItem}"/> class. /// </summary> /// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param> /// <param name="schema"> /// The schema for collection itself or its items for the member this instance will be used to. /// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="ownerContext"/> is <c>null</c>. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] protected EnumerableMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext ) { this._itemSerializer = ownerContext.GetSerializer<TItem>( ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } /// <summary> /// Creates a new collection instance with specified initial capacity. /// </summary> /// <param name="initialCapacity"> /// The initial capacy of creating collection. /// Note that this parameter may <c>0</c> for non-empty collection. /// </param> /// <returns> /// New collection instance. This value will not be <c>null</c>. /// </returns> /// <remarks> /// An author of <see cref="Unpacker" /> could implement unpacker for non-MessagePack format, /// so implementer of this interface should not rely on that <paramref name="initialCapacity" /> reflects actual items count. /// For example, JSON unpacker cannot supply collection items count efficiently. /// </remarks> /// <seealso cref="ICollectionInstanceFactory.CreateInstance"/> protected abstract TCollection CreateInstance( int initialCapacity ); object ICollectionInstanceFactory.CreateInstance( int initialCapacity ) { return this.CreateInstance( initialCapacity ); } /// <summary> /// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param> /// <exception cref="SerializationException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="NotSupportedException"> /// <typeparamref name="TCollection"/> is not collection. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] protected internal sealed override void UnpackToCore( Unpacker unpacker, TCollection collection ) { if ( !unpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } internal void UnpackToCore( Unpacker unpacker, TCollection collection, int itemsCount ) { for ( var i = 0; i < itemsCount; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } TItem item; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { item = this._itemSerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { item = this._itemSerializer.UnpackFrom( subtreeUnpacker ); } } this.AddItem( collection, item ); } } /// <summary> /// When implemented by derive class, /// adds the deserialized item to the collection on <typeparamref name="TCollection"/> specific manner /// to implement <see cref="UnpackToCore(Unpacker,TCollection)"/>. /// </summary> /// <param name="collection">The collection to be added.</param> /// <param name="item">The item to be added.</param> /// <exception cref="NotSupportedException"> /// This implementation always throws it. /// </exception> protected virtual void AddItem( TCollection collection, TItem item ) { throw SerializationExceptions.NewUnpackToIsNotSupported( typeof( TCollection ), null ); } } #if UNITY internal abstract class UnityEnumerableMessagePackSerializerBase : NonGenericMessagePackSerializer, ICollectionInstanceFactory { private readonly IMessagePackSingleObjectSerializer _itemSerializer; internal IMessagePackSingleObjectSerializer ItemSerializer { get { return this._itemSerializer; } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] protected UnityEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, Type itemType, PolymorphismSchema schema ) : base( ownerContext, targetType ) { this._itemSerializer = ownerContext.GetSerializer( itemType, ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } protected abstract object CreateInstance( int initialCapacity ); object ICollectionInstanceFactory.CreateInstance( int initialCapacity ) { return this.CreateInstance( initialCapacity ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] protected internal sealed override void UnpackToCore( Unpacker unpacker, object collection ) { if ( !unpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } internal void UnpackToCore( Unpacker unpacker, object collection, int itemsCount ) { for ( var i = 0; i < itemsCount; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } object item; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { item = this._itemSerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { item = this._itemSerializer.UnpackFrom( subtreeUnpacker ); } } this.AddItem( collection, item ); } } protected virtual void AddItem( object collection, object item ) { throw SerializationExceptions.NewUnpackToIsNotSupported( this.TargetType, null ); } } #endif // UNITY }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Threading.Tasks; namespace Cassandra.Mapping { /// <summary> /// A client for creating, updating, deleting, and reading POCOs from a Cassandra cluster. /// </summary> /// <seealso cref="Mapper"/> public interface IMapper : ICqlQueryAsyncClient, ICqlWriteAsyncClient, ICqlQueryClient, ICqlWriteClient { /// <summary> /// Creates a new batch. /// <para> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </para> /// </summary> ICqlBatch CreateBatch(); /// <summary> /// Creates a new batch. /// <para> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </para> /// </summary> ICqlBatch CreateBatch(BatchType batchType); /// <summary> /// Executes the batch specfied synchronously. /// </summary> /// <remarks> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </remarks> void Execute(ICqlBatch batch); /// <summary> /// Executes the batch specified synchronously with the provided execution profile. /// </summary> /// <remarks> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </remarks> void Execute(ICqlBatch batch, string executionProfile); /// <summary> /// Executes the batch specified asynchronously. /// </summary> /// <remarks> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </remarks> Task ExecuteAsync(ICqlBatch batch); /// <summary> /// Executes the batch specified asynchronously with the provided execution profile. /// </summary> /// <remarks> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </remarks> Task ExecuteAsync(ICqlBatch batch, string executionProfile); /// <summary> /// Allows you to convert an argument/bind variable value being used in a CQL statement using the same converters that are being used by the client /// internally, including any user-defined conversions if you configured them. Will convert a value of Type <typeparamref name="TValue"/> to a value of /// Type <typeparamref name="TDatabase"/> or throw an InvalidOperationException if no converter is available. /// </summary> /// <typeparam name="TValue">The original Type of the value.</typeparam> /// <typeparam name="TDatabase">The Type expected by Cassandra to convert to.</typeparam> /// <param name="value">The value to convert.</param> /// <returns>The converted value.</returns> TDatabase ConvertCqlArgument<TValue, TDatabase>(TValue value); ////Execution Profiles should be included at IMapper level as they are not supported in individual statements within batches. /// <summary> /// Inserts the specified POCO in Cassandra using the provided execution profile. /// </summary> void Insert<T>(T poco, string executionProfile, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra using the provided execution profile. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="executionProfile">The execution profile to use when executing the request.</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> void Insert<T>(T poco, string executionProfile, bool insertNulls, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra using the provided execution profile. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="executionProfile">The execution profile to use when executing the request.</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="queryOptions">Optional query options</param> /// <param name="ttl">Time to live (in seconds) for the inserted values. If set, the inserted values are automatically removed /// from the database after the specified time.</param> /// <returns></returns> void Insert<T>(T poco, string executionProfile, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra using the provided execution profile. /// </summary> Task InsertAsync<T>(T poco, string executionProfile, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra using the provided execution profile. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="executionProfile">The execution profile to use when executing the request.</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="ttl">Time to live (in seconds) for the inserted values. If set, the inserted values are automatically removed /// from the database after the specified time.</param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> Task InsertAsync<T>(T poco, string executionProfile, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra using the provided execution profile. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="executionProfile">The execution profile to use when executing the request.</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> Task InsertAsync<T>(T poco, string executionProfile, bool insertNulls, CqlQueryOptions queryOptions = null); /// <summary> /// Updates the POCO specified in Cassandra using the provided execution profile. /// </summary> void Update<T>(T poco, string executionProfile, CqlQueryOptions queryOptions = null); /// <summary> /// Updates the POCO specified in Cassandra using the provided execution profile. /// </summary> Task UpdateAsync<T>(T poco, string executionProfile, CqlQueryOptions queryOptions = null); /// <summary> /// Deletes the specified POCO from Cassandra using the provided execution profile. /// </summary> void Delete<T>(T poco, string executionProfile, CqlQueryOptions queryOptions = null); /// <summary> /// Deletes the specified POCO from Cassandra using the provided execution profile. /// </summary> Task DeleteAsync<T>(T poco, string executionProfile, CqlQueryOptions queryOptions = null); ////Lightweight transaction support methods must be included at IMapper level as conditional queries are not supported in batches /// <summary> /// Deletes from the table for the POCO type specified (T) using the CQL string specified and query parameters specified. /// Prepends "DELETE FROM tablename " to the CQL statement you specify, getting the tablename appropriately from the POCO Type T. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> AppliedInfo<T> DeleteIf<T>(string cql, params object[] args); /// <summary> /// Deletes from the table for the POCO type specified (T) using the Cql query specified. /// Prepends "DELETE FROM tablename " to the CQL statement you specify, getting the tablename appropriately from the POCO Type T. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> AppliedInfo<T> DeleteIf<T>(Cql cql); /// <summary> /// Deletes from the table for the POCO type specified (T) using the CQL string specified and query parameters specified. /// Prepends "DELETE FROM tablename " to the CQL statement you specify, getting the tablename appropriately from the POCO Type T. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> Task<AppliedInfo<T>> DeleteIfAsync<T>(string cql, params object[] args); /// <summary> /// Deletes from the table for the POCO type specified (T) using the Cql query specified. /// Prepends "DELETE FROM tablename " to the CQL statement you specify, getting the tablename appropriately from the POCO Type T. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> Task<AppliedInfo<T>> DeleteIfAsync<T>(Cql cql); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> Task<AppliedInfo<T>> InsertIfNotExistsAsync<T>(T poco, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> Task<AppliedInfo<T>> InsertIfNotExistsAsync<T>(T poco, string executionProfile, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> Task<AppliedInfo<T>> InsertIfNotExistsAsync<T>(T poco, bool insertNulls, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="executionProfile">The execution profile to use when executing the request.</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> Task<AppliedInfo<T>> InsertIfNotExistsAsync<T>(T poco, string executionProfile, bool insertNulls, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="ttl">Time to live (in seconds) for the inserted values. If set, the inserted values are automatically removed /// from the database after the specified time.</param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> Task<AppliedInfo<T>> InsertIfNotExistsAsync<T>(T poco, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="executionProfile">The execution profile to use when executing the request.</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="ttl">Time to live (in seconds) for the inserted values. If set, the inserted values are automatically removed /// from the database after the specified time.</param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> Task<AppliedInfo<T>> InsertIfNotExistsAsync<T>(T poco, string executionProfile, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> AppliedInfo<T> InsertIfNotExists<T>(T poco, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> AppliedInfo<T> InsertIfNotExists<T>(T poco, string executionProfile, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> AppliedInfo<T> InsertIfNotExists<T>(T poco, bool insertNulls, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="executionProfile">The execution profile to use when executing the request.</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> AppliedInfo<T> InsertIfNotExists<T>(T poco, string executionProfile, bool insertNulls, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="ttl">Time to live (in seconds) for the inserted values. If set, the inserted values are automatically removed /// from the database after the specified time.</param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> AppliedInfo<T> InsertIfNotExists<T>(T poco, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); /// <summary> /// Inserts the specified POCO in Cassandra, if not exists, with the provided execution profile. /// </summary> /// <param name="poco">The POCO instance</param> /// <param name="executionProfile">The execution profile to use when executing the request.</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> POCO /// members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> /// <param name="ttl">Time to live (in seconds) for the inserted values. If set, the inserted values are automatically removed /// from the database after the specified time.</param> /// <param name="queryOptions">Optional query options</param> /// <returns></returns> AppliedInfo<T> InsertIfNotExists<T>(T poco, string executionProfile, bool insertNulls, int? ttl, CqlQueryOptions queryOptions = null); /// <summary> /// Updates the table for the poco type specified (T) using the CQL statement specified, using lightweight transactions. /// Prepends "UPDATE tablename" to the CQL statement you specify, getting the table name appropriately from the POCO Type T. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> AppliedInfo<T> UpdateIf<T>(Cql cql); /// <summary> /// Updates the table for the poco type specified (T) using the CQL statement specified, using lightweight transactions. /// Prepends "UPDATE tablename" to the CQL statement you specify, getting the table name appropriately from the POCO Type T. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> AppliedInfo<T> UpdateIf<T>(string cql, params object[] args); /// <summary> /// Updates the table for the poco type specified (T) using the CQL statement specified, using lightweight transactions. /// Prepends "UPDATE tablename" to the CQL statement you specify, getting the table name appropriately from the POCO Type T. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> Task<AppliedInfo<T>> UpdateIfAsync<T>(Cql cql); /// <summary> /// Updates the table for the poco type specified (T) using the CQL statement specified, using lightweight transactions. /// Prepends "UPDATE tablename" to the CQL statement you specify, getting the table name appropriately from the POCO Type T. /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// </summary> Task<AppliedInfo<T>> UpdateIfAsync<T>(string cql, params object[] args); /// <summary> /// Executes a batch that contains a Lightweight transaction. /// </summary> /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// <remarks> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </remarks> Task<AppliedInfo<T>> ExecuteConditionalAsync<T>(ICqlBatch batch); /// <summary> /// Executes a batch that contains a Lightweight transaction with the provided execution profile. /// </summary> /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// <remarks> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </remarks> Task<AppliedInfo<T>> ExecuteConditionalAsync<T>(ICqlBatch batch, string executionProfile); /// <summary> /// Executes a batch that contains a Lightweight transaction. /// </summary> /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// <remarks> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </remarks> AppliedInfo<T> ExecuteConditional<T>(ICqlBatch batch); /// <summary> /// Executes a batch that contains a Lightweight transaction. /// </summary> /// <para> /// Returns information whether it was applied or not. If it was not applied, it returns details of the existing values. /// </para> /// <remarks> /// To set the consistency level, timestamp and other batch options, use /// <see cref="ICqlBatch.WithOptions(System.Action{CqlQueryOptions})"/>. Individual options for each /// query within the batch will be ignored. /// </remarks> AppliedInfo<T> ExecuteConditional<T>(ICqlBatch batch, string executionProfile); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractSaturateByte() { var test = new SimpleBinaryOpTest__SubtractSaturateByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractSaturateByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractSaturateByte testClass) { var result = Sse2.SubtractSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractSaturateByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractSaturateByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__SubtractSaturateByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.SubtractSaturate( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.SubtractSaturate( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.SubtractSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.SubtractSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.SubtractSaturate), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.SubtractSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse2.SubtractSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.SubtractSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.SubtractSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractSaturateByte(); var result = Sse2.SubtractSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__SubtractSaturateByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.SubtractSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.SubtractSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Sse2Verify.SubtractSaturate(left[0], right[0], result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (Sse2Verify.SubtractSaturate(left[i], right[i], result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.SubtractSaturate)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Runtime.InteropServices; namespace System.Data.Odbc { internal struct SQLLEN { private IntPtr _value; internal SQLLEN(int value) { _value = new IntPtr(value); } internal SQLLEN(long value) { #if WIN32 _value = new IntPtr(checked((int)value)); #else _value = new IntPtr(value); #endif } internal SQLLEN(IntPtr value) { _value = value; } public static implicit operator SQLLEN(int value) { // return new SQLLEN(value); } public static explicit operator SQLLEN(long value) { return new SQLLEN(value); } public static unsafe implicit operator int (SQLLEN value) { // #if WIN32 return (int)value._value.ToInt32(); #else long l = (long)value._value.ToInt64(); return checked((int)l); #endif } public static unsafe explicit operator long (SQLLEN value) { return value._value.ToInt64(); } public unsafe long ToInt64() { return _value.ToInt64(); } } internal sealed class OdbcStatementHandle : OdbcHandle { internal OdbcStatementHandle(OdbcConnectionHandle connectionHandle) : base(ODBC32.SQL_HANDLE.STMT, connectionHandle) { } internal ODBC32.RetCode BindColumn2(int columnNumber, ODBC32.SQL_C targetType, HandleRef buffer, IntPtr length, IntPtr srLen_or_Ind) { ODBC32.RetCode retcode = Interop.Odbc.SQLBindCol(this, checked((ushort)columnNumber), targetType, buffer, length, srLen_or_Ind); ODBC.TraceODBC(3, "SQLBindCol", retcode); return retcode; } internal ODBC32.RetCode BindColumn3(int columnNumber, ODBC32.SQL_C targetType, IntPtr srLen_or_Ind) { ODBC32.RetCode retcode = Interop.Odbc.SQLBindCol(this, checked((ushort)columnNumber), targetType, ADP.PtrZero, ADP.PtrZero, srLen_or_Ind); ODBC.TraceODBC(3, "SQLBindCol", retcode); return retcode; } internal ODBC32.RetCode BindParameter(short ordinal, short parameterDirection, ODBC32.SQL_C sqlctype, ODBC32.SQL_TYPE sqltype, IntPtr cchSize, IntPtr scale, HandleRef buffer, IntPtr bufferLength, HandleRef intbuffer) { ODBC32.RetCode retcode = Interop.Odbc.SQLBindParameter(this, checked((ushort)ordinal), // Parameter Number parameterDirection, // InputOutputType sqlctype, // ValueType checked((short)sqltype), // ParameterType cchSize, // ColumnSize scale, // DecimalDigits buffer, // ParameterValuePtr bufferLength, // BufferLength intbuffer); // StrLen_or_IndPtr ODBC.TraceODBC(3, "SQLBindParameter", retcode); return retcode; } internal ODBC32.RetCode Cancel() { // In ODBC3.0 ... a call to SQLCancel when no processing is done has no effect at all // (ODBC Programmer's Reference ...) ODBC32.RetCode retcode = Interop.Odbc.SQLCancel(this); ODBC.TraceODBC(3, "SQLCancel", retcode); return retcode; } internal ODBC32.RetCode CloseCursor() { ODBC32.RetCode retcode = Interop.Odbc.SQLCloseCursor(this); ODBC.TraceODBC(3, "SQLCloseCursor", retcode); return retcode; } internal ODBC32.RetCode ColumnAttribute(int columnNumber, short fieldIdentifier, CNativeBuffer characterAttribute, out short stringLength, out SQLLEN numericAttribute) { IntPtr result; ODBC32.RetCode retcode = Interop.Odbc.SQLColAttributeW(this, checked((short)columnNumber), fieldIdentifier, characterAttribute, characterAttribute.ShortLength, out stringLength, out result); numericAttribute = new SQLLEN(result); ODBC.TraceODBC(3, "SQLColAttributeW", retcode); return retcode; } internal ODBC32.RetCode Columns(string tableCatalog, string tableSchema, string tableName, string columnName) { ODBC32.RetCode retcode = Interop.Odbc.SQLColumnsW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), tableName, ODBC.ShortStringLength(tableName), columnName, ODBC.ShortStringLength(columnName)); ODBC.TraceODBC(3, "SQLColumnsW", retcode); return retcode; } internal ODBC32.RetCode Execute() { ODBC32.RetCode retcode = Interop.Odbc.SQLExecute(this); ODBC.TraceODBC(3, "SQLExecute", retcode); return retcode; } internal ODBC32.RetCode ExecuteDirect(string commandText) { ODBC32.RetCode retcode = Interop.Odbc.SQLExecDirectW(this, commandText, ODBC32.SQL_NTS); ODBC.TraceODBC(3, "SQLExecDirectW", retcode); return retcode; } internal ODBC32.RetCode Fetch() { ODBC32.RetCode retcode = Interop.Odbc.SQLFetch(this); ODBC.TraceODBC(3, "SQLFetch", retcode); return retcode; } internal ODBC32.RetCode FreeStatement(ODBC32.STMT stmt) { ODBC32.RetCode retcode = Interop.Odbc.SQLFreeStmt(this, stmt); ODBC.TraceODBC(3, "SQLFreeStmt", retcode); return retcode; } internal ODBC32.RetCode GetData(int index, ODBC32.SQL_C sqlctype, CNativeBuffer buffer, int cb, out IntPtr cbActual) { ODBC32.RetCode retcode = Interop.Odbc.SQLGetData(this, checked((ushort)index), sqlctype, buffer, new IntPtr(cb), out cbActual); ODBC.TraceODBC(3, "SQLGetData", retcode); return retcode; } internal ODBC32.RetCode GetStatementAttribute(ODBC32.SQL_ATTR attribute, out IntPtr value, out int stringLength) { ODBC32.RetCode retcode = Interop.Odbc.SQLGetStmtAttrW(this, attribute, out value, ADP.PtrSize, out stringLength); ODBC.TraceODBC(3, "SQLGetStmtAttrW", retcode); return retcode; } internal ODBC32.RetCode GetTypeInfo(short fSqlType) { ODBC32.RetCode retcode = Interop.Odbc.SQLGetTypeInfo(this, fSqlType); ODBC.TraceODBC(3, "SQLGetTypeInfo", retcode); return retcode; } internal ODBC32.RetCode MoreResults() { ODBC32.RetCode retcode = Interop.Odbc.SQLMoreResults(this); ODBC.TraceODBC(3, "SQLMoreResults", retcode); return retcode; } internal ODBC32.RetCode NumberOfResultColumns(out short columnsAffected) { ODBC32.RetCode retcode = Interop.Odbc.SQLNumResultCols(this, out columnsAffected); ODBC.TraceODBC(3, "SQLNumResultCols", retcode); return retcode; } internal ODBC32.RetCode Prepare(string commandText) { ODBC32.RetCode retcode = Interop.Odbc.SQLPrepareW(this, commandText, ODBC32.SQL_NTS); ODBC.TraceODBC(3, "SQLPrepareW", retcode); return retcode; } internal ODBC32.RetCode PrimaryKeys(string catalogName, string schemaName, string tableName) { ODBC32.RetCode retcode = Interop.Odbc.SQLPrimaryKeysW(this, catalogName, ODBC.ShortStringLength(catalogName), // CatalogName schemaName, ODBC.ShortStringLength(schemaName), // SchemaName tableName, ODBC.ShortStringLength(tableName) // TableName ); ODBC.TraceODBC(3, "SQLPrimaryKeysW", retcode); return retcode; } internal ODBC32.RetCode Procedures(string procedureCatalog, string procedureSchema, string procedureName) { ODBC32.RetCode retcode = Interop.Odbc.SQLProceduresW(this, procedureCatalog, ODBC.ShortStringLength(procedureCatalog), procedureSchema, ODBC.ShortStringLength(procedureSchema), procedureName, ODBC.ShortStringLength(procedureName)); ODBC.TraceODBC(3, "SQLProceduresW", retcode); return retcode; } internal ODBC32.RetCode ProcedureColumns(string procedureCatalog, string procedureSchema, string procedureName, string columnName) { ODBC32.RetCode retcode = Interop.Odbc.SQLProcedureColumnsW(this, procedureCatalog, ODBC.ShortStringLength(procedureCatalog), procedureSchema, ODBC.ShortStringLength(procedureSchema), procedureName, ODBC.ShortStringLength(procedureName), columnName, ODBC.ShortStringLength(columnName)); ODBC.TraceODBC(3, "SQLProcedureColumnsW", retcode); return retcode; } internal ODBC32.RetCode RowCount(out SQLLEN rowCount) { IntPtr result; ODBC32.RetCode retcode = Interop.Odbc.SQLRowCount(this, out result); rowCount = new SQLLEN(result); ODBC.TraceODBC(3, "SQLRowCount", retcode); return retcode; } internal ODBC32.RetCode SetStatementAttribute(ODBC32.SQL_ATTR attribute, IntPtr value, ODBC32.SQL_IS stringLength) { ODBC32.RetCode retcode = Interop.Odbc.SQLSetStmtAttrW(this, (int)attribute, value, (int)stringLength); ODBC.TraceODBC(3, "SQLSetStmtAttrW", retcode); return retcode; } internal ODBC32.RetCode SpecialColumns(string quotedTable) { ODBC32.RetCode retcode = Interop.Odbc.SQLSpecialColumnsW(this, ODBC32.SQL_SPECIALCOLS.ROWVER, null, 0, null, 0, quotedTable, ODBC.ShortStringLength(quotedTable), ODBC32.SQL_SCOPE.SESSION, ODBC32.SQL_NULLABILITY.NO_NULLS); ODBC.TraceODBC(3, "SQLSpecialColumnsW", retcode); return retcode; } internal ODBC32.RetCode Statistics(string tableCatalog, string tableSchema, string tableName, short unique, short accuracy) { ODBC32.RetCode retcode; // MDAC Bug 75928 - SQLStatisticsW damages the string passed in // To protect the tablename we need to pass in a copy of that string IntPtr pwszTableName = Marshal.StringToCoTaskMemUni(tableName); try { retcode = Interop.Odbc.SQLStatisticsW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), pwszTableName, ODBC.ShortStringLength(tableName), unique, accuracy); } finally { Marshal.FreeCoTaskMem(pwszTableName); } ODBC.TraceODBC(3, "SQLStatisticsW", retcode); return retcode; } internal ODBC32.RetCode Statistics(string tableName) { return Statistics(null, null, tableName, (short)ODBC32.SQL_INDEX.UNIQUE, (short)ODBC32.SQL_STATISTICS_RESERVED.ENSURE); } internal ODBC32.RetCode Tables(string tableCatalog, string tableSchema, string tableName, string tableType) { ODBC32.RetCode retcode = Interop.Odbc.SQLTablesW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), tableName, ODBC.ShortStringLength(tableName), tableType, ODBC.ShortStringLength(tableType)); ODBC.TraceODBC(3, "SQLTablesW", retcode); return retcode; } } }
// 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.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System.Net.WebSockets { [Serializable] public sealed class WebSocketException : Win32Exception { private readonly WebSocketError _webSocketErrorCode; [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException() : this(Marshal.GetLastWin32Error()) { } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(WebSocketError error) : this(error, GetErrorMessage(error)) { } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(WebSocketError error, string message) : base(message) { _webSocketErrorCode = error; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(WebSocketError error, Exception innerException) : this(error, GetErrorMessage(error), innerException) { } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(WebSocketError error, string message, Exception innerException) : base(message, innerException) { _webSocketErrorCode = error; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(int nativeError) : base(nativeError) { _webSocketErrorCode = !Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; SetErrorCodeOnError(nativeError); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(int nativeError, string message) : base(nativeError, message) { _webSocketErrorCode = !Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; SetErrorCodeOnError(nativeError); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(int nativeError, Exception innerException) : base(SR.net_WebSockets_Generic, innerException) { _webSocketErrorCode = !Succeeded(nativeError) ? WebSocketError.NativeError : WebSocketError.Success; SetErrorCodeOnError(nativeError); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(WebSocketError error, int nativeError) : this(error, nativeError, GetErrorMessage(error)) { } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(WebSocketError error, int nativeError, string message) : base(message) { _webSocketErrorCode = error; SetErrorCodeOnError(nativeError); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(WebSocketError error, int nativeError, Exception innerException) : this(error, nativeError, GetErrorMessage(error), innerException) { } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(WebSocketError error, int nativeError, string message, Exception innerException) : base(message, innerException) { _webSocketErrorCode = error; SetErrorCodeOnError(nativeError); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(string message) : base(message) { } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This ctor is harmless, because it does not pass arbitrary data into the native code.")] public WebSocketException(string message, Exception innerException) : base(message, innerException) { } private WebSocketException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { _webSocketErrorCode = (WebSocketError)serializationInfo.GetInt32(nameof(WebSocketErrorCode)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue(nameof(WebSocketErrorCode), (int)_webSocketErrorCode); base.GetObjectData(info, context); } public override int ErrorCode { get { return base.NativeErrorCode; } } public WebSocketError WebSocketErrorCode { get { return _webSocketErrorCode; } } private static string GetErrorMessage(WebSocketError error) { // Provide a canned message for the error type. switch (error) { case WebSocketError.InvalidMessageType: return SR.Format(SR.net_WebSockets_InvalidMessageType_Generic, $"{nameof(WebSocket)}.{nameof(WebSocket.CloseAsync)}", $"{nameof(WebSocket)}.{nameof(WebSocket.CloseOutputAsync)}"); case WebSocketError.Faulted: return SR.net_Websockets_WebSocketBaseFaulted; case WebSocketError.NotAWebSocket: return SR.net_WebSockets_NotAWebSocket_Generic; case WebSocketError.UnsupportedVersion: return SR.net_WebSockets_UnsupportedWebSocketVersion_Generic; case WebSocketError.UnsupportedProtocol: return SR.net_WebSockets_UnsupportedProtocol_Generic; case WebSocketError.HeaderError: return SR.net_WebSockets_HeaderError_Generic; case WebSocketError.ConnectionClosedPrematurely: return SR.net_WebSockets_ConnectionClosedPrematurely_Generic; case WebSocketError.InvalidState: return SR.net_WebSockets_InvalidState_Generic; default: return SR.net_WebSockets_Generic; } } // Set the error code only if there is an error (i.e. nativeError >= 0). Otherwise the code fails during deserialization // as the Exception..ctor() throws on setting HResult to 0. The default for HResult is -2147467259. private void SetErrorCodeOnError(int nativeError) { if (!Succeeded(nativeError)) { HResult = nativeError; } } private static bool Succeeded(int hr) { return (hr >= 0); } } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using ImageOrganizer.ViewModels; using System.ComponentModel.Composition; using Microsoft.Practices.Prism.Commands; using System.Windows.Input; using System.Windows.Data; using System.ComponentModel; using System.Threading; using ImageOrganizer.Presentation.Collections; using System.Windows.Media; using ImageOrganizer.Common.Utils; namespace ImageOrganizer.ViewModels { [Export] public class MainWindowViewModel : ViewModel { #region Global Variables private readonly DelegateCommand _BrowseFolderCommand; private readonly DelegateCommand _CloseFolderCommand; private readonly DelegateCommand _GotoFirstFileCommand; private readonly DelegateCommand _GotoPreviousFileCommand; private readonly DelegateCommand _GotoNextFileCommand; private readonly DelegateCommand _GotoLastFileCommand; private readonly DelegateCommand _GotoImageNameCommand; private readonly DelegateCommand _ZoomInCommand; private readonly DelegateCommand _ZoomOutCommand; private readonly DelegateCommand _ActualSizeCommand; private readonly DelegateCommand _ZoomFitCommand; private readonly DelegateCommand _FitWidthCommand; private readonly DelegateCommand _FitHeightCommand; private readonly DelegateCommand _RenameActiveImageCommand; private readonly DelegateCommand _DeleteActiveImageCommand; private readonly DelegateCommand _RefreshActiveImageCommand; private readonly DelegateCommand _AboutCommand; private readonly ActiveImagesViewModel _ActiveImagesViewModel; #endregion #region Properties public ICommand BrowseFolderCommand { get { return _BrowseFolderCommand; } } public ICommand CloseFolderCommand { get { return _CloseFolderCommand; } } public ICommand GotoFirstFileCommand { get { return _GotoFirstFileCommand; } } public ICommand GotoPreviousFileCommand { get { return _GotoPreviousFileCommand; } } public ICommand GotoNextFileCommand { get { return _GotoNextFileCommand; } } public ICommand GotoLastFileCommand { get { return _GotoLastFileCommand; } } public ICommand GotoImageNameCommand { get { return _GotoImageNameCommand; } } public ICommand ZoomInCommand { get { return _ZoomInCommand; } } public ICommand ZoomOutCommand { get { return _ZoomOutCommand; } } public ICommand ActualSizeCommand { get { return _ActualSizeCommand; } } public ICommand ZoomFitCommand { get { return _ZoomFitCommand; } } public ICommand FitWidthCommand { get { return _FitWidthCommand; } } public ICommand FitHeightCommand { get { return _FitHeightCommand; } } public ICommand RenameActiveImageCommand { get { return _RenameActiveImageCommand; } } public ICommand DeleteActiveImageCommand { get { return _DeleteActiveImageCommand; } } public ICommand RefreshActiveImageCommand { get { return _RefreshActiveImageCommand; } } public ICommand AboutCommand { get { return _AboutCommand; } } public ActiveImagesViewModel ActiveImagesViewModel { get { return _ActiveImagesViewModel; } } public ImageOrganizer.Windows.MainWindow Owner { get; internal set; } #endregion #region Events #endregion #region Constructor public MainWindowViewModel() { _BrowseFolderCommand = new DelegateCommand(DoBrowseFolderCommand, CanDoBrowseFolderCommand); _CloseFolderCommand = new DelegateCommand(DoCloseFolderCommand, CanDoCloseFolderCommand); _GotoFirstFileCommand = new DelegateCommand(DoGotoFirstFileCommand, CanDoGotoFirstFileCommand); _GotoPreviousFileCommand = new DelegateCommand(DoGotoPreviousFileCommand, CanDoGotoPreviousFileCommand); _GotoNextFileCommand = new DelegateCommand(DoGotoNextFileCommand, CanDoGotoNextFileCommand); _GotoLastFileCommand = new DelegateCommand(DoGotoLastFileCommand, CanDoGotoLastFileCommand); _GotoImageNameCommand = new DelegateCommand(DoGotoImageNameCommand, CanDoGotoImageNameCommand); _ZoomInCommand = new DelegateCommand(DoZoomInCommand, CanDoZoomInCommandCommand); _ZoomOutCommand = new DelegateCommand(DoZoomOutCommand, CanDoZoomOutCommandCommand); _ActualSizeCommand = new DelegateCommand(DoActualSizeCommand, CanDoActualSizeCommandCommand); _ZoomFitCommand = new DelegateCommand(DoZoomFitCommand, CanDoZoomFitCommandCommand); _FitWidthCommand = new DelegateCommand(DoFitWidthCommand, CanDoFitWidthCommandCommand); _FitHeightCommand = new DelegateCommand(DoFitHeightCommand, CanDoFitHeightCommandCommand); _RenameActiveImageCommand = new DelegateCommand(DoRenameActiveImageCommand, CanDoRenameActiveImageCommand); _DeleteActiveImageCommand = new DelegateCommand(DoDeleteActiveImageCommand, CanDoDeleteActiveImageCommand); _RefreshActiveImageCommand = new DelegateCommand(DoRefreshActiveImageCommand, CanDoRefreshActiveImageCommandCommand); _AboutCommand = new DelegateCommand(DoAboutCommand, CanDoAboutCommand); _ActiveImagesViewModel = new ActiveImagesViewModel(); _ActiveImagesViewModel.ActiveFilesCollection.CollectionChanged += (s, e) => { _CloseFolderCommand.RaiseCanExecuteChanged(); RaisePositionCommandEvents(); RaiseZoomCommandEvents(); RaiseFileOperationEvents(); }; _ActiveImagesViewModel.ActiveImageChanged += (s, e) => { RaisePositionCommandEvents(); }; _ActiveImagesViewModel.PropertyChanged += (s, e) => { switch (e.PropertyName) { case "IsLoadingFiles": RaiseFileOperationEvents(); break; } }; } #endregion #region Event Handlers #endregion #region Methods private void DoBrowseFolderCommand() { if (!CanDoBrowseFolderCommand()) return; var Browser = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog(); Browser.IsFolderPicker = true; var LastBrowsedDirectory = ImageOrganizer.Properties.Settings.Default.LastBrowsedDirectory; if (!string.IsNullOrEmpty(LastBrowsedDirectory) && System.IO.Directory.Exists(LastBrowsedDirectory)) Browser.InitialDirectory = LastBrowsedDirectory; else Browser.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); var Result = Browser.ShowDialog(); if (Result != Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Ok) return; ImageOrganizer.Properties.Settings.Default.LastBrowsedDirectory = Browser.FileName; this.ActiveImagesViewModel.LoadImages(Browser.FileName); } private bool CanDoBrowseFolderCommand() { return true; } private void DoCloseFolderCommand() { if (!CanDoCloseFolderCommand()) return; this.ActiveImagesViewModel.CloseFolder(); } private bool CanDoCloseFolderCommand() { return this.ActiveImagesViewModel.IsViewingFiles; } private void DoGotoFirstFileCommand() { if (!CanDoGotoFirstFileCommand()) return; this.ActiveImagesViewModel.MoveToFirst(); } private bool CanDoGotoFirstFileCommand() { return this.ActiveImagesViewModel.IsViewingFiles && !this.ActiveImagesViewModel.IsViewingFirstFile; } private void DoGotoPreviousFileCommand() { if (!CanDoGotoPreviousFileCommand()) return; this.ActiveImagesViewModel.MoveToPrevious(); } private bool CanDoGotoPreviousFileCommand() { return this.ActiveImagesViewModel.IsViewingFiles && !this.ActiveImagesViewModel.IsViewingFirstFile; } private void DoGotoNextFileCommand() { if (!CanDoGotoNextFileCommand()) return; this.ActiveImagesViewModel.MoveToNext(); } private bool CanDoGotoNextFileCommand() { return this.ActiveImagesViewModel.IsViewingFiles && !this.ActiveImagesViewModel.IsViewingLastFile; } private void DoGotoLastFileCommand() { if (!CanDoGotoLastFileCommand()) return; this.ActiveImagesViewModel.MoveToLast(); } private bool CanDoGotoLastFileCommand() { return this.ActiveImagesViewModel.IsViewingFiles && !this.ActiveImagesViewModel.IsViewingLastFile; } private void DoGotoImageNameCommand() { if (!CanDoGotoImageNameCommand()) return; this.ActiveImagesViewModel.MoveToImageName(); } private bool CanDoGotoImageNameCommand() { return this.ActiveImagesViewModel.IsViewingFiles; } private void DoZoomInCommand() { if (!CanDoZoomInCommandCommand()) return; this.ActiveImagesViewModel.ZoomIn(); } private bool CanDoZoomInCommandCommand() { return this.ActiveImagesViewModel.IsViewingFiles; } private void DoZoomOutCommand() { if (!CanDoZoomOutCommandCommand()) return; this.ActiveImagesViewModel.ZoomOut(); } private bool CanDoZoomOutCommandCommand() { return this.ActiveImagesViewModel.IsViewingFiles; // && this.ActiveImagesViewModel.SelectedImage != null; } private void DoActualSizeCommand() { if (!CanDoActualSizeCommandCommand()) return; this.ActiveImagesViewModel.ActualSize(); } private bool CanDoActualSizeCommandCommand() { return this.ActiveImagesViewModel.IsViewingFiles; // && this.ActiveImagesViewModel.SelectedImage != null; } private void DoZoomFitCommand() { if (!CanDoZoomFitCommandCommand()) return; this.ActiveImagesViewModel.ZoomFit(); } private bool CanDoZoomFitCommandCommand() { return this.ActiveImagesViewModel.IsViewingFiles; // && this.ActiveImagesViewModel.SelectedImage != null; } private void DoFitWidthCommand() { if (!CanDoFitWidthCommandCommand()) return; this.ActiveImagesViewModel.FitWidth(); } private bool CanDoFitWidthCommandCommand() { return this.ActiveImagesViewModel.IsViewingFiles; // && this.ActiveImagesViewModel.SelectedImage != null; } private void DoFitHeightCommand() { if (!CanDoFitHeightCommandCommand()) return; this.ActiveImagesViewModel.FitHeight(); } private bool CanDoFitHeightCommandCommand() { return this.ActiveImagesViewModel.IsViewingFiles; // && this.ActiveImagesViewModel.SelectedImage != null; } private void DoRenameActiveImageCommand() { if (!CanDoRenameActiveImageCommand()) return; this.ActiveImagesViewModel.RenameActiveImage(); } private bool CanDoRenameActiveImageCommand() { return this.ActiveImagesViewModel.IsViewingFiles && !this.ActiveImagesViewModel.IsLoadingFiles; } private void DoDeleteActiveImageCommand() { if (!CanDoDeleteActiveImageCommand()) return; this.ActiveImagesViewModel.DeleteActiveImage(); } private bool CanDoDeleteActiveImageCommand() { return this.ActiveImagesViewModel.IsViewingFiles && !this.ActiveImagesViewModel.IsLoadingFiles; } private void DoRefreshActiveImageCommand() { if (!CanDoRefreshActiveImageCommandCommand()) return; this.ActiveImagesViewModel.RefreshActiveImage(); } private bool CanDoRefreshActiveImageCommandCommand() { return this.ActiveImagesViewModel.IsViewingFiles; } private void DoAboutCommand() { if (!CanDoAboutCommand()) return; var AboutWindow = new ImageOrganizer.Windows.AboutWindow(); AboutWindow.Owner = this.Owner; AboutWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner; AboutWindow.ShowDialog(); } private bool CanDoAboutCommand() { return true; } //private void Do() //{ // if (!CanDo)) // return; //} //private bool CanDo() //{ // return true; //} private void RaisePositionCommandEvents() { this._GotoFirstFileCommand.RaiseCanExecuteChanged(); this._GotoPreviousFileCommand.RaiseCanExecuteChanged(); this._GotoNextFileCommand.RaiseCanExecuteChanged(); this._GotoLastFileCommand.RaiseCanExecuteChanged(); this._GotoImageNameCommand.RaiseCanExecuteChanged(); } private void RaiseZoomCommandEvents() { this._ZoomInCommand.RaiseCanExecuteChanged(); this._ZoomOutCommand.RaiseCanExecuteChanged(); this._ActualSizeCommand.RaiseCanExecuteChanged(); this._ZoomFitCommand.RaiseCanExecuteChanged(); } private void RaiseFileOperationEvents() { this._RenameActiveImageCommand.RaiseCanExecuteChanged(); this._DeleteActiveImageCommand.RaiseCanExecuteChanged(); } #endregion } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Zunix.ScreensManager { /// <summary> /// A popup message box screen, used to display "are you sure?" /// confirmation messages. /// </summary> class MessageBoxScreen : GameScreen { #region Fields string message; Texture2D grakillntTexture; const string usageTextOk = "A Button = Ok"; const string usageTextCancel = "B Button = Cancel"; bool includeUsageTextOk = false; bool includeUsageTextCancel = false; #endregion #region Events public event EventHandler<EventArgs> Accepted; public event EventHandler<EventArgs> Cancelled; #endregion #region Initialization /// <summary> /// Constructor automatically includes the standard "A=ok, B=cancel" /// usage text prompt. /// </summary> public MessageBoxScreen(string message) : this(message, true) { } /// <summary> /// Constructor lets the caller specify whether to include the standard /// "A=ok, B=cancel" usage text prompt. /// </summary> public MessageBoxScreen(string message, bool includeUsageText) { if (includeUsageText) { this.message = message; this.includeUsageTextOk = true; this.includeUsageTextOk = true; } else { this.includeUsageTextCancel = false; this.includeUsageTextOk = false; this.message = message; } IsPopup = true; TransitionOnTime = TimeSpan.FromSeconds(0.2); TransitionOffTime = TimeSpan.FromSeconds(0.2); } public MessageBoxScreen(string message, bool includeUsageOk, bool includeUsageCancel) { this.message = message; if (includeUsageOk) { this.includeUsageTextOk = true; } else { this.includeUsageTextOk = false; } if (includeUsageCancel) { this.includeUsageTextCancel = true; } else { this.includeUsageTextCancel = false; } this.includeUsageTextCancel = includeUsageCancel; IsPopup = true; TransitionOnTime = TimeSpan.FromSeconds(0.2); TransitionOffTime = TimeSpan.FromSeconds(0.2); } /// <summary> /// Loads graphics content for this screen. This uses the shared ContentManager /// provided by the Game class, so the content will remain loaded forever. /// Whenever a subsequent MessageBoxScreen tries to load this same content, /// it will just get back another reference to the already loaded data. /// </summary> public override void LoadContent() { ContentManager content = ScreenManager.Game.Content; grakillntTexture = content.Load<Texture2D>(@"Textures\grakillnt"); } #endregion #region Handle Input /// <summary> /// Responds to user input, accepting or cancelling the message box. /// </summary> public override void HandleInput(InputState input) { if (input.MenuSelect) { // Raise the accepted event, then exit the message box. if (Accepted != null) Accepted(this, EventArgs.Empty); ExitScreen(); } else if (input.MenuCancel) { // Raise the cancelled event, then exit the message box. if (Cancelled != null) Cancelled(this, EventArgs.Empty); ExitScreen(); } } #endregion #region Draw /// <summary> /// Draws the message box. /// </summary> public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; // Darken down any other screens that were drawn beneath the popup. ScreenManager.FadeBackBufferToBlack(TransitionAlpha * 2 / 3); //Usage Text // Calculate the hieght of the text // Center the message text in the viewport. Vector2 textSize = font.MeasureString(message); Vector2 textPosition = new Vector2(10, 20); // The background includes a border somewhat larger than the text itself. const int hPad = 32; const int vPad = 16; Rectangle backgroundRectangle = new Rectangle((int)textPosition.X - hPad, (int)textPosition.Y - vPad, (int)textSize.X + hPad * 2, (int)textSize.Y + vPad * 2); // Fade the popup alpha during transitions. Color color = new Color(255, 255, 255, TransitionAlpha); spriteBatch.Begin(); // Draw the message box text. spriteBatch.DrawString(font, wordwrap(240,message,font), textPosition, color); // Draw Usage Text if (this.includeUsageTextOk || this.includeUsageTextCancel) { // Display both Usage Lines spriteBatch.DrawString(font, usageTextOk, new Vector2(10, 280), color); spriteBatch.DrawString(font, usageTextCancel, new Vector2(10, 300), color); } else if (this.includeUsageTextOk) { // Display only the Ok Usage Line spriteBatch.DrawString(font, usageTextOk, new Vector2(10, 300), color); } spriteBatch.End(); } #endregion public string wordwrap(int width, String in_string, SpriteFont in_font) { int x; String current_line = ""; String current_word = ""; String new_string = ""; for (x = 0; x < in_string.Length; x++) { if (in_string[x].CompareTo(' ') == 0) { if (in_font.MeasureString(current_word).X + in_font.MeasureString(current_line + " ").X > width) { new_string = new_string + current_line + "\n"; current_line = current_word + " "; current_word = ""; } else { if (current_line.Length > 0) { current_line = current_line + " " + current_word; current_word = ""; } else { current_line = current_word; current_word = ""; } } } else { current_word = current_word + in_string[x]; } } new_string = new_string + current_line + " " + current_word; return new_string; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Threading; using System.Security; namespace System.Text { // DBCSCodePageEncoding // internal class DBCSCodePageEncoding : BaseCodePageEncoding { // Pointers to our memory section parts [SecurityCritical] protected unsafe char* mapBytesToUnicode = null; // char 65536 [SecurityCritical] protected unsafe ushort* mapUnicodeToBytes = null; // byte 65536 protected const char UNKNOWN_CHAR_FLAG = (char)0x0; protected const char UNICODE_REPLACEMENT_CHAR = (char)0xFFFD; protected const char LEAD_BYTE_CHAR = (char)0xFFFE; // For lead bytes // Note that even though we provide bytesUnknown and byteCountUnknown, // They aren't actually used because of the fallback mechanism. (char is though) private ushort _bytesUnknown; private int _byteCountUnknown; protected char charUnknown = (char)0; [System.Security.SecurityCritical] // auto-generated public DBCSCodePageEncoding(int codePage) : this(codePage, codePage) { } [System.Security.SecurityCritical] // auto-generated internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage) { } [System.Security.SecurityCritical] // auto-generated internal DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, dataCodePage, enc, dec) { } // MBCS data section: // // We treat each multibyte pattern as 2 bytes in our table. If it's a single byte, then the high byte // for that position will be 0. When the table is loaded, leading bytes are flagged with 0xFFFE, so // when reading the table look up with each byte. If the result is 0xFFFE, then use 2 bytes to read // further data. FFFF is a special value indicating that the Unicode code is the same as the // character code (this helps us support code points < 0x20). FFFD is used as replacement character. // // Normal table: // WCHAR* - Starting with MB code point 0. // FFFF indicates we are to use the multibyte value for our code point. // FFFE is the lead byte mark. (This should only appear in positions < 0x100) // FFFD is the replacement (unknown character) mark. // 2-20 means to advance the pointer 2-0x20 characters. // 1 means to advance to the multibyte position contained in the next char. // 0 has no specific meaning (May not be possible.) // // Table ends when multibyte position has advanced to 0xFFFF. // // Bytes->Unicode Best Fit table: // WCHAR* - Same as normal table, except first wchar is byte position to start at. // // Unicode->Bytes Best Fit Table: // WCHAR* - Same as normal table, except first wchar is char position to start at and // we loop through unicode code points and the table has the byte points that // correspond to those unicode code points. // We have a managed code page entry, so load our tables // [System.Security.SecurityCritical] // auto-generated protected override unsafe void LoadManagedCodePage() { fixed (byte* pBytes = m_codePageHeader) { CodePageHeader* pCodePage = (CodePageHeader*)pBytes; // Should be loading OUR code page Debug.Assert(pCodePage->CodePage == dataTableCodePage, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1-byte code page if (pCodePage->ByteCount != 2) throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage)); // Remember our unknown bytes & chars _bytesUnknown = pCodePage->ByteReplace; charUnknown = pCodePage->UnicodeReplace; // Need to make sure the fallback buffer's fallback char is correct if (DecoderFallback is InternalDecoderBestFitFallback) { ((InternalDecoderBestFitFallback)(DecoderFallback)).cReplacement = charUnknown; } // Is our replacement bytesUnknown a single or double byte character? _byteCountUnknown = 1; if (_bytesUnknown > 0xff) _byteCountUnknown++; // We use fallback encoder, which uses ?, which so far all of our tables do as well Debug.Assert(_bytesUnknown == 0x3f, "[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character"); // Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars) // Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment) byte* pNativeMemory = GetNativeMemory(65536 * 2 * 2 + 4 + iExtraBytes); mapBytesToUnicode = (char*)pNativeMemory; mapUnicodeToBytes = (ushort*)(pNativeMemory + 65536 * 2); // Need to read our data file and fill in our section. // WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide) // so be careful here. Only stick legal values in here, don't stick temporary values. // Move to the beginning of the data section byte[] buffer = new byte[m_dataSize]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize); } fixed (byte* pBuffer = buffer) { char* pData = (char*)pBuffer; // We start at bytes position 0 int bytePosition = 0; int useBytes = 0; while (bytePosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position bytePosition = (int)(*pData); pData++; continue; } else if (input < 0x20 && input > 0) { // Advance input characters bytePosition += input; continue; } else if (input == 0xFFFF) { // Same as our bytePosition useBytes = bytePosition; input = unchecked((char)bytePosition); } else if (input == LEAD_BYTE_CHAR) // 0xfffe { // Lead byte mark Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100"); useBytes = bytePosition; // input stays 0xFFFE } else if (input == UNICODE_REPLACEMENT_CHAR) { // Replacement char is already done bytePosition++; continue; } else { // Use this character useBytes = bytePosition; // input == input; } // We may need to clean up the selected character & position if (CleanUpBytes(ref useBytes)) { // Use this selected character at the selected position, don't do this if not supposed to. if (input != LEAD_BYTE_CHAR) { // Don't do this for lead byte marks. mapUnicodeToBytes[input] = unchecked((ushort)useBytes); } mapBytesToUnicode[useBytes] = input; } bytePosition++; } } // See if we have any clean up to do CleanUpEndBytes(mapBytesToUnicode); } } // Any special processing for this code page protected virtual bool CleanUpBytes(ref int bytes) { return true; } // Any special processing for this code page [System.Security.SecurityCritical] // auto-generated protected virtual unsafe void CleanUpEndBytes(char* chars) { } // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Read in our best fit table [System.Security.SecurityCritical] // auto-generated protected unsafe override void ReadBestFitTable() { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // If we got a best fit array already then don't do this if (arrayUnicodeBestFit == null) { // // Read in Best Fit table. // // First we have to advance past original character mapping table // Move to the beginning of the data section byte[] buffer = new byte[m_dataSize]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize); } fixed (byte* pBuffer = buffer) { char* pData = (char*)pBuffer; // We start at bytes position 0 int bytesPosition = 0; while (bytesPosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position bytesPosition = (int)(*pData); pData++; } else if (input < 0x20 && input > 0) { // Advance input characters bytesPosition += input; } else { // All other cases add 1 to bytes position bytesPosition++; } } // Now bytesPosition is at start of bytes->unicode best fit table char* pBytes2Unicode = pData; // Now pData should be pointing to first word of bytes -> unicode best fit table // (which we're also not using at the moment) int iBestFitCount = 0; bytesPosition = *pData; pData++; while (bytesPosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position bytesPosition = (int)(*pData); pData++; } else if (input < 0x20 && input > 0) { // Advance input characters bytesPosition += input; } else { // Use this character (unless it's unknown, unk just skips 1) if (input != UNICODE_REPLACEMENT_CHAR) { int correctedChar = bytesPosition; if (CleanUpBytes(ref correctedChar)) { // Sometimes correction makes them the same as no best fit, skip those. if (mapBytesToUnicode[correctedChar] != input) { iBestFitCount++; } } } // Position gets incremented in any case. bytesPosition++; } } // Now we know how big the best fit table has to be char[] arrayTemp = new char[iBestFitCount * 2]; // Now we know how many best fits we have, so go back & read them in iBestFitCount = 0; pData = pBytes2Unicode; bytesPosition = *pData; pData++; bool bOutOfOrder = false; // Read it all in again while (bytesPosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position bytesPosition = (int)(*pData); pData++; } else if (input < 0x20 && input > 0) { // Advance input characters bytesPosition += input; } else { // Use this character (unless its unknown, unk just skips 1) if (input != UNICODE_REPLACEMENT_CHAR) { int correctedChar = bytesPosition; if (CleanUpBytes(ref correctedChar)) { // Sometimes correction makes them same as no best fit, skip those. if (mapBytesToUnicode[correctedChar] != input) { if (correctedChar != bytesPosition) bOutOfOrder = true; arrayTemp[iBestFitCount++] = unchecked((char)correctedChar); arrayTemp[iBestFitCount++] = input; } } } // Position gets incremented in any case. bytesPosition++; } } // If they're out of order we need to sort them. if (bOutOfOrder) { Debug.Assert((arrayTemp.Length / 2) < 20, "[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2); for (int i = 0; i < arrayTemp.Length - 2; i += 2) { int iSmallest = i; char cSmallest = arrayTemp[i]; for (int j = i + 2; j < arrayTemp.Length; j += 2) { // Find smallest one for front if (cSmallest > arrayTemp[j]) { cSmallest = arrayTemp[j]; iSmallest = j; } } // If smallest one is something else, switch them if (iSmallest != i) { char temp = arrayTemp[iSmallest]; arrayTemp[iSmallest] = arrayTemp[i]; arrayTemp[i] = temp; temp = arrayTemp[iSmallest + 1]; arrayTemp[iSmallest + 1] = arrayTemp[i + 1]; arrayTemp[i + 1] = temp; } } } // Remember our array arrayBytesBestFit = arrayTemp; // Now were at beginning of Unicode -> Bytes best fit table, need to count them char* pUnicode2Bytes = pData; int unicodePosition = *(pData++); iBestFitCount = 0; while (unicodePosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position unicodePosition = (int)*pData; pData++; } else if (input < 0x20 && input > 0) { // Advance input characters unicodePosition += input; } else { // Same as our unicodePosition or use this character if (input > 0) iBestFitCount++; unicodePosition++; } } // Allocate our table arrayTemp = new char[iBestFitCount * 2]; // Now do it again to fill the array with real values pData = pUnicode2Bytes; unicodePosition = *(pData++); iBestFitCount = 0; while (unicodePosition < 0x10000) { // Get the next byte char input = *pData; pData++; // build our table: if (input == 1) { // Use next data as our byte position unicodePosition = (int)*pData; pData++; } else if (input < 0x20 && input > 0) { // Advance input characters unicodePosition += input; } else { if (input > 0) { // Use this character, may need to clean it up int correctedChar = (int)input; if (CleanUpBytes(ref correctedChar)) { arrayTemp[iBestFitCount++] = unchecked((char)unicodePosition); // Have to map it to Unicode because best fit will need Unicode value of best fit char. arrayTemp[iBestFitCount++] = mapBytesToUnicode[correctedChar]; } } unicodePosition++; } } // Remember our array arrayUnicodeBestFit = arrayTemp; } } } } // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback"); CheckMemorySection(); // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; // Only count if encoder.m_throwOnOverflow if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); } // prepare our end int byteCount = 0; char* charEnd = chars + count; // For fallback we will need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate fallbackHelper.InternalFallback(charLeftOver, ref chars); } // Now we may have fallback char[] already (from the encoder) // We have to use fallback method. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char ushort sTemp = mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (sTemp == 0 && ch != (char)0) { if (fallbackBuffer == null) { // Initialize the buffer if (encoder == null) fallbackBuffer = EncoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(charEnd - count, charEnd, encoder, false); } // Get Fallback fallbackHelper.InternalFallback(ch, ref chars); continue; } // We'll use this one byteCount++; if (sTemp >= 0x100) byteCount++; } return (int)byteCount; } [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback"); CheckMemorySection(); // For fallback we will need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; // prepare our end char* charEnd = chars + charCount; char* charStart = chars; byte* byteStart = bytes; byte* byteEnd = bytes + byteCount; EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); // Get any left over characters char charLeftOver = (char)0; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate"); // Go ahead and get the fallback buffer (need leftover fallback if converting) fallbackBuffer = encoder.FallbackBuffer; fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(chars, charEnd, encoder, true); // If we're not converting we must not have a fallback buffer if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType())); // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(encoder != null, "[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackHelper.InternalFallback(charLeftOver, ref chars); } } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // get byte for this char ushort sTemp = mapUnicodeToBytes[ch]; // Check for fallback, this'll catch surrogate pairs too. if (sTemp == 0 && ch != (char)0) { if (fallbackBuffer == null) { // Initialize the buffer Debug.Assert(encoder == null, "[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder."); fallbackBuffer = EncoderFallback.CreateFallbackBuffer(); fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Get Fallback fallbackHelper.InternalFallback(ch, ref chars); continue; } // We'll use this one (or two) // Bounds check // Go ahead and add it, lead byte 1st if necessary if (sTemp >= 0x100) { if (bytes + 1 >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)"); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // don't use last fallback ThrowBytesOverflow(encoder, chars == charStart); // throw ? break; // don't throw, stop } *bytes = unchecked((byte)(sTemp >> 8)); bytes++; } // Single byte else if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackHelper.bFallingBack == false) { Debug.Assert(chars > charStart, "[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)"); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // don't use last fallback ThrowBytesOverflow(encoder, chars == charStart); // throw ? break; // don't throw, stop } *bytes = unchecked((byte)(sTemp & 0xff)); bytes++; } // encoder stuff if we have one if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } // This is internal and called by something else, [System.Security.SecurityCritical] // auto-generated public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative"); CheckMemorySection(); // Fix our decoder DBCSDecoder decoder = (DBCSDecoder)baseDecoder; // Get our fallback DecoderFallbackBuffer fallbackBuffer = null; // We'll need to know where the end is byte* byteEnd = bytes + count; int charCount = count; // Assume 1 char / byte // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check m_throwOnOverflow for count) Debug.Assert(decoder == null || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start"); DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); // If we have a left over byte, use it if (decoder != null && decoder.bLeftOver > 0) { // We have a left over byte? if (count == 0) { // No input though if (!decoder.MustFlush) { // Don't have to flush return 0; } Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(bytes, null); byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) }; return fallbackHelper.InternalFallback(byteBuffer, bytes); } // Get our full info int iBytes = decoder.bLeftOver << 8; iBytes |= (*bytes); bytes++; // This is either 1 known char or fallback // Already counted 1 char // Look up our bytes char cDecoder = mapBytesToUnicode[iBytes]; if (cDecoder == 0 && iBytes != 0) { // Deallocate preallocated one charCount--; // We'll need a fallback Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - count, null); // Do fallback, we know there are 2 bytes byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) }; charCount += fallbackHelper.InternalFallback(byteBuffer, bytes); } // else we already reserved space for this one. } // Loop, watch out for fallbacks while (bytes < byteEnd) { // Faster if don't use *bytes++; int iBytes = *bytes; bytes++; char c = mapBytesToUnicode[iBytes]; // See if it was a double byte character if (c == LEAD_BYTE_CHAR) { // It's a lead byte charCount--; // deallocate preallocated lead byte if (bytes < byteEnd) { // Have another to use, so use it iBytes <<= 8; iBytes |= *bytes; bytes++; c = mapBytesToUnicode[iBytes]; } else { // No input left if (decoder == null || decoder.MustFlush) { // have to flush anyway, set to unknown so we use fallback charCount++; // reallocate deallocated lead byte c = UNKNOWN_CHAR_FLAG; } else { // We'll stick it in decoder break; } } } // See if it was unknown. // Unknown and known chars already allocated, but fallbacks aren't if (c == UNKNOWN_CHAR_FLAG && iBytes != 0) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - count, null); } // Do fallback charCount--; // Get rid of preallocated extra char byte[] byteBuffer = null; if (iBytes < 0x100) byteBuffer = new byte[] { unchecked((byte)iBytes) }; else byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) }; charCount += fallbackHelper.InternalFallback(byteBuffer, bytes); } } // Shouldn't have anything in fallback buffer for GetChars Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end"); // Return our count return charCount; } [System.Security.SecurityCritical] // auto-generated public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative"); CheckMemorySection(); // Fix our decoder DBCSDecoder decoder = (DBCSDecoder)baseDecoder; // We'll need to know where the end is byte* byteStart = bytes; byte* byteEnd = bytes + byteCount; char* charStart = chars; char* charEnd = chars + charCount; bool bUsedDecoder = false; // Get our fallback DecoderFallbackBuffer fallbackBuffer = null; // Shouldn't have anything in fallback buffer for GetChars Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start"); DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); // If we have a left over byte, use it if (decoder != null && decoder.bLeftOver > 0) { // We have a left over byte? if (byteCount == 0) { // No input though if (!decoder.MustFlush) { // Don't have to flush return 0; } // Well, we're flushing, so use '?' or fallback // fallback leftover byte Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(bytes, charEnd); // If no room, it's hopeless, this was 1st fallback byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) }; if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars)) ThrowCharsOverflow(decoder, true); decoder.bLeftOver = 0; // Done, return it return (int)(chars - charStart); } // Get our full info int iBytes = decoder.bLeftOver << 8; iBytes |= (*bytes); bytes++; // Look up our bytes char cDecoder = mapBytesToUnicode[iBytes]; if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0) { Debug.Assert(fallbackBuffer == null, "[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes"); fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd); byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) }; if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars)) ThrowCharsOverflow(decoder, true); } else { // Do we have output room?, hopeless if not, this is first char if (chars >= charEnd) ThrowCharsOverflow(decoder, true); *(chars++) = cDecoder; } } // Loop, paying attention to our fallbacks. while (bytes < byteEnd) { // Faster if don't use *bytes++; int iBytes = *bytes; bytes++; char c = mapBytesToUnicode[iBytes]; // See if it was a double byte character if (c == LEAD_BYTE_CHAR) { // Its a lead byte if (bytes < byteEnd) { // Have another to use, so use it iBytes <<= 8; iBytes |= *bytes; bytes++; c = mapBytesToUnicode[iBytes]; } else { // No input left if (decoder == null || decoder.MustFlush) { // have to flush anyway, set to unknown so we use fallback c = UNKNOWN_CHAR_FLAG; } else { // Stick it in decoder bUsedDecoder = true; decoder.bLeftOver = (byte)iBytes; break; } } } // See if it was unknown if (c == UNKNOWN_CHAR_FLAG && iBytes != 0) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer); fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd); } // Do fallback byte[] byteBuffer = null; if (iBytes < 0x100) byteBuffer = new byte[] { unchecked((byte)iBytes) }; else byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) }; if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get these byte(s) Debug.Assert(bytes >= byteStart + byteBuffer.Length, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback"); bytes -= byteBuffer.Length; // didn't use these byte(s) fallbackHelper.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } } else { // Do we have buffer room? if (chars >= charEnd) { // May or may not throw, but we didn't get these byte(s) Debug.Assert(bytes > byteStart, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte"); bytes--; // unused byte if (iBytes >= 0x100) { Debug.Assert(bytes > byteStart, "[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte"); bytes--; // 2nd unused byte } ThrowCharsOverflow(decoder, bytes == byteStart); // throw? break; // don't throw, but stop loop } *(chars++) = c; } } // We already stuck it in encoder if necessary, but we have to clear cases where nothing new got into decoder if (decoder != null) { // Clear it in case of MustFlush if (bUsedDecoder == false) { decoder.bLeftOver = 0; } // Remember our count decoder.m_bytesUsed = (int)(bytes - byteStart); } // Shouldn't have anything in fallback buffer for GetChars Debug.Assert(decoder == null || !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end"); // Return length of our output return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 2 to 1 is worst case. Already considered surrogate fallback byteCount *= 2; if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // DBCS is pretty much the same, but could have hanging high byte making extra ? and fallback for unknown long charCount = ((long)byteCount + 1); // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } public override Decoder GetDecoder() { return new DBCSDecoder(this); } internal class DBCSDecoder : DecoderNLS { // Need a place for the last left over byte internal byte bLeftOver = 0; public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding) { // Base calls reset } public override void Reset() { bLeftOver = 0; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Anything left in our decoder? internal override bool HasState { get { return (bLeftOver != 0); } } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Streams; using Microsoft.Extensions.Logging; namespace Orleans.Providers.Streams.SimpleMessageStream { /// <summary> /// Multiplexes messages to mutiple different producers in the same grain over one grain-extension interface. /// /// On the silo, we have one extension per activation and this extesion multiplexes all streams on this activation /// (different stream ids and different stream providers). /// On the client, we have one extension per stream (we bind an extesion for every StreamProducer, therefore every stream has its own extension). /// </summary> [Serializable] internal class SimpleMessageStreamProducerExtension : IStreamProducerExtension { private readonly Dictionary<StreamId, StreamConsumerExtensionCollection> remoteConsumers; private readonly IStreamProviderRuntime providerRuntime; private readonly IStreamPubSub streamPubSub; private readonly bool fireAndForgetDelivery; private readonly bool optimizeForImmutableData; private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; internal SimpleMessageStreamProducerExtension(IStreamProviderRuntime providerRt, IStreamPubSub pubsub, ILoggerFactory loggerFactory, bool fireAndForget, bool optimizeForImmutable) { providerRuntime = providerRt; streamPubSub = pubsub; fireAndForgetDelivery = fireAndForget; optimizeForImmutableData = optimizeForImmutable; remoteConsumers = new Dictionary<StreamId, StreamConsumerExtensionCollection>(); logger = loggerFactory.CreateLogger<SimpleMessageStreamProducerExtension>(); this.loggerFactory = loggerFactory; } internal void AddStream(StreamId streamId) { StreamConsumerExtensionCollection obs; // no need to lock on _remoteConsumers, since on the client we have one extension per stream (per StreamProducer) // so this call is only made once, when StreamProducer is created. if (remoteConsumers.TryGetValue(streamId, out obs)) return; obs = new StreamConsumerExtensionCollection(streamPubSub, this.loggerFactory); remoteConsumers.Add(streamId, obs); } internal void RemoveStream(StreamId streamId) { remoteConsumers.Remove(streamId); } internal void AddSubscribers(StreamId streamId, ICollection<PubSubSubscriptionState> newSubscribers) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("{0} AddSubscribers {1} for stream {2}", providerRuntime.ExecutingEntityIdentity(), Utils.EnumerableToString(newSubscribers), streamId); StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { foreach (var newSubscriber in newSubscribers) { consumers.AddRemoteSubscriber(newSubscriber.SubscriptionId, newSubscriber.Consumer, newSubscriber.Filter); } } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } } internal Task DeliverItem(StreamId streamId, object item) { StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { // Note: This is the main hot code path, // and the caller immediately does await on the Task // returned from this method, so we can just direct return here // without incurring overhead of additional await. return consumers.DeliverItem(streamId, item, fireAndForgetDelivery, optimizeForImmutableData); } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } return Task.CompletedTask; } internal Task CompleteStream(StreamId streamId) { StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { return consumers.CompleteStream(streamId, fireAndForgetDelivery); } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } return Task.CompletedTask; } internal Task ErrorInStream(StreamId streamId, Exception exc) { StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { return consumers.ErrorInStream(streamId, exc, fireAndForgetDelivery); } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } return Task.CompletedTask; } // Called by rendezvous when new remote subsriber subscribes to this stream. public Task AddSubscriber(GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("{0} AddSubscriber {1} for stream {2}", providerRuntime.ExecutingEntityIdentity(), streamConsumer, streamId); } StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { consumers.AddRemoteSubscriber(subscriptionId, streamConsumer, filter); } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } return Task.CompletedTask; } public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId) { if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("{0} RemoveSubscription {1}", providerRuntime.ExecutingEntityIdentity(), subscriptionId); } foreach (StreamConsumerExtensionCollection consumers in remoteConsumers.Values) { consumers.RemoveRemoteSubscriber(subscriptionId); } return Task.CompletedTask; } [Serializable] internal class StreamConsumerExtensionCollection { private readonly ConcurrentDictionary<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>> consumers; private readonly IStreamPubSub streamPubSub; private readonly ILogger logger; internal StreamConsumerExtensionCollection(IStreamPubSub pubSub, ILoggerFactory loggerFactory) { streamPubSub = pubSub; this.logger = loggerFactory.CreateLogger<StreamConsumerExtensionCollection>(); consumers = new ConcurrentDictionary<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>>(); } internal void AddRemoteSubscriber(GuidId subscriptionId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { consumers.TryAdd(subscriptionId, Tuple.Create(streamConsumer, filter)); } internal void RemoveRemoteSubscriber(GuidId subscriptionId) { Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper> ignore; consumers.TryRemove(subscriptionId, out ignore); if (consumers.Count == 0) { // Unsubscribe from PubSub? } } internal Task DeliverItem(StreamId streamId, object item, bool fireAndForgetDelivery, bool optimizeForImmutableData) { var tasks = fireAndForgetDelivery ? null : new List<Task>(); foreach (KeyValuePair<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>> subscriptionKvp in consumers) { IStreamConsumerExtension remoteConsumer = subscriptionKvp.Value.Item1; // Apply filter(s) to see if we should forward this item to this consumer IStreamFilterPredicateWrapper filter = subscriptionKvp.Value.Item2; if (filter != null) { if (!filter.ShouldReceive(streamId, filter.FilterData, item)) continue; } Task task = DeliverToRemote(remoteConsumer, streamId, subscriptionKvp.Key, item, optimizeForImmutableData); if (fireAndForgetDelivery) task.Ignore(); else tasks.Add(task); } // If there's no subscriber, presumably we just drop the item on the floor return fireAndForgetDelivery ? Task.CompletedTask : Task.WhenAll(tasks); } private async Task DeliverToRemote(IStreamConsumerExtension remoteConsumer, StreamId streamId, GuidId subscriptionId, object item, bool optimizeForImmutableData) { try { if (optimizeForImmutableData) await remoteConsumer.DeliverImmutable(subscriptionId, streamId, new Immutable<object>(item), null, null); else await remoteConsumer.DeliverMutable(subscriptionId, streamId, item, null, null); } catch (ClientNotAvailableException) { Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper> discard; if (consumers.TryRemove(subscriptionId, out discard)) { streamPubSub.UnregisterConsumer(subscriptionId, streamId, streamId.ProviderName).Ignore(); logger.Warn(ErrorCode.Stream_ConsumerIsDead, "Consumer {0} on stream {1} is no longer active - permanently removing Consumer.", remoteConsumer, streamId); } } } internal Task CompleteStream(StreamId streamId, bool fireAndForgetDelivery) { var tasks = fireAndForgetDelivery ? null : new List<Task>(); foreach (GuidId subscriptionId in consumers.Keys) { var data = consumers[subscriptionId]; IStreamConsumerExtension remoteConsumer = data.Item1; Task task = remoteConsumer.CompleteStream(subscriptionId); if (fireAndForgetDelivery) task.Ignore(); else tasks.Add(task); } // If there's no subscriber, presumably we just drop the item on the floor return fireAndForgetDelivery ? Task.CompletedTask : Task.WhenAll(tasks); } internal Task ErrorInStream(StreamId streamId, Exception exc, bool fireAndForgetDelivery) { var tasks = fireAndForgetDelivery ? null : new List<Task>(); foreach (GuidId subscriptionId in consumers.Keys) { var data = consumers[subscriptionId]; IStreamConsumerExtension remoteConsumer = data.Item1; Task task = remoteConsumer.ErrorInStream(subscriptionId, exc); if (fireAndForgetDelivery) task.Ignore(); else tasks.Add(task); } // If there's no subscriber, presumably we just drop the item on the floor return fireAndForgetDelivery ? Task.CompletedTask : Task.WhenAll(tasks); } } } }
using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.CustomRuntimes; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Native; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace nullc_debugger_component { namespace DkmDebugger { internal class NullcStackFilterDataItem : DkmDataItem { public bool nullcIsMissing = false; public bool nullcIsReady = false; public string nullcDebugGetVmAddressLocation = null; public string nullcDebugGetNativeAddressLocation = null; public string nullcDebugGetReversedStackDataBase = null; public int nullcFramePosition = 1; } internal class NullcModuleDataItem : DkmDataItem { public bool nullcIsMissing = false; public ulong moduleBase; public uint moduleSize; } public class NullcStackFilter : IDkmCallStackFilter, IDkmInstructionAddressProvider { internal void InitNullcDebugFunctions(NullcStackFilterDataItem processData, DkmRuntimeInstance runtimeInstance) { if (processData.nullcIsMissing) { return; } processData.nullcDebugGetVmAddressLocation = DebugHelpers.FindFunctionAddress(runtimeInstance, "nullcDebugGetVmAddressLocation"); processData.nullcDebugGetNativeAddressLocation = DebugHelpers.FindFunctionAddress(runtimeInstance, "nullcDebugGetNativeAddressLocation"); processData.nullcDebugGetReversedStackDataBase = DebugHelpers.FindFunctionAddress(runtimeInstance, "nullcDebugGetReversedStackDataBase"); if (processData.nullcDebugGetVmAddressLocation == null || processData.nullcDebugGetNativeAddressLocation == null || processData.nullcDebugGetReversedStackDataBase == null) { processData.nullcIsMissing = true; } } internal string ExecuteExpression(string expression, DkmStackContext stackContext, DkmStackWalkFrame input, bool allowZero) { var compilerId = new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.Cpp); var language = DkmLanguage.Create("C++", compilerId); var languageExpression = DkmLanguageExpression.Create(language, DkmEvaluationFlags.None, expression, null); var inspectionContext = DkmInspectionContext.Create(stackContext.InspectionSession, input.RuntimeInstance, stackContext.Thread, 200, DkmEvaluationFlags.None, DkmFuncEvalFlags.None, 10, language, null); var workList = DkmWorkList.Create(null); string resultText = null; inspectionContext.EvaluateExpression(workList, languageExpression, input, res => { if (res.ErrorCode == 0) { var result = res.ResultObject as DkmSuccessEvaluationResult; if (result != null && result.TagValue == DkmEvaluationResult.Tag.SuccessResult && (allowZero || result.Address.Value != 0)) { resultText = result.Value; } res.ResultObject.Close(); } }); workList.Execute(); return resultText; } DkmStackWalkFrame[] IDkmCallStackFilter.FilterNextFrame(DkmStackContext stackContext, DkmStackWalkFrame input) { if (input == null) // null input frame indicates the end of the call stack. This sample does nothing on end-of-stack. { var processData = DebugHelpers.GetOrCreateDataItem<NullcStackFilterDataItem>(stackContext.InspectionSession.Process); processData.nullcFramePosition = 1; return null; } if (input.InstructionAddress == null) { return new DkmStackWalkFrame[1] { input }; } if (input.InstructionAddress.ModuleInstance != null) { if (input.BasicSymbolInfo != null && input.BasicSymbolInfo.MethodName == "ExecutorRegVm::RunCode") { var processData = DebugHelpers.GetOrCreateDataItem<NullcStackFilterDataItem>(input.Thread.Process); InitNullcDebugFunctions(processData, input.RuntimeInstance); if (processData.nullcIsMissing) { return new DkmStackWalkFrame[1] { input }; } string vmInstructionStr = ExecuteExpression("instruction - codeBase", stackContext, input, true); string ptrValue = DebugHelpers.Is64Bit(input.Thread.Process) ? "longValue" : "intValue"; string vmDataOffsetStr = ExecuteExpression($"(unsigned long long)regFilePtr[1].{ptrValue} - (unsigned long long)rvm->dataStack.data", stackContext, input, true); if (vmInstructionStr != null && vmDataOffsetStr != null) { ulong vmInstruction = ulong.Parse(vmInstructionStr); string stackFrameDesc = ExecuteExpression($"((char*(*)(unsigned, unsigned)){processData.nullcDebugGetVmAddressLocation})({vmInstruction}, 0),sb", stackContext, input, false); var nullcCustomRuntime = input.Thread.Process.GetRuntimeInstances().OfType<DkmCustomRuntimeInstance>().FirstOrDefault(el => el.Id.RuntimeType == DebugHelpers.NullcVmRuntimeGuid); if (stackFrameDesc != null && nullcCustomRuntime != null) { var flags = input.Flags; flags = flags & ~(DkmStackWalkFrameFlags.NonuserCode | DkmStackWalkFrameFlags.UserStatusNotDetermined); flags = flags | DkmStackWalkFrameFlags.InlineOptimized; DkmCustomModuleInstance nullcModuleInstance = nullcCustomRuntime.GetModuleInstances().OfType<DkmCustomModuleInstance>().FirstOrDefault(el => el.Module != null && el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); if (nullcModuleInstance != null) { DkmInstructionAddress instructionAddress = DkmCustomInstructionAddress.Create(nullcCustomRuntime, nullcModuleInstance, null, vmInstruction, null, null); var rawAnnotations = new List<DkmStackWalkFrameAnnotation>(); // Additional unique request id rawAnnotations.Add(DkmStackWalkFrameAnnotation.Create(DebugHelpers.NullcCallStackDataBaseGuid, ulong.Parse(vmDataOffsetStr))); var annotations = new ReadOnlyCollection<DkmStackWalkFrameAnnotation>(rawAnnotations); DkmStackWalkFrame frame = DkmStackWalkFrame.Create(stackContext.Thread, instructionAddress, input.FrameBase, input.FrameSize, flags, stackFrameDesc, input.Registers, annotations, nullcModuleInstance, null, null); return new DkmStackWalkFrame[2] { frame, input }; } } } } return new DkmStackWalkFrame[1] { input }; } // Currently we want to provide info only for JiT frames if (!input.Flags.HasFlag(DkmStackWalkFrameFlags.UserStatusNotDetermined)) { return new DkmStackWalkFrame[1] { input }; } try { var processData = DebugHelpers.GetOrCreateDataItem<NullcStackFilterDataItem>(input.Thread.Process); InitNullcDebugFunctions(processData, input.RuntimeInstance); if (processData.nullcIsMissing) return new DkmStackWalkFrame[1] { input }; string stackFrameDesc = ExecuteExpression($"((char*(*)(void*, unsigned)){processData.nullcDebugGetNativeAddressLocation})((void*)0x{input.InstructionAddress.CPUInstructionPart.InstructionPointer:X}, 0),sb", stackContext, input, false); if (stackFrameDesc != null) { var flags = input.Flags; flags = flags & ~(DkmStackWalkFrameFlags.NonuserCode | DkmStackWalkFrameFlags.UserStatusNotDetermined); if (stackFrameDesc == "[Transition to nullc]") { return new DkmStackWalkFrame[1] { DkmStackWalkFrame.Create(stackContext.Thread, input.InstructionAddress, input.FrameBase, input.FrameSize, flags, stackFrameDesc, input.Registers, input.Annotations) }; } DkmStackWalkFrame frame = null; var nullcCustomRuntime = input.Thread.Process.GetRuntimeInstances().OfType<DkmCustomRuntimeInstance>().FirstOrDefault(el => el.Id.RuntimeType == DebugHelpers.NullcRuntimeGuid); var nullcNativeRuntime = DebugHelpers.useDefaultRuntimeInstance ? input.Thread.Process.GetNativeRuntimeInstance() : input.Thread.Process.GetRuntimeInstances().OfType<DkmNativeRuntimeInstance>().FirstOrDefault(el => el.Id.RuntimeType == DebugHelpers.NullcRuntimeGuid); if (DebugHelpers.useNativeInterfaces ? nullcNativeRuntime != null : nullcCustomRuntime != null) { DkmModuleInstance nullcModuleInstance; if (DebugHelpers.useNativeInterfaces) { nullcModuleInstance = nullcNativeRuntime.GetModuleInstances().OfType<DkmNativeModuleInstance>().FirstOrDefault(el => el.Module != null && el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); } else { nullcModuleInstance = nullcCustomRuntime.GetModuleInstances().OfType<DkmCustomModuleInstance>().FirstOrDefault(el => el.Module != null && el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); } if (nullcModuleInstance != null) { // If the top of the call stack is a nullc frame, nullc call stack wont have an entry for it and we start from 0, otherwise we start from default value of 1 if (input.Flags.HasFlag(DkmStackWalkFrameFlags.TopFrame)) { processData.nullcFramePosition = 0; } string stackFrameBase = ExecuteExpression($"((unsigned(*)(unsigned)){processData.nullcDebugGetReversedStackDataBase})({processData.nullcFramePosition})", stackContext, input, true); processData.nullcFramePosition++; if (int.TryParse(stackFrameBase, out int stackFrameBaseValue)) { DkmInstructionAddress instructionAddress; if (DebugHelpers.useNativeInterfaces) { var rva = (uint)(input.InstructionAddress.CPUInstructionPart.InstructionPointer - nullcModuleInstance.BaseAddress); instructionAddress = DkmNativeInstructionAddress.Create(nullcNativeRuntime, nullcModuleInstance as DkmNativeModuleInstance, rva, input.InstructionAddress.CPUInstructionPart); } else { instructionAddress = DkmCustomInstructionAddress.Create(nullcCustomRuntime, nullcModuleInstance as DkmCustomModuleInstance, null, input.InstructionAddress.CPUInstructionPart.InstructionPointer, null, input.InstructionAddress.CPUInstructionPart); } var rawAnnotations = new List<DkmStackWalkFrameAnnotation>(); // Additional unique request id rawAnnotations.Add(DkmStackWalkFrameAnnotation.Create(DebugHelpers.NullcCallStackDataBaseGuid, (ulong)(stackFrameBaseValue))); var annotations = new ReadOnlyCollection<DkmStackWalkFrameAnnotation>(rawAnnotations); frame = DkmStackWalkFrame.Create(stackContext.Thread, instructionAddress, input.FrameBase, input.FrameSize, flags, stackFrameDesc, input.Registers, annotations, nullcModuleInstance, null, null); } } } if (frame == null) { frame = DkmStackWalkFrame.Create(stackContext.Thread, input.InstructionAddress, input.FrameBase, input.FrameSize, flags, stackFrameDesc, input.Registers, input.Annotations); } return new DkmStackWalkFrame[1] { frame }; } } catch (Exception ex) { Console.WriteLine("Failed to evaluate: " + ex.ToString()); } return new DkmStackWalkFrame[1] { input }; } void IDkmInstructionAddressProvider.GetInstructionAddress(DkmProcess process, DkmWorkList workList, ulong instructionPointer, DkmCompletionRoutine<DkmGetInstructionAddressAsyncResult> completionRoutine) { var processData = DebugHelpers.GetOrCreateDataItem<NullcModuleDataItem>(process); if (!processData.nullcIsMissing && processData.moduleBase == 0) { processData.moduleBase = DebugHelpers.ReadPointerVariable(process, "nullcModuleStartAddress").GetValueOrDefault(0); processData.moduleSize = (uint)(DebugHelpers.ReadPointerVariable(process, "nullcModuleEndAddress").GetValueOrDefault(0) - processData.moduleBase); processData.nullcIsMissing = processData.moduleBase == 0; } if (processData.moduleBase != 0) { if (instructionPointer >= processData.moduleBase && instructionPointer < processData.moduleBase + processData.moduleSize) { DkmInstructionAddress address; if (DebugHelpers.useNativeInterfaces) { var nullcNativeRuntime = DebugHelpers.useDefaultRuntimeInstance ? process.GetNativeRuntimeInstance() : process.GetRuntimeInstances().OfType<DkmNativeRuntimeInstance>().FirstOrDefault(el => el.Id.RuntimeType == DebugHelpers.NullcRuntimeGuid); var nullcModuleInstance = nullcNativeRuntime.GetModuleInstances().OfType<DkmNativeModuleInstance>().FirstOrDefault(el => el.Module != null && el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); address = DkmNativeInstructionAddress.Create(nullcNativeRuntime, nullcModuleInstance, (uint)(instructionPointer - processData.moduleBase), new DkmInstructionAddress.CPUInstruction(instructionPointer)); } else { var nullcNativeRuntime = process.GetRuntimeInstances().OfType<DkmCustomRuntimeInstance>().FirstOrDefault(el => el.Id.RuntimeType == DebugHelpers.NullcRuntimeGuid); var nullcModuleInstance = nullcNativeRuntime.GetModuleInstances().OfType<DkmCustomModuleInstance>().FirstOrDefault(el => el.Module != null && el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); address = DkmCustomInstructionAddress.Create(nullcNativeRuntime, nullcModuleInstance, null, instructionPointer, null, new DkmInstructionAddress.CPUInstruction(instructionPointer)); } completionRoutine(new DkmGetInstructionAddressAsyncResult(address, true)); return; } } process.GetInstructionAddress(workList, instructionPointer, completionRoutine); } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Text; namespace Microsoft.PythonTools.Parsing.Ast { public class FunctionDefinition : ScopeStatement { protected Statement _body; private readonly NameExpression/*!*/ _name; private readonly Parameter[] _parameters; private Expression _returnAnnotation; private DecoratorStatement _decorators; private bool _generator; // The function is a generator private bool _coroutine; private bool _isLambda; private PythonVariable _variable; // The variable corresponding to the function name or null for lambdas internal PythonVariable _nameVariable; // the variable that refers to the global __name__ internal bool _hasReturn; private int _headerIndex; internal static readonly object WhitespaceAfterAsync = new object(); public FunctionDefinition(NameExpression name, Parameter[] parameters) : this(name, parameters, (Statement)null) { } public FunctionDefinition(NameExpression name, Parameter[] parameters, Statement body, DecoratorStatement decorators = null) { if (name == null) { _name = new NameExpression("<lambda>"); _isLambda = true; } else { _name = name; } _parameters = parameters; _body = body; _decorators = decorators; } public bool IsLambda { get { return _isLambda; } } public IList<Parameter> Parameters { get { return _parameters; } } internal override int ArgCount { get { return _parameters.Length; } } public Expression ReturnAnnotation { get { return _returnAnnotation; } set { _returnAnnotation = value; } } public override Statement Body { get { return _body; } } internal void SetBody(Statement body) { _body = body; } public int HeaderIndex { get { return _headerIndex; } set { _headerIndex = value; } } public override string/*!*/ Name { get { return _name.Name ?? ""; } } public NameExpression NameExpression { get { return _name; } } public DecoratorStatement Decorators { get { return _decorators; } internal set { _decorators = value; } } /// <summary> /// True if the function is a generator. Generators contain at least one yield /// expression and instead of returning a value when called they return a generator /// object which implements the iterator protocol. /// </summary> public bool IsGenerator { get { return _generator; } set { _generator = value; } } /// <summary> /// True if the function is a coroutine. Coroutines are defined using /// 'async def'. /// </summary> public bool IsCoroutine { get { return _coroutine; } set { _coroutine = value; } } /// <summary> /// Gets the variable that this function is assigned to. /// </summary> public PythonVariable Variable { get { return _variable; } set { _variable = value; } } /// <summary> /// Gets the variable reference for the specific assignment to the variable for this function definition. /// </summary> public PythonReference GetVariableReference(PythonAst ast) { return GetVariableReference(this, ast); } internal override bool ExposesLocalVariable(PythonVariable variable) { return NeedsLocalsDictionary; } internal override bool TryBindOuter(ScopeStatement from, string name, bool allowGlobals, out PythonVariable variable) { // Functions expose their locals to direct access ContainsNestedFreeVariables = true; if (TryGetVariable(name, out variable)) { variable.AccessedInNestedScope = true; if (variable.Kind == VariableKind.Local || variable.Kind == VariableKind.Parameter) { from.AddFreeVariable(variable, true); for (ScopeStatement scope = from.Parent; scope != this; scope = scope.Parent) { scope.AddFreeVariable(variable, false); } AddCellVariable(variable); } else if(allowGlobals) { from.AddReferencedGlobal(name); } return true; } return false; } internal override PythonVariable BindReference(PythonNameBinder binder, string name) { PythonVariable variable; // First try variables local to this scope if (TryGetVariable(name, out variable) && variable.Kind != VariableKind.Nonlocal) { if (variable.Kind == VariableKind.Global) { AddReferencedGlobal(name); } return variable; } // Try to bind in outer scopes for (ScopeStatement parent = Parent; parent != null; parent = parent.Parent) { if (parent.TryBindOuter(this, name, true, out variable)) { return variable; } } return null; } internal override void Bind(PythonNameBinder binder) { base.Bind(binder); Verify(binder); } private void Verify(PythonNameBinder binder) { if (ContainsImportStar && IsClosure) { binder.ReportSyntaxError( String.Format( System.Globalization.CultureInfo.InvariantCulture, "import * is not allowed in function '{0}' because it is a nested function", Name), this); } if (ContainsImportStar && Parent is FunctionDefinition) { binder.ReportSyntaxError( String.Format( System.Globalization.CultureInfo.InvariantCulture, "import * is not allowed in function '{0}' because it is a nested function", Name), this); } if (ContainsImportStar && ContainsNestedFreeVariables) { binder.ReportSyntaxError( String.Format( System.Globalization.CultureInfo.InvariantCulture, "import * is not allowed in function '{0}' because it contains a nested function with free variables", Name), this); } if (ContainsUnqualifiedExec && ContainsNestedFreeVariables) { binder.ReportSyntaxError( String.Format( System.Globalization.CultureInfo.InvariantCulture, "unqualified exec is not allowed in function '{0}' because it contains a nested function with free variables", Name), this); } if (ContainsUnqualifiedExec && IsClosure) { binder.ReportSyntaxError( String.Format( System.Globalization.CultureInfo.InvariantCulture, "unqualified exec is not allowed in function '{0}' because it is a nested function", Name), this); } } public override void Walk(PythonWalker walker) { if (walker.Walk(this)) { if (_parameters != null) { foreach (Parameter p in _parameters) { p.Walk(walker); } } if (_decorators != null) { _decorators.Walk(walker); } if (_body != null) { _body.Walk(walker); } } walker.PostWalk(this); } public SourceLocation Header { get { return GlobalParent.IndexToLocation(_headerIndex); } } public override string GetLeadingWhiteSpace(PythonAst ast) { if (Decorators != null) { return Decorators.GetLeadingWhiteSpace(ast); } return base.GetLeadingWhiteSpace(ast); } public override void SetLeadingWhiteSpace(PythonAst ast, string whiteSpace) { if (Decorators != null) { Decorators.SetLeadingWhiteSpace(ast, whiteSpace); return; } base.SetLeadingWhiteSpace(ast, whiteSpace); } internal override void AppendCodeStringStmt(StringBuilder res, PythonAst ast, CodeFormattingOptions format) { var decorateWhiteSpace = this.GetNamesWhiteSpace(ast); if (Decorators != null) { Decorators.AppendCodeString(res, ast, format); } format.ReflowComment(res, this.GetProceedingWhiteSpaceDefaultNull(ast)); if (IsCoroutine) { res.Append("async"); res.Append(NodeAttributes.GetWhiteSpace(this, ast, WhitespaceAfterAsync)); } res.Append("def"); var name = this.GetVerbatimImage(ast) ?? Name; if (!String.IsNullOrEmpty(name)) { res.Append(this.GetSecondWhiteSpace(ast)); res.Append(name); if (!this.IsIncompleteNode(ast)) { format.Append( res, format.SpaceBeforeFunctionDeclarationParen, " ", "", this.GetThirdWhiteSpaceDefaultNull(ast) ); res.Append('('); if (Parameters.Count != 0) { var commaWhiteSpace = this.GetListWhiteSpace(ast); ParamsToString(res, ast, commaWhiteSpace, format, format.SpaceWithinFunctionDeclarationParens != null ? format.SpaceWithinFunctionDeclarationParens.Value ? " " : "" : null ); } string namedOnly = this.GetExtraVerbatimText(ast); if (namedOnly != null) { res.Append(namedOnly); } if (!this.IsMissingCloseGrouping(ast)) { format.Append( res, Parameters.Count != 0 ? format.SpaceWithinFunctionDeclarationParens : format.SpaceWithinEmptyParameterList, " ", "", this.GetFourthWhiteSpaceDefaultNull(ast) ); res.Append(')'); } if (ReturnAnnotation != null) { format.Append( res, format.SpaceAroundAnnotationArrow, " ", "", this.GetFifthWhiteSpace(ast) ); res.Append("->"); _returnAnnotation.AppendCodeString( res, ast, format, format.SpaceAroundAnnotationArrow != null ? format.SpaceAroundAnnotationArrow.Value ? " " : "" : null ); } if (Body != null) { Body.AppendCodeString(res, ast, format); } } } } internal void ParamsToString(StringBuilder res, PythonAst ast, string[] commaWhiteSpace, CodeFormattingOptions format, string initialLeadingWhiteSpace = null) { for (int i = 0; i < Parameters.Count; i++) { if (i > 0) { if (commaWhiteSpace != null) { res.Append(commaWhiteSpace[i - 1]); } res.Append(','); } Parameters[i].AppendCodeString(res, ast, format, initialLeadingWhiteSpace); initialLeadingWhiteSpace = null; } if (commaWhiteSpace != null && commaWhiteSpace.Length == Parameters.Count && Parameters.Count != 0) { // trailing comma res.Append(commaWhiteSpace[commaWhiteSpace.Length - 1]); res.Append(","); } } } }
using System.Diagnostics; namespace System.Threading.Atomics { /// <summary> /// An <see cref="long"/> value wrapper with atomic operations /// </summary> [DebuggerDisplay("{Value}")] #pragma warning disable 0659, 0661 public sealed class AtomicLong : IAtomic<long>, IEquatable<long> #pragma warning restore 0659, 0661 { private volatile MemoryOrder _order; // making volatile to prohibit reordering in constructors private long _value; private volatile object _instanceLock; /// <summary> /// Creates new instance of <see cref="AtomicLong"/> /// </summary> /// <param name="order">Affects the way store operation occur. Default is <see cref="MemoryOrder.AcqRel"/> semantics</param> public AtomicLong(MemoryOrder order = MemoryOrder.AcqRel) { if (!order.IsSpported()) throw new ArgumentException(string.Format("{0} is not supported", order)); if (order == MemoryOrder.SeqCst) _instanceLock = new object(); _order = order; } /// <summary> /// Creates new instance of <see cref="AtomicLong"/> /// </summary> /// <param name="value">The value to store</param> /// <param name="order">Affects the way store operation occur. Load operations are always use <see cref="MemoryOrder.Acquire"/> semantics</param> public AtomicLong(long value, MemoryOrder order = MemoryOrder.AcqRel) { if (!order.IsSpported()) throw new ArgumentException(string.Format("{0} is not supported", order)); if (order == MemoryOrder.SeqCst) _instanceLock = new object(); _order = order; this.Value = value; } /// <summary> /// Gets or sets atomically the underlying value /// </summary> public long Value { get { if (_order != MemoryOrder.SeqCst) return Volatile.Read(ref _value); lock (_instanceLock) { return Volatile.Read(ref _value); } } set { if (_order == MemoryOrder.SeqCst) { lock (_instanceLock) { Interlocked.Exchange(ref _value, value); // for processors cache coherence } } else if (_order.IsAcquireRelease()) { // should use compare_exchange_weak // but implementing CAS using compare_exchange_strong since we are on .NET long currentValue = Interlocked.Read(ref _value); long tempValue; do { tempValue = Interlocked.CompareExchange(ref this._value, value, currentValue); } while (tempValue != currentValue); } } } /// <summary> /// Increments the <see cref="AtomicLong"/> operand by one. /// </summary> /// <param name="atomicLong">The value to increment.</param> /// <returns>The value of <paramref name="atomicLong"/> incremented by 1.</returns> public static AtomicLong operator ++(AtomicLong atomicLong) { return Interlocked.Increment(ref atomicLong._value); } /// <summary> /// Decrements the <see cref="AtomicLong"/> operand by one. /// </summary> /// <param name="atomicLong">The value to decrement.</param> /// <returns>The value of <paramref name="atomicLong"/> decremented by 1.</returns> public static AtomicLong operator --(AtomicLong atomicLong) { return Interlocked.Decrement(ref atomicLong._value); } /// <summary> /// Adds specified <paramref name="value"/> to <see cref="AtomicLong"/> and returns the result as a <see cref="long"/>. /// </summary> /// <param name="atomicLong">The <paramref name="atomicLong"/> used for addition.</param> /// <param name="value">The value to add</param> /// <returns>The result of adding value to <paramref name="atomicLong"/></returns> public static long operator +(AtomicLong atomicLong, long value) { return Interlocked.Add(ref atomicLong._value, value); } /// <summary> /// Subtracts <paramref name="value"/> from <paramref name="atomicLong"/> and returns the result as a <see cref="long"/>. /// </summary> /// <param name="atomicLong">The <paramref name="atomicLong"/> from which <paramref name="value"/> is subtracted.</param> /// <param name="value">The value to subtract from <paramref name="atomicLong"/></param> /// <returns>The result of subtracting value from <see cref="AtomicLong"/></returns> public static long operator -(AtomicLong atomicLong, long value) { return Interlocked.Add(ref atomicLong._value, -value); } /// <summary> /// Multiplies <see cref="AtomicLong"/> by specified <paramref name="value"/> and returns the result as a <see cref="long"/>. /// </summary> /// <param name="atomicLong">The <see cref="AtomicLong"/> to multiply.</param> /// <param name="value">The value to multiply</param> /// <returns>The result of multiplying <see cref="AtomicLong"/> and <paramref name="value"/></returns> public static long operator *(AtomicLong atomicLong, long value) { bool entered = false; long currentValue = atomicLong.Value; if (atomicLong._order == MemoryOrder.SeqCst) { Monitor.Enter(atomicLong._instanceLock, ref entered); } long result = currentValue * value; try { long tempValue; do { tempValue = Interlocked.CompareExchange(ref atomicLong._value, result, currentValue); } while (tempValue != currentValue); } finally { if (entered) Monitor.Exit(atomicLong._instanceLock); } return result; } /// <summary> /// Divides the specified <see cref="AtomicLong"/> by the specified <paramref name="value"/> and returns the resulting as <see cref="long"/>. /// </summary> /// <param name="atomicLong">The <see cref="AtomicLong"/> to divide</param> /// <param name="value">The value by which <paramref name="atomicLong"/> will be divided.</param> /// <returns>The result of dividing <paramref name="atomicLong"/> by <paramref name="value"/>.</returns> public static long operator /(AtomicLong atomicLong, long value) { if (value == 0) throw new DivideByZeroException(); bool entered = false; long currentValue = atomicLong.Value; if (atomicLong._order == MemoryOrder.SeqCst) { Monitor.Enter(atomicLong._instanceLock, ref entered); } long result = currentValue / value; try { long tempValue; do { tempValue = Interlocked.CompareExchange(ref atomicLong._value, result, currentValue); } while (tempValue != currentValue); } finally { if (entered) Monitor.Exit(atomicLong._instanceLock); } return result; } /// <summary> /// Defines an implicit conversion of a <see cref="AtomicLong"/> to a 64-bit signed integer. /// </summary> /// <param name="atomicLong">The <see cref="AtomicLong"/> to convert.</param> /// <returns>The converted <see cref="AtomicLong"/>.</returns> public static implicit operator long(AtomicLong atomicLong) { return atomicLong.Value; } /// <summary> /// Defines an implicit conversion of a 64-bit signed integer to a <see cref="AtomicLong"/>. /// </summary> /// <param name="value">The 64-bit signed integer to convert.</param> /// <returns>The converted 64-bit signed integer.</returns> public static implicit operator AtomicLong(long value) { return new AtomicLong(value); } /// <summary> /// Returns a value that indicates whether <see cref="AtomicLong"/> and <see cref="long"/> are equal. /// </summary> /// <param name="x">The first value (<see cref="AtomicLong"/>) to compare.</param> /// <param name="y">The second value (<see cref="long"/>) to compare.</param> /// <returns><c>true</c> if <paramref name="x"/> and <paramref name="y"/> are equal; otherwise, <c>false</c>.</returns> public static bool operator ==(AtomicLong x, long y) { return (x != null && x.Value == y); } /// <summary> /// Returns a value that indicates whether <see cref="AtomicLong"/> and <see cref="long"/> have different values. /// </summary> /// <param name="x">The first value (<see cref="AtomicLong"/>) to compare.</param> /// <param name="y">The second value (<see cref="long"/>) to compare.</param> /// <returns><c>true</c> if <paramref name="x"/> and <paramref name="y"/> are not equal; otherwise, <c>false</c>.</returns> public static bool operator !=(AtomicLong x, long y) { return (x != null && x.Value != y); } /// <summary> /// Returns a value indicating whether this instance and a specified Object represent the same type and value. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns><c>true</c> if <paramref name="obj"/> is a <see cref="AtomicLong"/> and equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { AtomicLong other = obj as AtomicLong; if (other == null) return false; return object.ReferenceEquals(this, other) || this.Value == other.Value; } /// <summary> /// Returns a value indicating whether this instance and a specified <see cref="AtomicLong"/> object represent the same value. /// </summary> /// <param name="other">An object to compare to this instance.</param> /// <returns><c>true</c> if <paramref name="other"/> is equal to this instance; otherwise, <c>false</c>.</returns> bool IEquatable<long>.Equals(long other) { return this.Value == other; } long IAtomic<long>.Value { get { return this.Value; } set { this.Value = value; } } long IAtomicsOperator<long>.CompareExchange(ref long location1, long value, long comparand) { return Interlocked.CompareExchange(ref location1, value, comparand); } long IAtomicsOperator<long>.Read(ref long location1) { return Volatile.Read(ref location1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.Net { internal enum CookieToken { // State types Nothing, NameValuePair, // X=Y Attribute, // X EndToken, // ';' EndCookie, // ',' End, // EOLN Equals, // Value types Comment, CommentUrl, CookieName, Discard, Domain, Expires, MaxAge, Path, Port, Secure, HttpOnly, Unknown, Version } // CookieTokenizer // // Used to split a single or multi-cookie (header) string into individual // tokens. internal class CookieTokenizer { private bool _eofCookie; private int _index; private int _length; private string _name; private bool _quoted; private int _start; private CookieToken _token; private int _tokenLength; private string _tokenStream; private string _value; private int _cookieStartIndex; private int _cookieLength; internal CookieTokenizer(string tokenStream) { _length = tokenStream.Length; _tokenStream = tokenStream; } internal bool EndOfCookie { get { return _eofCookie; } set { _eofCookie = value; } } internal bool Eof { get { return _index >= _length; } } internal string Name { get { return _name; } set { _name = value; } } internal bool Quoted { get { return _quoted; } set { _quoted = value; } } internal CookieToken Token { get { return _token; } set { _token = value; } } internal string Value { get { return _value; } set { _value = value; } } // GetCookieString // // Gets the full string of the cookie internal string GetCookieString() { return _tokenStream.SubstringTrim(_cookieStartIndex, _cookieLength); } // Extract // // Extracts the current token internal string Extract() { string tokenString = string.Empty; if (_tokenLength != 0) { tokenString = Quoted ? _tokenStream.Substring(_start, _tokenLength) : _tokenStream.SubstringTrim(_start, _tokenLength); } return tokenString; } // FindNext // // Find the start and length of the next token. The token is terminated // by one of: // - end-of-line // - end-of-cookie: unquoted comma separates multiple cookies // - end-of-token: unquoted semi-colon // - end-of-name: unquoted equals // // Inputs: // <argument> ignoreComma // true if parsing doesn't stop at a comma. This is only true when // we know we're parsing an original cookie that has an expires= // attribute, because the format of the time/date used in expires // is: // Wdy, dd-mmm-yyyy HH:MM:SS GMT // // <argument> ignoreEquals // true if parsing doesn't stop at an equals sign. The LHS of the // first equals sign is an attribute name. The next token may // include one or more equals signs. For example: // SESSIONID=ID=MSNx45&q=33 // // Outputs: // <member> _index // incremented to the last position in _tokenStream contained by // the current token // // <member> _start // incremented to the start of the current token // // <member> _tokenLength // set to the length of the current token // // Assumes: Nothing // // Returns: // type of CookieToken found: // // End - end of the cookie string // EndCookie - end of current cookie in (potentially) a // multi-cookie string // EndToken - end of name=value pair, or end of an attribute // Equals - end of name= // // Throws: Nothing internal CookieToken FindNext(bool ignoreComma, bool ignoreEquals) { _tokenLength = 0; _start = _index; while ((_index < _length) && Char.IsWhiteSpace(_tokenStream[_index])) { ++_index; ++_start; } CookieToken token = CookieToken.End; int increment = 1; if (!Eof) { if (_tokenStream[_index] == '"') { Quoted = true; ++_index; bool quoteOn = false; while (_index < _length) { char currChar = _tokenStream[_index]; if (!quoteOn && currChar == '"') { break; } if (quoteOn) { quoteOn = false; } else if (currChar == '\\') { quoteOn = true; } ++_index; } if (_index < _length) { ++_index; } _tokenLength = _index - _start; increment = 0; // If we are here, reset ignoreComma. // In effect, we ignore everything after quoted string until the next delimiter. ignoreComma = false; } while ((_index < _length) && (_tokenStream[_index] != ';') && (ignoreEquals || (_tokenStream[_index] != '=')) && (ignoreComma || (_tokenStream[_index] != ','))) { // Fixing 2 things: // 1) ignore day of week in cookie string // 2) revert ignoreComma once meet it, so won't miss the next cookie) if (_tokenStream[_index] == ',') { _start = _index + 1; _tokenLength = -1; ignoreComma = false; } ++_index; _tokenLength += increment; } if (!Eof) { switch (_tokenStream[_index]) { case ';': token = CookieToken.EndToken; break; case '=': token = CookieToken.Equals; break; default: _cookieLength = _index - _cookieStartIndex; token = CookieToken.EndCookie; break; } ++_index; } if (Eof) { _cookieLength = _index - _cookieStartIndex; } } return token; } // Next // // Get the next cookie name/value or attribute // // Cookies come in the following formats: // // 1. Version0 // Set-Cookie: [<name>][=][<value>] // [; expires=<date>] // [; path=<path>] // [; domain=<domain>] // [; secure] // Cookie: <name>=<value> // // Notes: <name> and/or <value> may be blank // <date> is the RFC 822/1123 date format that // incorporates commas, e.g. // "Wednesday, 09-Nov-99 23:12:40 GMT" // // 2. RFC 2109 // Set-Cookie: 1#{ // <name>=<value> // [; comment=<comment>] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // } // // 3. RFC 2965 // Set-Cookie2: 1#{ // <name>=<value> // [; comment=<comment>] // [; commentURL=<comment>] // [; discard] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; ports=<portlist>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // [; port="<port>"] // } // [Cookie2: $Version=<version>] // // Inputs: // <argument> first // true if this is the first name/attribute that we have looked for // in the cookie stream // // Outputs: // // Assumes: // Nothing // // Returns: // type of CookieToken found: // // - Attribute // - token was single-value. May be empty. Caller should check // Eof or EndCookie to determine if any more action needs to // be taken // // - NameValuePair // - Name and Value are meaningful. Either may be empty // // Throws: // Nothing internal CookieToken Next(bool first, bool parseResponseCookies) { Reset(); if (first) { _cookieStartIndex = _index; _cookieLength = 0; } CookieToken terminator = FindNext(false, false); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } if ((terminator == CookieToken.End) || (terminator == CookieToken.EndCookie)) { if ((Name = Extract()).Length != 0) { Token = TokenFromName(parseResponseCookies); return CookieToken.Attribute; } return terminator; } Name = Extract(); if (first) { Token = CookieToken.CookieName; } else { Token = TokenFromName(parseResponseCookies); } if (terminator == CookieToken.Equals) { terminator = FindNext(!first && (Token == CookieToken.Expires), true); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } Value = Extract(); return CookieToken.NameValuePair; } else { return CookieToken.Attribute; } } // Reset // // Sets this tokenizer up for finding the next name/value pair, // attribute, or end-of-{token,cookie,line}. internal void Reset() { _eofCookie = false; _name = string.Empty; _quoted = false; _start = _index; _token = CookieToken.Nothing; _tokenLength = 0; _value = string.Empty; } private struct RecognizedAttribute { private string _name; private CookieToken _token; internal RecognizedAttribute(string name, CookieToken token) { _name = name; _token = token; } internal CookieToken Token { get { return _token; } } internal bool IsEqualTo(string value) { return string.Equals(_name, value, StringComparison.OrdinalIgnoreCase); } } // Recognized attributes in order of expected frequency. private static readonly RecognizedAttribute[] s_recognizedAttributes = { new RecognizedAttribute(CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute(CookieFields.MaxAgeAttributeName, CookieToken.MaxAge), new RecognizedAttribute(CookieFields.ExpiresAttributeName, CookieToken.Expires), new RecognizedAttribute(CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute(CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute(CookieFields.SecureAttributeName, CookieToken.Secure), new RecognizedAttribute(CookieFields.DiscardAttributeName, CookieToken.Discard), new RecognizedAttribute(CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute(CookieFields.CommentAttributeName, CookieToken.Comment), new RecognizedAttribute(CookieFields.CommentUrlAttributeName, CookieToken.CommentUrl), new RecognizedAttribute(CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; private static readonly RecognizedAttribute[] s_recognizedServerAttributes = { new RecognizedAttribute('$' + CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute('$' + CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute('$' + CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute('$' + CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute('$' + CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; internal CookieToken TokenFromName(bool parseResponseCookies) { if (!parseResponseCookies) { for (int i = 0; i < s_recognizedServerAttributes.Length; ++i) { if (s_recognizedServerAttributes[i].IsEqualTo(Name)) { return s_recognizedServerAttributes[i].Token; } } } else { for (int i = 0; i < s_recognizedAttributes.Length; ++i) { if (s_recognizedAttributes[i].IsEqualTo(Name)) { return s_recognizedAttributes[i].Token; } } } return CookieToken.Unknown; } } // CookieParser // // Takes a cookie header, makes cookies. internal class CookieParser { private CookieTokenizer _tokenizer; private Cookie _savedCookie; internal CookieParser(string cookieString) { _tokenizer = new CookieTokenizer(cookieString); } // GetString // // Gets the next cookie string internal string GetString() { bool first = true; if (_tokenizer.Eof) { return null; } do { _tokenizer.Next(first, true); first = false; } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return _tokenizer.GetCookieString(); } #if SYSTEM_NET_PRIMITIVES_DLL private static bool InternalSetNameMethod(Cookie cookie, string value) { return cookie.InternalSetName(value); } #else private static Func<Cookie, string, bool> s_internalSetNameMethod; private static Func<Cookie, string, bool> InternalSetNameMethod { get { if (s_internalSetNameMethod == null) { // TODO: #13607 // We need to use Cookie.InternalSetName instead of the Cookie.set_Name wrapped in a try catch block, as // Cookie.set_Name keeps the original name if the string is empty or null. // Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons. BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif MethodInfo method = typeof(Cookie).GetMethod("InternalSetName", flags); Debug.Assert(method != null, "We need to use an internal method named InternalSetName that is declared on Cookie."); s_internalSetNameMethod = (Func<Cookie, string, bool>)Delegate.CreateDelegate(typeof(Func<Cookie, string, bool>), method); } return s_internalSetNameMethod; } } #endif private static FieldInfo s_isQuotedDomainField = null; private static FieldInfo IsQuotedDomainField { get { if (s_isQuotedDomainField == null) { // TODO: #13607 BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", flags); Debug.Assert(field != null, "We need to use an internal field named IsQuotedDomain that is declared on Cookie."); s_isQuotedDomainField = field; } return s_isQuotedDomainField; } } private static FieldInfo s_isQuotedVersionField = null; private static FieldInfo IsQuotedVersionField { get { if (s_isQuotedVersionField == null) { // TODO: #13607 BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif FieldInfo field = typeof(Cookie).GetField("IsQuotedVersion", flags); Debug.Assert(field != null, "We need to use an internal field named IsQuotedVersion that is declared on Cookie."); s_isQuotedVersionField = field; } return s_isQuotedVersionField; } } // Get // // Gets the next cookie or null if there are no more cookies. internal Cookie Get() { Cookie cookie = null; // Only the first occurrence of an attribute value must be counted. bool commentSet = false; bool commentUriSet = false; bool domainSet = false; bool expiresSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. bool versionSet = false; bool secureSet = false; bool discardSet = false; do { CookieToken token = _tokenizer.Next(cookie == null, true); if (cookie == null && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { cookie = new Cookie(); InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Comment: if (!commentSet) { commentSet = true; cookie.Comment = _tokenizer.Value; } break; case CookieToken.CommentUrl: if (!commentUriSet) { commentUriSet = true; if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out Uri parsed)) { cookie.CommentUri = parsed; } } break; case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Expires: if (!expiresSet) { expiresSet = true; if (DateTime.TryParse(CheckQuoted(_tokenizer.Value), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime expires)) { cookie.Expires = expires; } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.MaxAge: if (!expiresSet) { expiresSet = true; if (int.TryParse(CheckQuoted(_tokenizer.Value), out int parsed)) { cookie.Expires = DateTime.Now.AddSeconds(parsed); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: if (!versionSet) { versionSet = true; int parsed; if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed)) { cookie.Version = parsed; IsQuotedVersionField.SetValue(cookie, _tokenizer.Quoted); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; } break; case CookieToken.Attribute: switch (_tokenizer.Token) { case CookieToken.Discard: if (!discardSet) { discardSet = true; cookie.Discard = true; } break; case CookieToken.Secure: if (!secureSet) { secureSet = true; cookie.Secure = true; } break; case CookieToken.HttpOnly: cookie.HttpOnly = true; break; case CookieToken.Port: if (!portSet) { portSet = true; cookie.Port = string.Empty; } break; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal Cookie GetServer() { Cookie cookie = _savedCookie; _savedCookie = null; // Only the first occurrence of an attribute value must be counted. bool domainSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. do { bool first = cookie == null || string.IsNullOrEmpty(cookie.Name); CookieToken token = _tokenizer.Next(first, false); if (first && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { if (cookie == null) { cookie = new Cookie(); } InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch (CookieException) { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: // this is a new cookie, this token is for the next cookie. _savedCookie = new Cookie(); if (int.TryParse(_tokenizer.Value, out int parsed)) { _savedCookie.Version = parsed; } return cookie; case CookieToken.Unknown: // this is a new cookie, the token is for the next cookie. _savedCookie = new Cookie(); InternalSetNameMethod(_savedCookie, _tokenizer.Name); _savedCookie.Value = _tokenizer.Value; return cookie; } break; case CookieToken.Attribute: if (_tokenizer.Token == CookieToken.Port && !portSet) { portSet = true; cookie.Port = string.Empty; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal static string CheckQuoted(string value) { if (value.Length < 2 || value[0] != '\"' || value[value.Length - 1] != '\"') return value; return value.Length == 2 ? string.Empty : value.Substring(1, value.Length - 2); } } }
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Runtime.InteropServices { #if ENABLE_MIN_WINRT public static partial class McgMarshal { /// <summary> /// Creates a temporary HSTRING on the staack /// NOTE: pchPinnedSourceString must be pinned before calling this function, making sure the pointer /// is valid during the entire interop call /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe void StringToHStringReference( char* pchPinnedSourceString, string sourceString, HSTRING_HEADER* pHeader, HSTRING* phString) { if (sourceString == null) throw new ArgumentNullException("sourceString", SR.Null_HString); int hr = ExternalInterop.WindowsCreateStringReference( pchPinnedSourceString, (uint)sourceString.Length, pHeader, (void**)phString); if (hr < 0) throw Marshal.GetExceptionForHR(hr); } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static unsafe string HStringToString(IntPtr hString) { HSTRING hstring = new HSTRING(hString); return HStringToString(hstring); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe string HStringToString(HSTRING pHString) { if (pHString.handle == IntPtr.Zero) { return String.Empty; } uint length = 0; char* pchBuffer = ExternalInterop.WindowsGetStringRawBuffer(pHString.handle.ToPointer(), &length); return new string(pchBuffer, 0, (int)length); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe void FreeHString(IntPtr pHString) { ExternalInterop.WindowsDeleteString(pHString.ToPointer()); } } #endif public static partial class ExternalInterop { [DllImport(Libraries.CORE_WINRT)] [McgGeneratedNativeCallCodeAttribute] [MethodImplAttribute(MethodImplOptions.NoInlining)] public static extern unsafe int RoGetActivationFactory(void* hstring_typeName, Guid* iid, void* ppv); [DllImport(Libraries.CORE_WINRT_STRING)] [McgGeneratedNativeCallCodeAttribute] [MethodImplAttribute(MethodImplOptions.NoInlining)] static internal extern unsafe int WindowsCreateStringReference(char* sourceString, uint length, HSTRING_HEADER* phstringHeader, void* hstring); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] static internal unsafe extern int CoCreateFreeThreadedMarshaler(void* pOuter, void** ppunkMarshal); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] public static extern unsafe int CoGetContextToken(IntPtr* ppToken); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] static internal unsafe extern int CoGetObjectContext(Guid* iid, void* ppv); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] private static unsafe extern int CoGetMarshalSizeMax(ulong* pulSize, Guid* iid, IntPtr pUnk, Interop.COM.MSHCTX dwDestContext, IntPtr pvDestContext, Interop.COM.MSHLFLAGS mshlflags); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] private extern unsafe static int CoMarshalInterface(IntPtr pStream, Guid* iid, IntPtr pUnk, Interop.COM.MSHCTX dwDestContext, IntPtr pvDestContext, Interop.COM.MSHLFLAGS mshlflags); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] private static unsafe extern int CoUnmarshalInterface(IntPtr pStream, Guid* iid, void** ppv); [DllImport(Libraries.CORE_COM)] [McgGeneratedNativeCallCodeAttribute] [MethodImplAttribute(MethodImplOptions.NoInlining)] static internal extern int CoReleaseMarshalData(IntPtr pStream); /// <summary> /// Marshal IUnknown * into IStream* /// </summary> /// <returns>HResult</returns> static internal unsafe int CoMarshalInterface(IntPtr pStream, ref Guid iid, IntPtr pUnk, Interop.COM.MSHCTX dwDestContext, IntPtr pvDestContext, Interop.COM.MSHLFLAGS mshlflags) { fixed (Guid* unsafe_iid = &iid) { return CoMarshalInterface(pStream, unsafe_iid, pUnk, dwDestContext, pvDestContext, mshlflags); } } /// <summary> /// Marshal IStream* into IUnknown* /// </summary> /// <returns>HResult</returns> static internal unsafe int CoUnmarshalInterface(IntPtr pStream, ref Guid iid, out IntPtr ppv) { fixed (Guid* unsafe_iid = &iid) { fixed (void* unsafe_ppv = &ppv) { return CoUnmarshalInterface(pStream, unsafe_iid, (void**)unsafe_ppv); } } } /// <summary> /// Returns an upper bound on the number of bytes needed to marshal the specified interface pointer to the specified object. /// </summary> /// <returns>HResult</returns> static internal unsafe int CoGetMarshalSizeMax(out ulong pulSize, ref Guid iid, IntPtr pUnk, Interop.COM.MSHCTX dwDestContext, IntPtr pvDestContext, Interop.COM.MSHLFLAGS mshlflags) { fixed (ulong* unsafe_pulSize = &pulSize) { fixed (Guid* unsafe_iid = &iid) { return CoGetMarshalSizeMax(unsafe_pulSize, unsafe_iid, pUnk, dwDestContext, pvDestContext, mshlflags); } } } static internal unsafe void RoGetActivationFactory(string className, ref Guid iid, out IntPtr ppv) { fixed (char* unsafe_className = className) { void* hstring_typeName = null; HSTRING_HEADER hstringHeader; int hr = WindowsCreateStringReference( unsafe_className, (uint)className.Length, &hstringHeader, &hstring_typeName); if (hr < 0) throw Marshal.GetExceptionForHR(hr); fixed (Guid* unsafe_iid = &iid) { fixed (void* unsafe_ppv = &ppv) { hr = ExternalInterop.RoGetActivationFactory( hstring_typeName, unsafe_iid, unsafe_ppv); if (hr < 0) throw Marshal.GetExceptionForHR(hr); } } } } public static unsafe int CoGetContextToken(out IntPtr ppToken) { ppToken = IntPtr.Zero; fixed (IntPtr* unsafePpToken = &ppToken) { return CoGetContextToken(unsafePpToken); } } static internal unsafe int CoGetObjectContext(ref Guid iid, out IntPtr ppv) { fixed (void* unsafe_ppv = &ppv) { fixed (Guid* unsafe_iid = &iid) { return CoGetObjectContext(unsafe_iid, (void**)unsafe_ppv); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (c) 2004 Mainsoft Co. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; namespace System.Data.Tests { public class UniqueConstraintTest2 { [Fact] public void Columns() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); // Columns 1 Assert.Equal(1, uc.Columns.Length); // Columns 2 Assert.Equal(dtParent.Columns[0], uc.Columns[0]); } [Fact] public void Equals_O() { var ds = new DataSet(); DataTable dtParent = DataProvider.CreateParentDataTable(); ds.Tables.Add(dtParent); UniqueConstraint uc1, uc2; uc1 = new UniqueConstraint(dtParent.Columns[0]); uc2 = new UniqueConstraint(dtParent.Columns[1]); // different columnn Assert.Equal(false, uc1.Equals(uc2)); //Two System.Data.ForeignKeyConstraint are equal if they constrain the same columns. // same column uc2 = new UniqueConstraint(dtParent.Columns[0]); Assert.Equal(true, uc1.Equals(uc2)); } [Fact] public void IsPrimaryKey() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0], false); dtParent.Constraints.Add(uc); // primary key 1 Assert.Equal(false, uc.IsPrimaryKey); dtParent.Constraints.Remove(uc); uc = new UniqueConstraint(dtParent.Columns[0], true); dtParent.Constraints.Add(uc); // primary key 2 Assert.Equal(true, uc.IsPrimaryKey); } [Fact] public void Table() { var ds = new DataSet(); DataTable dtParent = DataProvider.CreateParentDataTable(); ds.Tables.Add(dtParent); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); // Table Assert.Equal(dtParent, uc.Table); } [Fact] public new void ToString() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0], false); // ToString - default Assert.Equal(string.Empty, uc.ToString()); uc = new UniqueConstraint("myConstraint", dtParent.Columns[0], false); // Tostring - Constraint name Assert.Equal("myConstraint", uc.ToString()); } [Fact] public void constraintName() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); // default Assert.Equal(string.Empty, uc.ConstraintName); uc.ConstraintName = "myConstraint"; // set/get Assert.Equal("myConstraint", uc.ConstraintName); } [Fact] public void ctor_DataColumn() { Exception tmpEx = new Exception(); var ds = new DataSet(); DataTable dtParent = DataProvider.CreateParentDataTable(); ds.Tables.Add(dtParent); ds.EnforceConstraints = true; UniqueConstraint uc = null; // DataColumn.Unique - without constraint Assert.Equal(false, dtParent.Columns[0].Unique); uc = new UniqueConstraint(dtParent.Columns[0]); // Ctor Assert.Equal(false, uc == null); // DataColumn.Unique - with constraint Assert.Equal(false, dtParent.Columns[0].Unique); // Ctor - add existing column dtParent.Rows.Add(new object[] { 99, "str1", "str2" }); dtParent.Constraints.Add(uc); Assert.Throws<ConstraintException>(() => dtParent.Rows.Add(new object[] { 99, "str1", "str2" })); DataTable dtChild = DataProvider.CreateChildDataTable(); uc = new UniqueConstraint(dtChild.Columns[1]); //Column[1] is not unique, will throw exception // ArgumentException AssertExtensions.Throws<ArgumentException>(null, () => dtChild.Constraints.Add(uc)); //reset the table dtParent = DataProvider.CreateParentDataTable(); // DataColumn.Unique = true, will add UniqueConstraint dtParent.Columns[0].Unique = true; Assert.Equal(1, dtParent.Constraints.Count); // Check the created UniqueConstraint dtParent.Columns[0].Unique = true; Assert.Equal(typeof(UniqueConstraint).FullName, dtParent.Constraints[0].GetType().FullName); // add UniqueConstarint that don't belong to the table AssertExtensions.Throws<ArgumentException>(null, () => { dtParent.Constraints.Add(uc); }); } [Fact] public void ctor_DataColumnNoPrimary() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0], false); dtParent.Constraints.Add(uc); // Ctor Assert.Equal(false, uc == null); // primary key 1 Assert.Equal(0, dtParent.PrimaryKey.Length); dtParent.Constraints.Remove(uc); uc = new UniqueConstraint(dtParent.Columns[0], true); dtParent.Constraints.Add(uc); // primary key 2 Assert.Equal(1, dtParent.PrimaryKey.Length); } [Fact] public void ctor_DataColumns() { Exception tmpEx = new Exception(); DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(new DataColumn[] { dtParent.Columns[0], dtParent.Columns[1] }); // Ctor - parent Assert.Equal(false, uc == null); // Ctor - add existing column dtParent.Rows.Add(new object[] { 99, "str1", "str2" }); dtParent.Constraints.Add(uc); Assert.Throws<ConstraintException>(() => dtParent.Rows.Add(new object[] { 99, "str1", "str2" })); DataTable dtChild = DataProvider.CreateChildDataTable(); uc = new UniqueConstraint(new DataColumn[] { dtChild.Columns[0], dtChild.Columns[1] }); dtChild.Constraints.Add(uc); // Ctor - child Assert.Equal(false, uc == null); dtChild.Constraints.Clear(); uc = new UniqueConstraint(new DataColumn[] { dtChild.Columns[1], dtChild.Columns[2] }); //target columnn are not unnique, will throw an exception // ArgumentException - child AssertExtensions.Throws<ArgumentException>(null, () => dtChild.Constraints.Add(uc)); } [Fact] public void ctor_DataColumnPrimary() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0], false); dtParent.Constraints.Add(uc); // Ctor Assert.Equal(false, uc == null); // primary key 1 Assert.Equal(0, dtParent.PrimaryKey.Length); dtParent.Constraints.Remove(uc); uc = new UniqueConstraint(dtParent.Columns[0], true); dtParent.Constraints.Add(uc); // primary key 2 Assert.Equal(1, dtParent.PrimaryKey.Length); } [Fact] public void ctor_NameDataColumn() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint("myConstraint", dtParent.Columns[0]); // Ctor Assert.Equal(false, uc == null); // Ctor name Assert.Equal("myConstraint", uc.ConstraintName); } [Fact] public void ctor_NameDataColumnPrimary() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint("myConstraint", dtParent.Columns[0], false); dtParent.Constraints.Add(uc); // Ctor Assert.Equal(false, uc == null); // primary key 1 Assert.Equal(0, dtParent.PrimaryKey.Length); // Ctor name 1 Assert.Equal("myConstraint", uc.ConstraintName); dtParent.Constraints.Remove(uc); uc = new UniqueConstraint("myConstraint", dtParent.Columns[0], true); dtParent.Constraints.Add(uc); // primary key 2 Assert.Equal(1, dtParent.PrimaryKey.Length); // Ctor name 2 Assert.Equal("myConstraint", uc.ConstraintName); } [Fact] public void ctor_NameDataColumns() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint("myConstraint", new DataColumn[] { dtParent.Columns[0], dtParent.Columns[1] }); // Ctor Assert.Equal(false, uc == null); // Ctor name Assert.Equal("myConstraint", uc.ConstraintName); } [Fact] public void ctor_NameDataColumnsPrimary() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint("myConstraint", new DataColumn[] { dtParent.Columns[0] }, false); dtParent.Constraints.Add(uc); // Ctor Assert.Equal(false, uc == null); // primary key 1 Assert.Equal(0, dtParent.PrimaryKey.Length); // Ctor name 1 Assert.Equal("myConstraint", uc.ConstraintName); dtParent.Constraints.Remove(uc); uc = new UniqueConstraint("myConstraint", new DataColumn[] { dtParent.Columns[0] }, true); dtParent.Constraints.Add(uc); // primary key 2 Assert.Equal(1, dtParent.PrimaryKey.Length); // Ctor name 2 Assert.Equal("myConstraint", uc.ConstraintName); } [Fact] public void extendedProperties() { DataTable dtParent = DataProvider.CreateParentDataTable(); UniqueConstraint uc = null; uc = new UniqueConstraint(dtParent.Columns[0]); PropertyCollection pc = uc.ExtendedProperties; // Checking ExtendedProperties default Assert.Equal(true, pc != null); // Checking ExtendedProperties count Assert.Equal(0, pc.Count); } } }
using System; using System.Collections.Generic; using System.Reflection; using Stratus.Utilities; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace Stratus { /// <summary> /// Displays all present derived Stratus events in the assembly /// </summary> public class StratusEventBrowserWindow : StratusEditorWindow<StratusEventBrowserWindow> { //------------------------------------------------------------------------/ // Tree View //------------------------------------------------------------------------/ /// <summary> /// Basic information about an event /// </summary> public class EventInformation : IStratusLabeled { public string @namespace; public string @class; public string name; public string members; private const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; string IStratusLabeled.label => this.name; public EventInformation(System.Type type) { this.name = type.Name; this.@class = type.DeclaringType != null ? type.DeclaringType.Name : string.Empty; this.@namespace = type.Namespace; List<string> members = new List<string>(); members.AddRange(type.GetFields(bindingFlags).ToStringArray((FieldInfo member) => $"({member.FieldType.Name}) {member.Name}")); members.AddRange(type.GetProperties(bindingFlags).ToStringArray((PropertyInfo member) => $"({member.PropertyType.Name}) {member.Name}")); this.members = string.Join(", ", members); } } public class EventTreeElement : TreeElement<EventInformation> { } public enum Columns { Namespace, Class, Name, Members, } public class EventTreeView : MultiColumnTreeView<EventTreeElement, Columns> { public EventTreeView(TreeViewState state, IList<EventTreeElement> data) : base(state, data) { } protected override TreeViewColumn BuildColumn(Columns columnType) { TreeViewColumn column = null; switch (columnType) { case Columns.Name: column = new TreeViewColumn { headerContent = new GUIContent("Name"), sortedAscending = true, width = 150, autoResize = true, selectorFunction = (TreeViewItem<EventTreeElement> element) => element.item.data.name }; break; case Columns.Class: column = new TreeViewColumn { headerContent = new GUIContent("Class"), sortedAscending = true, width = 150, autoResize = true, selectorFunction = (TreeViewItem<EventTreeElement> element) => element.item.data.members }; break; case Columns.Members: column = new TreeViewColumn { headerContent = new GUIContent("Members"), sortedAscending = true, width = 450, autoResize = true, selectorFunction = (TreeViewItem<EventTreeElement> element) => element.item.data.members }; break; case Columns.Namespace: column = new TreeViewColumn { headerContent = new GUIContent("Namespace"), width = 175, autoResize = true, sortedAscending = true, selectorFunction = (TreeViewItem<EventTreeElement> element) => element.item.data.@namespace }; break; } return column; } protected override void DrawColumn(Rect cellRect, TreeViewItem<EventTreeElement> item, Columns column, ref RowGUIArgs args) { switch (column) { case Columns.Name: DefaultGUI.Label(cellRect, item.item.data.name, args.selected, args.focused); break; case Columns.Class: DefaultGUI.Label(cellRect, item.item.data.@class, args.selected, args.focused); break; case Columns.Members: DefaultGUI.Label(cellRect, item.item.data.members, args.selected, args.focused); break; case Columns.Namespace: DefaultGUI.Label(cellRect, item.item.data.@namespace, args.selected, args.focused); break; } } protected override Columns GetColumn(int index) { return (Columns)index; } protected override int GetColumnIndex(Columns columnType) { return (int)columnType; } protected override void OnContextMenu(GenericMenu menu) { } protected override void OnItemContextMenu(GenericMenu menu, EventTreeElement treeElement) { menu.AddItem(new GUIContent("Open file"), false, () => { }); } } //------------------------------------------------------------------------/ // Fields //------------------------------------------------------------------------/ [SerializeField] private TreeViewState treeViewState = new TreeViewState(); [SerializeField] private EventTreeView treeView; [SerializeField] private StratusSerializedTree<EventTreeElement, EventInformation> tree; private Vector2 scrollPosition; private Type[] events; //------------------------------------------------------------------------/ // Messages //------------------------------------------------------------------------/ protected override void OnWindowEnable() { this.treeView = new EventTreeView(this.treeViewState, this.BuildEventTree()); } protected override void OnWindowGUI() { this.treeView.TreeViewGUI(this.guiPosition); } [MenuItem("Stratus/Core/Event Browser")] private static void Open() { OnOpen("Event Browser"); } //------------------------------------------------------------------------/ // Data //------------------------------------------------------------------------/ private List<EventTreeElement> BuildEventTree() { this.events = StratusReflection.GetSubclass<Stratus.StratusEvent>(); EventInformation[] eventsInformation = new EventInformation[this.events.Length]; for (int i = 0; i < this.events.Length; ++i) { eventsInformation[i] = new EventInformation(this.events[i]); } //var treeBuilder = new TreeBuilder<EventTreeElement, EventInformation>(); //treeBuilder.AddChildren(eventsInformation, 0); //return treeBuilder.ToTree(); tree = new StratusSerializedTree<EventTreeElement, EventInformation>(eventsInformation); return tree.elements; } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Lucene.Net.Documents; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Search { /* * 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 DateTools = DateTools; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; /// <summary> /// Unit test for sorting code. </summary> [TestFixture] public class TestCustomSearcherSort : LuceneTestCase { private Directory Index = null; private IndexReader Reader; private Query Query = null; // reduced from 20000 to 2000 to speed up test... private int INDEX_SIZE; /// <summary> /// Create index and query for test cases. /// </summary> [SetUp] public override void SetUp() { base.SetUp(); INDEX_SIZE = AtLeast(2000); Index = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Index, Similarity, TimeZone); RandomGen random = new RandomGen(this, Random()); for (int i = 0; i < INDEX_SIZE; ++i) // don't decrease; if to low the { // problem doesn't show up Document doc = new Document(); if ((i % 5) != 0) // some documents must not have an entry in the first { // sort field doc.Add(NewStringField("publicationDate_", random.LuceneDate, Field.Store.YES)); } if ((i % 7) == 0) // some documents to match the query (see below) { doc.Add(NewTextField("content", "test", Field.Store.YES)); } // every document has a defined 'mandant' field doc.Add(NewStringField("mandant", Convert.ToString(i % 3), Field.Store.YES)); writer.AddDocument(doc); } Reader = writer.Reader; writer.Dispose(); Query = new TermQuery(new Term("content", "test")); } [TearDown] public override void TearDown() { Reader.Dispose(); Index.Dispose(); base.TearDown(); } /// <summary> /// Run the test using two CustomSearcher instances. /// </summary> [Test] public virtual void TestFieldSortCustomSearcher() { // log("Run testFieldSortCustomSearcher"); // define the sort criteria Sort custSort = new Sort(new SortField("publicationDate_", SortFieldType.STRING), SortField.FIELD_SCORE); IndexSearcher searcher = new CustomSearcher(this, Reader, 2); // search and check hits MatchHits(searcher, custSort); } /// <summary> /// Run the test using one CustomSearcher wrapped by a MultiSearcher. /// </summary> [Test] public virtual void TestFieldSortSingleSearcher() { // log("Run testFieldSortSingleSearcher"); // define the sort criteria Sort custSort = new Sort(new SortField("publicationDate_", SortFieldType.STRING), SortField.FIELD_SCORE); IndexSearcher searcher = new CustomSearcher(this, Reader, 2); // search and check hits MatchHits(searcher, custSort); } // make sure the documents returned by the search match the expected list private void MatchHits(IndexSearcher searcher, Sort sort) { // make a query without sorting first ScoreDoc[] hitsByRank = searcher.Search(Query, null, int.MaxValue).ScoreDocs; CheckHits(hitsByRank, "Sort by rank: "); // check for duplicates IDictionary<int?, int?> resultMap = new SortedDictionary<int?, int?>(); // store hits in TreeMap - TreeMap does not allow duplicates; existing // entries are silently overwritten for (int hitid = 0; hitid < hitsByRank.Length; ++hitid) { resultMap[Convert.ToInt32(hitsByRank[hitid].Doc)] = Convert.ToInt32(hitid); // Value: Hits-Objekt Index - Key: Lucene // Document ID } // now make a query using the sort criteria ScoreDoc[] resultSort = searcher.Search(Query, null, int.MaxValue, sort).ScoreDocs; CheckHits(resultSort, "Sort by custom criteria: "); // check for duplicates // besides the sorting both sets of hits must be identical for (int hitid = 0; hitid < resultSort.Length; ++hitid) { int? idHitDate = Convert.ToInt32(resultSort[hitid].Doc); // document ID // from sorted // search if (!resultMap.ContainsKey(idHitDate)) { Log("ID " + idHitDate + " not found. Possibliy a duplicate."); } Assert.IsTrue(resultMap.ContainsKey(idHitDate)); // same ID must be in the // Map from the rank-sorted // search // every hit must appear once in both result sets --> remove it from the // Map. // At the end the Map must be empty! resultMap.Remove(idHitDate); } if (resultMap.Count == 0) { // log("All hits matched"); } else { Log("Couldn't match " + resultMap.Count + " hits."); } Assert.AreEqual(resultMap.Count, 0); } /// <summary> /// Check the hits for duplicates. /// </summary> private void CheckHits(ScoreDoc[] hits, string prefix) { if (hits != null) { IDictionary<int?, int?> idMap = new SortedDictionary<int?, int?>(); for (int docnum = 0; docnum < hits.Length; ++docnum) { int? luceneId = null; luceneId = Convert.ToInt32(hits[docnum].Doc); if (idMap.ContainsKey(luceneId)) { StringBuilder message = new StringBuilder(prefix); message.Append("Duplicate key for hit index = "); message.Append(docnum); message.Append(", previous index = "); message.Append((idMap[luceneId]).ToString()); message.Append(", Lucene ID = "); message.Append(luceneId); Log(message.ToString()); } else { idMap[luceneId] = Convert.ToInt32(docnum); } } } } // Simply write to console - choosen to be independant of log4j etc private void Log(string message) { if (VERBOSE) { Console.WriteLine(message); } } public class CustomSearcher : IndexSearcher { private readonly TestCustomSearcherSort OuterInstance; internal int Switcher; public CustomSearcher(TestCustomSearcherSort outerInstance, IndexReader r, int switcher) : base(r) { this.OuterInstance = outerInstance; this.Switcher = switcher; } public override TopFieldDocs Search(Query query, Filter filter, int nDocs, Sort sort) { BooleanQuery bq = new BooleanQuery(); bq.Add(query, Occur.MUST); bq.Add(new TermQuery(new Term("mandant", Convert.ToString(Switcher))), Occur.MUST); return base.Search(bq, filter, nDocs, sort); } public override TopDocs Search(Query query, Filter filter, int nDocs) { BooleanQuery bq = new BooleanQuery(); bq.Add(query, Occur.MUST); bq.Add(new TermQuery(new Term("mandant", Convert.ToString(Switcher))), Occur.MUST); return base.Search(bq, filter, nDocs); } } private class RandomGen { private readonly TestCustomSearcherSort OuterInstance; internal RandomGen(TestCustomSearcherSort outerInstance, Random random) { this.OuterInstance = outerInstance; this.Random = random; @base = new DateTime(1980, 1, 1); } internal Random Random; // we use the default Locale/TZ since LuceneTestCase randomizes it internal DateTime @base; // Just to generate some different Lucene Date strings internal virtual string LuceneDate { get { return DateTools.TimeToString((DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + Random.Next() - int.MinValue, DateTools.Resolution.DAY); } } } } }
/* MIT License Copyright (c) 2016 JetBrains https://www.jetbrains.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; #pragma warning disable 1591 // ReSharper disable UnusedMember.Global // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable IntroduceOptionalParameters.Global // ReSharper disable MemberCanBeProtected.Global // ReSharper disable InconsistentNaming namespace JetBrains.Annotations { /// <summary> /// Indicates that the value of the marked element could be <c>null</c> sometimes, /// so the check for <c>null</c> is necessary before its usage. /// </summary> /// <example><code> /// [CanBeNull] object Test() => null; /// /// void UseTest() { /// var p = Test(); /// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] internal sealed class CanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the value of the marked element could never be <c>null</c>. /// </summary> /// <example><code> /// [NotNull] object Foo() { /// return null; // Warning: Possible 'null' assignment /// } /// </code></example> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] internal sealed class NotNullAttribute : Attribute { } /// <summary> /// Can be applied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can never be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] internal sealed class ItemNotNullAttribute : Attribute { } /// <summary> /// Can be appplied to symbols of types derived from IEnumerable as well as to symbols of Task /// and Lazy classes to indicate that the value of a collection item, of the Task.Result property /// or of the Lazy.Value property can be null. /// </summary> [AttributeUsage( AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field)] internal sealed class ItemCanBeNullAttribute : Attribute { } /// <summary> /// Indicates that the marked method builds string by format pattern and (optional) arguments. /// Parameter, which contains format string, should be given in constructor. The format string /// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form. /// </summary> /// <example><code> /// [StringFormatMethod("message")] /// void ShowError(string message, params object[] args) { /* do something */ } /// /// void Foo() { /// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string /// } /// </code></example> [AttributeUsage( AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Delegate)] internal sealed class StringFormatMethodAttribute : Attribute { /// <param name="formatParameterName"> /// Specifies which parameter of an annotated method should be treated as format-string /// </param> public StringFormatMethodAttribute([NotNull] string formatParameterName) { FormatParameterName = formatParameterName; } [NotNull] public string FormatParameterName { get; private set; } } /// <summary> /// For a parameter that is expected to be one of the limited set of values. /// Specify fields of which type should be used as values for this parameter. /// </summary> [AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] internal sealed class ValueProviderAttribute : Attribute { public ValueProviderAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Indicates that the function argument should be string literal and match one /// of the parameters of the caller function. For example, ReSharper annotates /// the parameter of <see cref="System.ArgumentNullException"/>. /// </summary> /// <example><code> /// void Foo(string param) { /// if (param == null) /// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class InvokerParameterNameAttribute : Attribute { } /// <summary> /// Indicates that the method is contained in a type that implements /// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method /// is used to notify that some property value changed. /// </summary> /// <remarks> /// The method should be non-static and conform to one of the supported signatures: /// <list> /// <item><c>NotifyChanged(string)</c></item> /// <item><c>NotifyChanged(params string[])</c></item> /// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item> /// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item> /// <item><c>SetProperty{T}(ref T, T, string)</c></item> /// </list> /// </remarks> /// <example><code> /// public class Foo : INotifyPropertyChanged { /// public event PropertyChangedEventHandler PropertyChanged; /// /// [NotifyPropertyChangedInvocator] /// protected virtual void NotifyChanged(string propertyName) { ... } /// /// string _name; /// /// public string Name { /// get { return _name; } /// set { _name = value; NotifyChanged("LastName"); /* Warning */ } /// } /// } /// </code> /// Examples of generated notifications: /// <list> /// <item><c>NotifyChanged("Property")</c></item> /// <item><c>NotifyChanged(() =&gt; Property)</c></item> /// <item><c>NotifyChanged((VM x) =&gt; x.Property)</c></item> /// <item><c>SetProperty(ref myField, value, "Property")</c></item> /// </list> /// </example> [AttributeUsage(AttributeTargets.Method)] internal sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) { ParameterName = parameterName; } [CanBeNull] public string ParameterName { get; private set; } } /// <summary> /// Describes dependency between method input and output. /// </summary> /// <syntax> /// <p>Function Definition Table syntax:</p> /// <list> /// <item>FDT ::= FDTRow [;FDTRow]*</item> /// <item>FDTRow ::= Input =&gt; Output | Output &lt;= Input</item> /// <item>Input ::= ParameterName: Value [, Input]*</item> /// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item> /// <item>Value ::= true | false | null | notnull | canbenull</item> /// </list> /// If method has single input parameter, it's name could be omitted.<br/> /// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output /// means that the methos doesn't return normally (throws or terminates the process).<br/> /// Value <c>canbenull</c> is only applicable for output parameters.<br/> /// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute /// with rows separated by semicolon. There is no notion of order rows, all rows are checked /// for applicability and applied per each program state tracked by R# analysis.<br/> /// </syntax> /// <examples><list> /// <item><code> /// [ContractAnnotation("=&gt; halt")] /// public void TerminationMethod() /// </code></item> /// <item><code> /// [ContractAnnotation("halt &lt;= condition: false")] /// public void Assert(bool condition, string text) // regular assertion method /// </code></item> /// <item><code> /// [ContractAnnotation("s:null =&gt; true")] /// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty() /// </code></item> /// <item><code> /// // A method that returns null if the parameter is null, /// // and not null if the parameter is not null /// [ContractAnnotation("null =&gt; null; notnull =&gt; notnull")] /// public object Transform(object data) /// </code></item> /// <item><code> /// [ContractAnnotation("=&gt; true, result: notnull; =&gt; false, result: null")] /// public bool TryParse(string s, out Person result) /// </code></item> /// </list></examples> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] internal sealed class ContractAnnotationAttribute : Attribute { public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } [NotNull] public string Contract { get; private set; } public bool ForceFullStates { get; private set; } } /// <summary> /// Indicates that marked element should be localized or not. /// </summary> /// <example><code> /// [LocalizationRequiredAttribute(true)] /// class Foo { /// string str = "my string"; // Warning: Localizable string /// } /// </code></example> [AttributeUsage(AttributeTargets.All)] internal sealed class LocalizationRequiredAttribute : Attribute { public LocalizationRequiredAttribute() : this(true) { } public LocalizationRequiredAttribute(bool required) { Required = required; } public bool Required { get; private set; } } /// <summary> /// Indicates that the value of the marked type (or its derivatives) /// cannot be compared using '==' or '!=' operators and <c>Equals()</c> /// should be used instead. However, using '==' or '!=' for comparison /// with <c>null</c> is always permitted. /// </summary> /// <example><code> /// [CannotApplyEqualityOperator] /// class NoEquality { } /// /// class UsesNoEquality { /// void Test() { /// var ca1 = new NoEquality(); /// var ca2 = new NoEquality(); /// if (ca1 != null) { // OK /// bool condition = ca1 == ca2; // Warning /// } /// } /// } /// </code></example> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)] internal sealed class CannotApplyEqualityOperatorAttribute : Attribute { } /// <summary> /// When applied to a target attribute, specifies a requirement for any type marked /// with the target attribute to implement or inherit specific type or types. /// </summary> /// <example><code> /// [BaseTypeRequired(typeof(IComponent)] // Specify requirement /// class ComponentAttribute : Attribute { } /// /// [Component] // ComponentAttribute requires implementing IComponent interface /// class MyComponent : IComponent { } /// </code></example> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [BaseTypeRequired(typeof(Attribute))] internal sealed class BaseTypeRequiredAttribute : Attribute { public BaseTypeRequiredAttribute([NotNull] Type baseType) { BaseType = baseType; } [NotNull] public Type BaseType { get; private set; } } /// <summary> /// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library), /// so this symbol will not be marked as unused (as well as by other usage inspections). /// </summary> [AttributeUsage(AttributeTargets.All)] internal sealed class UsedImplicitlyAttribute : Attribute { public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } public ImplicitUseKindFlags UseKindFlags { get; private set; } public ImplicitUseTargetFlags TargetFlags { get; private set; } } /// <summary> /// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes /// as unused (as well as by other usage inspections) /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)] internal sealed class MeansImplicitUseAttribute : Attribute { public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; } } [Flags] internal enum ImplicitUseKindFlags { Default = Access | Assign | InstantiatedWithFixedConstructorSignature, /// <summary>Only entity marked with attribute considered used.</summary> Access = 1, /// <summary>Indicates implicit assignment to a member.</summary> Assign = 2, /// <summary> /// Indicates implicit instantiation of a type with fixed constructor signature. /// That means any unused constructor parameters won't be reported as such. /// </summary> InstantiatedWithFixedConstructorSignature = 4, /// <summary>Indicates implicit instantiation of a type.</summary> InstantiatedNoFixedConstructorSignature = 8, } /// <summary> /// Specify what is considered used implicitly when marked /// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>. /// </summary> [Flags] internal enum ImplicitUseTargetFlags { Default = Itself, Itself = 1, /// <summary>Members of entity marked with attribute are considered used.</summary> Members = 2, /// <summary>Entity marked with attribute and all its members considered used.</summary> WithMembers = Itself | Members } /// <summary> /// This attribute is intended to mark publicly available API /// which should not be removed and so is treated as used. /// </summary> [MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)] internal sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } [CanBeNull] public string Comment { get; private set; } } /// <summary> /// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack. /// If the parameter is a delegate, indicates that delegate is executed while the method is executed. /// If the parameter is an enumerable, indicates that it is enumerated while the method is executed. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class InstantHandleAttribute : Attribute { } /// <summary> /// Indicates that a method does not make any observable state changes. /// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>. /// </summary> /// <example><code> /// [Pure] int Multiply(int x, int y) => x * y; /// /// void M() { /// Multiply(123, 42); // Waring: Return value of pure method is not used /// } /// </code></example> [AttributeUsage(AttributeTargets.Method)] internal sealed class PureAttribute : Attribute { } /// <summary> /// Indicates that the return value of method invocation must be used. /// </summary> [AttributeUsage(AttributeTargets.Method)] internal sealed class MustUseReturnValueAttribute : Attribute { public MustUseReturnValueAttribute() { } public MustUseReturnValueAttribute([NotNull] string justification) { Justification = justification; } [CanBeNull] public string Justification { get; private set; } } /// <summary> /// Indicates the type member or parameter of some type, that should be used instead of all other ways /// to get the value that type. This annotation is useful when you have some "context" value evaluated /// and stored somewhere, meaning that all other ways to get this value must be consolidated with existing one. /// </summary> /// <example><code> /// class Foo { /// [ProvidesContext] IBarService _barService = ...; /// /// void ProcessNode(INode node) { /// DoSomething(node, node.GetGlobalServices().Bar); /// // ^ Warning: use value of '_barService' field /// } /// } /// </code></example> [AttributeUsage( AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)] internal sealed class ProvidesContextAttribute : Attribute { } /// <summary> /// Indicates that a parameter is a path to a file or a folder within a web project. /// Path can be relative or absolute, starting from web root (~). /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class PathReferenceAttribute : Attribute { public PathReferenceAttribute() { } public PathReferenceAttribute([NotNull, PathReference] string basePath) { BasePath = basePath; } [CanBeNull] public string BasePath { get; private set; } } /// <summary> /// An extension method marked with this attribute is processed by ReSharper code completion /// as a 'Source Template'. When extension method is completed over some expression, it's source code /// is automatically expanded like a template at call site. /// </summary> /// <remarks> /// Template method body can contain valid source code and/or special comments starting with '$'. /// Text inside these comments is added as source code when the template is applied. Template parameters /// can be used either as additional method parameters or as identifiers wrapped in two '$' signs. /// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters. /// </remarks> /// <example> /// In this example, the 'forEach' method is a source template available over all values /// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block: /// <code> /// [SourceTemplate] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; xs) { /// foreach (var x in xs) { /// //$ $END$ /// } /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] internal sealed class SourceTemplateAttribute : Attribute { } /// <summary> /// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>. /// </summary> /// <remarks> /// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression /// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target /// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently /// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1. /// </remarks> /// <example> /// Applying the attribute on a source template method: /// <code> /// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")] /// public static void forEach&lt;T&gt;(this IEnumerable&lt;T&gt; collection) { /// foreach (var item in collection) { /// //$ $END$ /// } /// } /// </code> /// Applying the attribute on a template method parameter: /// <code> /// [SourceTemplate] /// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) { /// /*$ var $x$Id = "$newguid$" + x.ToString(); /// x.DoSomething($x$Id); */ /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)] internal sealed class MacroAttribute : Attribute { /// <summary> /// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see> /// parameter when the template is expanded. /// </summary> [CanBeNull] public string Expression { get; set; } /// <summary> /// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed. /// </summary> /// <remarks> /// If the target parameter is used several times in the template, only one occurrence becomes editable; /// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence, /// use values >= 0. To make the parameter non-editable when the template is expanded, use -1. /// </remarks>> public int Editable { get; set; } /// <summary> /// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the /// <see cref="MacroAttribute"/> is applied on a template method. /// </summary> [CanBeNull] public string Target { get; set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] internal sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute { public AspMvcAreaMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] internal sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute { public AspMvcAreaPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] internal sealed class AspMvcAreaViewLocationFormatAttribute : Attribute { public AspMvcAreaViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] internal sealed class AspMvcMasterLocationFormatAttribute : Attribute { public AspMvcMasterLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] internal sealed class AspMvcPartialViewLocationFormatAttribute : Attribute { public AspMvcPartialViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] internal sealed class AspMvcViewLocationFormatAttribute : Attribute { public AspMvcViewLocationFormatAttribute([NotNull] string format) { Format = format; } [NotNull] public string Format { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC action. If applied to a method, the MVC action name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcActionAttribute : Attribute { public AspMvcActionAttribute() { } public AspMvcActionAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC area. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcAreaAttribute : Attribute { public AspMvcAreaAttribute() { } public AspMvcAreaAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is /// an MVC controller. If applied to a method, the MVC controller name is calculated /// implicitly from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcControllerAttribute : Attribute { public AspMvcControllerAttribute() { } public AspMvcControllerAttribute([NotNull] string anonymousProperty) { AnonymousProperty = anonymousProperty; } [CanBeNull] public string AnonymousProperty { get; private set; } } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcMasterAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute /// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcModelTypeAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC /// partial view. If applied to a method, the MVC partial view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcPartialViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] internal sealed class AspMvcSuppressViewErrorAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcDisplayTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template. /// Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcEditorTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. Indicates that a parameter is an MVC template. /// Use this attribute for custom wrappers similar to /// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcTemplateAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component. If applied to a method, the MVC view name is calculated implicitly /// from the context. Use this attribute for custom wrappers similar to /// <c>System.Web.Mvc.Controller.View(Object)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component name. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AspMvcViewComponentAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component view. If applied to a method, the MVC view component view name is default. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class AspMvcViewComponentViewAttribute : Attribute { } /// <summary> /// ASP.NET MVC attribute. When applied to a parameter of an attribute, /// indicates that this parameter is an MVC action name. /// </summary> /// <example><code> /// [ActionName("Foo")] /// public ActionResult Login(string returnUrl) { /// ViewBag.ReturnUrl = Url.Action("Foo"); // OK /// return RedirectToAction("Bar"); // Error: Cannot resolve action /// } /// </code></example> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] internal sealed class AspMvcActionSelectorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)] internal sealed class HtmlElementAttributesAttribute : Attribute { public HtmlElementAttributesAttribute() { } public HtmlElementAttributesAttribute([NotNull] string name) { Name = name; } [CanBeNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] internal sealed class HtmlAttributeValueAttribute : Attribute { public HtmlAttributeValueAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } /// <summary> /// Razor attribute. Indicates that a parameter or a method is a Razor section. /// Use this attribute for custom wrappers similar to /// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>. /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class RazorSectionAttribute : Attribute { } /// <summary> /// Indicates how method, constructor invocation or property access /// over collection type affects content of the collection. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] internal sealed class CollectionAccessAttribute : Attribute { public CollectionAccessAttribute(CollectionAccessType collectionAccessType) { CollectionAccessType = collectionAccessType; } public CollectionAccessType CollectionAccessType { get; private set; } } [Flags] internal enum CollectionAccessType { /// <summary>Method does not use or modify content of the collection.</summary> None = 0, /// <summary>Method only reads content of the collection but does not modify it.</summary> Read = 1, /// <summary>Method can change content of the collection but does not add new elements.</summary> ModifyExistingContent = 2, /// <summary>Method can add new elements to the collection.</summary> UpdatedContent = ModifyExistingContent | 4 } /// <summary> /// Indicates that the marked method is assertion method, i.e. it halts control flow if /// one of the conditions is satisfied. To set the condition, mark one of the parameters with /// <see cref="AssertionConditionAttribute"/> attribute. /// </summary> [AttributeUsage(AttributeTargets.Method)] internal sealed class AssertionMethodAttribute : Attribute { } /// <summary> /// Indicates the condition parameter of the assertion method. The method itself should be /// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of /// the attribute is the assertion type. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class AssertionConditionAttribute : Attribute { public AssertionConditionAttribute(AssertionConditionType conditionType) { ConditionType = conditionType; } public AssertionConditionType ConditionType { get; private set; } } /// <summary> /// Specifies assertion type. If the assertion method argument satisfies the condition, /// then the execution continues. Otherwise, execution is assumed to be halted. /// </summary> internal enum AssertionConditionType { /// <summary>Marked parameter should be evaluated to true.</summary> IS_TRUE = 0, /// <summary>Marked parameter should be evaluated to false.</summary> IS_FALSE = 1, /// <summary>Marked parameter should be evaluated to null value.</summary> IS_NULL = 2, /// <summary>Marked parameter should be evaluated to not null value.</summary> IS_NOT_NULL = 3, } /// <summary> /// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select, /// .Where). This annotation allows inference of [InstantHandle] annotation for parameters /// of delegate type by analyzing LINQ method chains. /// </summary> [AttributeUsage(AttributeTargets.Method)] internal sealed class LinqTunnelAttribute : Attribute { } /// <summary> /// Indicates that IEnumerable, passed as parameter, is not enumerated. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class NoEnumerationAttribute : Attribute { } /// <summary> /// Indicates that parameter is regular expression pattern. /// </summary> [AttributeUsage(AttributeTargets.Parameter)] internal sealed class RegexPatternAttribute : Attribute { } /// <summary> /// Prevents the Member Reordering feature from tossing members of the marked class. /// </summary> /// <remarks> /// The attribute must be mentioned in your member reordering patterns /// </remarks> [AttributeUsage( AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] internal sealed class NoReorderAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated /// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve. /// </summary> [AttributeUsage(AttributeTargets.Class)] internal sealed class XamlItemsControlAttribute : Attribute { } /// <summary> /// XAML attribute. Indicates the property of some <c>BindingBase</c>-derived type, that /// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will /// enable the <c>DataContext</c> type resolve for XAML bindings for such properties. /// </summary> /// <remarks> /// Property should have the tree ancestor of the <c>ItemsControl</c> type or /// marked with the <see cref="XamlItemsControlAttribute"/> attribute. /// </remarks> [AttributeUsage(AttributeTargets.Property)] internal sealed class XamlItemBindingOfItemsControlAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class AspChildControlTypeAttribute : Attribute { public AspChildControlTypeAttribute([NotNull] string tagName, [NotNull] Type controlType) { TagName = tagName; ControlType = controlType; } [NotNull] public string TagName { get; private set; } [NotNull] public Type ControlType { get; private set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] internal sealed class AspDataFieldAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] internal sealed class AspDataFieldsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] internal sealed class AspMethodPropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class AspRequiredAttributeAttribute : Attribute { public AspRequiredAttributeAttribute([NotNull] string attribute) { Attribute = attribute; } [NotNull] public string Attribute { get; private set; } } [AttributeUsage(AttributeTargets.Property)] internal sealed class AspTypePropertyAttribute : Attribute { public bool CreateConstructorReferences { get; private set; } public AspTypePropertyAttribute(bool createConstructorReferences) { CreateConstructorReferences = createConstructorReferences; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorImportNamespaceAttribute : Attribute { public RazorImportNamespaceAttribute([NotNull] string name) { Name = name; } [NotNull] public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorInjectionAttribute : Attribute { public RazorInjectionAttribute([NotNull] string type, [NotNull] string fieldName) { Type = type; FieldName = fieldName; } [NotNull] public string Type { get; private set; } [NotNull] public string FieldName { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorDirectiveAttribute : Attribute { public RazorDirectiveAttribute([NotNull] string directive) { Directive = directive; } [NotNull] public string Directive { get; private set; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class RazorPageBaseTypeAttribute : Attribute { public RazorPageBaseTypeAttribute([NotNull] string baseType) { BaseType = baseType; } public RazorPageBaseTypeAttribute([NotNull] string baseType, string pageName) { BaseType = baseType; PageName = pageName; } [NotNull] public string BaseType { get; private set; } [CanBeNull] public string PageName { get; private set; } } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorHelperCommonAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] internal sealed class RazorLayoutAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorWriteLiteralMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class RazorWriteMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class RazorWriteMethodParameterAttribute : Attribute { } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using Mono.Collections.Generic; using SR = System.Reflection; using Mono.Cecil.Metadata; namespace Mono.Cecil { #if !READ_ONLY public interface IMetadataImporterProvider { IMetadataImporter GetMetadataImporter (ModuleDefinition module); } public interface IMetadataImporter { TypeReference ImportReference (TypeReference type, IGenericParameterProvider context); FieldReference ImportReference (FieldReference field, IGenericParameterProvider context); MethodReference ImportReference (MethodReference method, IGenericParameterProvider context); } #if !CF public interface IReflectionImporterProvider { IReflectionImporter GetReflectionImporter (ModuleDefinition module); } public interface IReflectionImporter { TypeReference ImportReference (Type type, IGenericParameterProvider context); FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context); MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context); } #endif struct ImportGenericContext { Collection<IGenericParameterProvider> stack; public bool IsEmpty { get { return stack == null; } } public ImportGenericContext (IGenericParameterProvider provider) { if (provider == null) throw new ArgumentNullException ("provider"); stack = null; Push (provider); } public void Push (IGenericParameterProvider provider) { if (stack == null) stack = new Collection<IGenericParameterProvider> (1) { provider }; else stack.Add (provider); } public void Pop () { stack.RemoveAt (stack.Count - 1); } public TypeReference MethodParameter (string method, int position) { for (int i = stack.Count - 1; i >= 0; i--) { var candidate = stack [i] as MethodReference; if (candidate == null) continue; if (method != candidate.Name) continue; return candidate.GenericParameters [position]; } throw new InvalidOperationException (); } public TypeReference TypeParameter (string type, int position) { for (int i = stack.Count - 1; i >= 0; i--) { var candidate = GenericTypeFor (stack [i]); if (candidate.FullName != type) continue; return candidate.GenericParameters [position]; } throw new InvalidOperationException (); } static TypeReference GenericTypeFor (IGenericParameterProvider context) { var type = context as TypeReference; if (type != null) return type.GetElementType (); var method = context as MethodReference; if (method != null) return method.DeclaringType.GetElementType (); throw new InvalidOperationException (); } public static ImportGenericContext For (IGenericParameterProvider context) { return context != null ? new ImportGenericContext (context) : default (ImportGenericContext); } } #if !CF public class ReflectionImporter : IReflectionImporter { readonly ModuleDefinition module; public ReflectionImporter (ModuleDefinition module) { Mixin.CheckModule (module); this.module = module; } enum ImportGenericKind { Definition, Open, } static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) { { typeof (void), ElementType.Void }, { typeof (bool), ElementType.Boolean }, { typeof (char), ElementType.Char }, { typeof (sbyte), ElementType.I1 }, { typeof (byte), ElementType.U1 }, { typeof (short), ElementType.I2 }, { typeof (ushort), ElementType.U2 }, { typeof (int), ElementType.I4 }, { typeof (uint), ElementType.U4 }, { typeof (long), ElementType.I8 }, { typeof (ulong), ElementType.U8 }, { typeof (float), ElementType.R4 }, { typeof (double), ElementType.R8 }, { typeof (string), ElementType.String }, { typeof (TypedReference), ElementType.TypedByRef }, { typeof (IntPtr), ElementType.I }, { typeof (UIntPtr), ElementType.U }, { typeof (object), ElementType.Object }, }; TypeReference ImportType (Type type, ImportGenericContext context) { return ImportType (type, context, ImportGenericKind.Open); } TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind) { if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind)) return ImportTypeSpecification (type, context); var reference = new TypeReference ( string.Empty, type.Name, module, ImportScope (type.Assembly), type.IsValueType); reference.etype = ImportElementType (type); if (IsNestedType (type)) reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind); else reference.Namespace = type.Namespace ?? string.Empty; if (type.IsGenericType) ImportGenericParameters (reference, type.GetGenericArguments ()); return reference; } static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind) { return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open; } static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind) { return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open; } static bool IsNestedType (Type type) { #if !SILVERLIGHT return type.IsNested; #else return type.DeclaringType != null; #endif } TypeReference ImportTypeSpecification (Type type, ImportGenericContext context) { if (type.IsByRef) return new ByReferenceType (ImportType (type.GetElementType (), context)); if (type.IsPointer) return new PointerType (ImportType (type.GetElementType (), context)); if (type.IsArray) return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ()); if (type.IsGenericType) return ImportGenericInstance (type, context); if (type.IsGenericParameter) return ImportGenericParameter (type, context); throw new NotSupportedException (type.FullName); } static TypeReference ImportGenericParameter (Type type, ImportGenericContext context) { if (context.IsEmpty) throw new InvalidOperationException (); if (type.DeclaringMethod != null) return context.MethodParameter (type.DeclaringMethod.Name, type.GenericParameterPosition); if (type.DeclaringType != null) return context.TypeParameter (NormalizedFullName (type.DeclaringType), type.GenericParameterPosition); throw new InvalidOperationException(); } private static string NormalizedFullName (Type type) { if (IsNestedType (type)) return NormalizedFullName (type.DeclaringType) + "/" + type.Name; return type.FullName; } TypeReference ImportGenericInstance (Type type, ImportGenericContext context) { var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceType (element_type); var arguments = type.GetGenericArguments (); var instance_arguments = instance.GenericArguments; context.Push (element_type); try { for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context)); return instance; } finally { context.Pop (); } } static bool IsTypeSpecification (Type type) { return type.HasElementType || IsGenericInstance (type) || type.IsGenericParameter; } static bool IsGenericInstance (Type type) { return type.IsGenericType && !type.IsGenericTypeDefinition; } static ElementType ImportElementType (Type type) { ElementType etype; if (!type_etype_mapping.TryGetValue (type, out etype)) return ElementType.None; return etype; } AssemblyNameReference ImportScope (SR.Assembly assembly) { AssemblyNameReference scope; #if !SILVERLIGHT var name = assembly.GetName (); if (TryGetAssemblyNameReference (name, out scope)) return scope; scope = new AssemblyNameReference (name.Name, name.Version) { Culture = name.CultureInfo.Name, PublicKeyToken = name.GetPublicKeyToken (), HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm, }; module.AssemblyReferences.Add (scope); return scope; #else var name = AssemblyNameReference.Parse (assembly.FullName); if (module.TryGetAssemblyNameReference (name, out scope)) return scope; module.AssemblyReferences.Add (name); return name; #endif } #if !SILVERLIGHT bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (name.FullName != reference.FullName) // TODO compare field by field continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } #endif FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); if (IsGenericInstance (field.DeclaringType)) field = ResolveFieldDefinition (field); context.Push (declaring_type); try { return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context), }; } finally { context.Pop (); } } static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field) { #if !SILVERLIGHT return field.Module.ResolveField (field.MetadataToken); #else return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name, SR.BindingFlags.Public | SR.BindingFlags.NonPublic | (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance)); #endif } MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind) { if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind)) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); if (IsGenericInstance (method.DeclaringType)) method = method.Module.ResolveMethod (method.MetadataToken); var reference = new MethodReference { Name = method.Name, HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis), ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis), DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition), }; if (HasCallingConvention (method, SR.CallingConventions.VarArgs)) reference.CallingConvention &= MethodCallingConvention.VarArg; if (method.IsGenericMethod) ImportGenericParameters (reference, method.GetGenericArguments ()); context.Push (reference); try { var method_info = method as SR.MethodInfo; reference.ReturnType = method_info != null ? ImportType (method_info.ReturnType, context) : ImportType (typeof (void), default (ImportGenericContext)); var parameters = method.GetParameters (); var reference_parameters = reference.Parameters; for (int i = 0; i < parameters.Length; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context))); reference.DeclaringType = declaring_type; return reference; } finally { context.Pop (); } } static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments) { var provider_parameters = provider.GenericParameters; for (int i = 0; i < arguments.Length; i++) provider_parameters.Add (new GenericParameter (arguments [i].Name, provider)); } static bool IsMethodSpecification (SR.MethodBase method) { return method.IsGenericMethod && !method.IsGenericMethodDefinition; } MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context) { var method_info = method as SR.MethodInfo; if (method_info == null) throw new InvalidOperationException (); var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceMethod (element_method); var arguments = method.GetGenericArguments (); var instance_arguments = instance.GenericArguments; context.Push (element_method); try { for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context)); return instance; } finally { context.Pop (); } } static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions) { return (method.CallingConvention & conventions) != 0; } public virtual TypeReference ImportReference (Type type, IGenericParameterProvider context) { Mixin.CheckType (type); return ImportType ( type, ImportGenericContext.For (context), context != null ? ImportGenericKind.Open : ImportGenericKind.Definition); } public virtual FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context) { Mixin.CheckField (field); return ImportField (field, ImportGenericContext.For (context)); } public virtual MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context) { Mixin.CheckMethod (method); return ImportMethod (method, ImportGenericContext.For (context), context != null ? ImportGenericKind.Open : ImportGenericKind.Definition); } } #endif public class MetadataImporter : IMetadataImporter { readonly ModuleDefinition module; public MetadataImporter (ModuleDefinition module) { Mixin.CheckModule (module); this.module = module; } TypeReference ImportType (TypeReference type, ImportGenericContext context) { if (type.IsTypeSpecification ()) return ImportTypeSpecification (type, context); var reference = new TypeReference ( type.Namespace, type.Name, module, ImportScope (type.Scope), type.IsValueType); MetadataSystem.TryProcessPrimitiveTypeReference (reference); if (type.IsNested) reference.DeclaringType = ImportType (type.DeclaringType, context); if (type.HasGenericParameters) ImportGenericParameters (reference, type); return reference; } IMetadataScope ImportScope (IMetadataScope scope) { switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: return ImportAssemblyName ((AssemblyNameReference) scope); case MetadataScopeType.ModuleDefinition: if (scope == module) return scope; return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name); case MetadataScopeType.ModuleReference: throw new NotImplementedException (); } throw new NotSupportedException (); } AssemblyNameReference ImportAssemblyName (AssemblyNameReference name) { AssemblyNameReference reference; if (module.TryGetAssemblyNameReference (name, out reference)) return reference; reference = new AssemblyNameReference (name.Name, name.Version) { Culture = name.Culture, HashAlgorithm = name.HashAlgorithm, IsRetargetable = name.IsRetargetable }; var pk_token = !name.PublicKeyToken.IsNullOrEmpty () ? new byte [name.PublicKeyToken.Length] : Empty<byte>.Array; if (pk_token.Length > 0) Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length); reference.PublicKeyToken = pk_token; module.AssemblyReferences.Add (reference); return reference; } static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original) { var parameters = original.GenericParameters; var imported_parameters = imported.GenericParameters; for (int i = 0; i < parameters.Count; i++) imported_parameters.Add (new GenericParameter (parameters [i].Name, imported)); } TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context) { switch (type.etype) { case ElementType.SzArray: var vector = (ArrayType) type; return new ArrayType (ImportType (vector.ElementType, context)); case ElementType.Ptr: var pointer = (PointerType) type; return new PointerType (ImportType (pointer.ElementType, context)); case ElementType.ByRef: var byref = (ByReferenceType) type; return new ByReferenceType (ImportType (byref.ElementType, context)); case ElementType.Pinned: var pinned = (PinnedType) type; return new PinnedType (ImportType (pinned.ElementType, context)); case ElementType.Sentinel: var sentinel = (SentinelType) type; return new SentinelType (ImportType (sentinel.ElementType, context)); case ElementType.FnPtr: var fnptr = (FunctionPointerType) type; var imported_fnptr = new FunctionPointerType () { HasThis = fnptr.HasThis, ExplicitThis = fnptr.ExplicitThis, CallingConvention = fnptr.CallingConvention, ReturnType = ImportType (fnptr.ReturnType, context), }; if (!fnptr.HasParameters) return imported_fnptr; for (int i = 0; i < fnptr.Parameters.Count; i++) imported_fnptr.Parameters.Add (new ParameterDefinition ( ImportType (fnptr.Parameters [i].ParameterType, context))); return imported_fnptr; case ElementType.CModOpt: var modopt = (OptionalModifierType) type; return new OptionalModifierType ( ImportType (modopt.ModifierType, context), ImportType (modopt.ElementType, context)); case ElementType.CModReqD: var modreq = (RequiredModifierType) type; return new RequiredModifierType ( ImportType (modreq.ModifierType, context), ImportType (modreq.ElementType, context)); case ElementType.Array: var array = (ArrayType) type; var imported_array = new ArrayType (ImportType (array.ElementType, context)); if (array.IsVector) return imported_array; var dimensions = array.Dimensions; var imported_dimensions = imported_array.Dimensions; imported_dimensions.Clear (); for (int i = 0; i < dimensions.Count; i++) { var dimension = dimensions [i]; imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound)); } return imported_array; case ElementType.GenericInst: var instance = (GenericInstanceType) type; var element_type = ImportType (instance.ElementType, context); var imported_instance = new GenericInstanceType (element_type); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; case ElementType.Var: var var_parameter = (GenericParameter) type; if (var_parameter.DeclaringType == null) throw new InvalidOperationException (); return context.TypeParameter (var_parameter.DeclaringType.FullName, var_parameter.Position); case ElementType.MVar: var mvar_parameter = (GenericParameter) type; if (mvar_parameter.DeclaringMethod == null) throw new InvalidOperationException (); return context.MethodParameter (mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position); } throw new NotSupportedException (type.etype.ToString ()); } FieldReference ImportField (FieldReference field, ImportGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); context.Push (declaring_type); try { return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context), }; } finally { context.Pop (); } } MethodReference ImportMethod (MethodReference method, ImportGenericContext context) { if (method.IsGenericInstance) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); var reference = new MethodReference { Name = method.Name, HasThis = method.HasThis, ExplicitThis = method.ExplicitThis, DeclaringType = declaring_type, CallingConvention = method.CallingConvention, }; if (method.HasGenericParameters) ImportGenericParameters (reference, method); context.Push (reference); try { reference.ReturnType = ImportType (method.ReturnType, context); if (!method.HasParameters) return reference; var parameters = method.Parameters; var reference_parameters = reference.parameters = new ParameterDefinitionCollection (reference, parameters.Count); for (int i = 0; i < parameters.Count; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context))); return reference; } finally { context.Pop(); } } MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context) { if (!method.IsGenericInstance) throw new NotSupportedException (); var instance = (GenericInstanceMethod) method; var element_method = ImportMethod (instance.ElementMethod, context); var imported_instance = new GenericInstanceMethod (element_method); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; } public virtual TypeReference ImportReference (TypeReference type, IGenericParameterProvider context) { Mixin.CheckType (type); return ImportType (type, ImportGenericContext.For (context)); } public virtual FieldReference ImportReference (FieldReference field, IGenericParameterProvider context) { Mixin.CheckField (field); return ImportField (field, ImportGenericContext.For (context)); } public virtual MethodReference ImportReference (MethodReference method, IGenericParameterProvider context) { Mixin.CheckMethod (method); return ImportMethod (method, ImportGenericContext.For (context)); } } static partial class Mixin { public static void CheckModule (ModuleDefinition module) { if (module == null) throw new ArgumentNullException ("module"); } public static bool TryGetAssemblyNameReference (this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (!Equals (name_reference, reference)) continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } private static bool Equals (byte [] a, byte [] b) { if (ReferenceEquals (a, b)) return true; if (a == null) return false; if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) if (a [i] != b [i]) return false; return true; } private static bool Equals<T> (T a, T b) where T : class, IEquatable<T> { if (ReferenceEquals (a, b)) return true; if (a == null) return false; return a.Equals (b); } private static bool Equals (AssemblyNameReference a, AssemblyNameReference b) { if (ReferenceEquals (a, b)) return true; if (a.Name != b.Name) return false; if (!Equals (a.Version, b.Version)) return false; if (a.Culture != b.Culture) return false; if (!Equals (a.PublicKeyToken, b.PublicKeyToken)) return false; return true; } } #endif }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using Xunit; namespace System.Text.EncodingTests { // Decodes a sequence of bytes from the specified byte array into the specified character array. // ASCIIEncoding.GetChars(byte[], int, int, char[], int) public class ASCIIEncodingGetChars { private const int c_MIN_STRING_LENGTH = 2; private const int c_MAX_STRING_LENGTH = 260; private const char c_MIN_ASCII_CHAR = (char)0x0; private const char c_MAX_ASCII_CHAR = (char)0x7f; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); // PosTest1: zero-length byte array. [Fact] public void PosTest1() { DoPosTest(new ASCIIEncoding(), new byte[0], 0, 0, new char[0], 0); } // PosTest2: random byte array. [Fact] public void PosTest2() { ASCIIEncoding ascii; byte[] bytes; int byteIndex, byteCount; char[] chars; int charIndex; string source; ascii = new ASCIIEncoding(); source = _generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); bytes = new byte[ascii.GetByteCount(source)]; ascii.GetBytes(source, 0, source.Length, bytes, 0); byteIndex = _generator.GetInt32(-55) % bytes.Length; byteCount = _generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1; chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH]; charIndex = _generator.GetInt32(-55) % (chars.Length - byteCount + 1); DoPosTest(ascii, bytes, byteIndex, byteCount, chars, charIndex); } private void DoPosTest(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int actualValue = ascii.GetChars(bytes, byteIndex, byteCount, chars, charIndex); Assert.True(VerifyGetCharsResult(ascii, bytes, byteIndex, byteCount, chars, charIndex, actualValue)); } private bool VerifyGetCharsResult(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int actualValue) { if (actualValue != byteCount) return false; //Assume that the character array has enough capacity to accommodate the resulting characters //i current index of byte array, j current index of character array for (int byteEnd = byteIndex + byteCount, i = byteIndex, j = charIndex; i < byteEnd; ++i, ++j) { if (bytes[i] != (byte)chars[j]) return false; } return true; } // NegTest1: count of bytes is less than zero. [Fact] public void NegTest1() { ASCIIEncoding ascii; byte[] bytes; int byteIndex, byteCount; char[] chars; int charIndex; ascii = new ASCIIEncoding(); bytes = new byte[] { 65, 83, 67, 73, 73, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108 }; byteCount = -1 * _generator.GetInt32(-55) - 1; byteIndex = _generator.GetInt32(-55) % bytes.Length; int actualByteCount = bytes.Length - byteIndex; chars = new char[actualByteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH]; charIndex = _generator.GetInt32(-55) % (chars.Length - actualByteCount + 1); DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex); } // NegTest2: The start index of bytes is less than zero. [Fact] public void NegTest2() { ASCIIEncoding ascii; byte[] bytes; int byteIndex, byteCount; char[] chars; int charIndex; ascii = new ASCIIEncoding(); bytes = new byte[] { 65, 83, 67, 73, 73, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108 }; byteCount = _generator.GetInt32(-55) % bytes.Length + 1; byteIndex = -1 * _generator.GetInt32(-55) - 1; chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH]; charIndex = _generator.GetInt32(-55) % (chars.Length - byteCount + 1); DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex); } // NegTest3: count of bytes is too large. [Fact] public void NegTest3() { ASCIIEncoding ascii; byte[] bytes; int byteIndex, byteCount; char[] chars; int charIndex; ascii = new ASCIIEncoding(); bytes = new byte[] { 65, 83, 67, 73, 73, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108 }; byteIndex = _generator.GetInt32(-55) % bytes.Length; byteCount = bytes.Length - byteIndex + 1 + _generator.GetInt32(-55) % (int.MaxValue - bytes.Length + byteIndex); int actualByteCount = bytes.Length - byteIndex; chars = new char[actualByteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH]; charIndex = _generator.GetInt32(-55) % (chars.Length - actualByteCount + 1); DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex); } // NegTest4: The start index of bytes is too large. [Fact] public void NegTest4() { ASCIIEncoding ascii; byte[] bytes; int byteIndex, byteCount; char[] chars; int charIndex; ascii = new ASCIIEncoding(); bytes = new byte[] { 65, 83, 67, 73, 73, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108 }; byteCount = _generator.GetInt32(-55) % bytes.Length + 1; byteIndex = bytes.Length - byteCount + 1 + _generator.GetInt32(-55) % (int.MaxValue - bytes.Length + byteCount); chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH]; charIndex = _generator.GetInt32(-55) % (chars.Length - byteCount + 1); DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex); } // NegTest5: bytes is a null reference [Fact] public void NegTest5() { ASCIIEncoding ascii = new ASCIIEncoding(); byte[] bytes = null; Assert.Throws<ArgumentNullException>(() => { ascii.GetChars(bytes, 0, 0, new char[0], 0); }); } // NegTest6: character array is a null reference [Fact] public void NegTest6() { ASCIIEncoding ascii = new ASCIIEncoding(); byte[] bytes = new byte[] { 65, 83, 67, 73, 73, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108 }; Assert.Throws<ArgumentNullException>(() => { ascii.GetChars(bytes, 0, 0, null, 0); }); } // NegTest7: The start index of character array is less than zero. [Fact] public void NegTest7() { ASCIIEncoding ascii; byte[] bytes; int byteIndex, byteCount; char[] chars; int charIndex; ascii = new ASCIIEncoding(); bytes = new byte[] { 65, 83, 67, 73, 73, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108 }; byteIndex = _generator.GetInt32(-55) % bytes.Length; byteCount = _generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1; chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH]; charIndex = -1 * _generator.GetInt32(-55) - 1; DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex); } // NegTest8: The start index of character array is too large. [Fact] public void NegTest8() { ASCIIEncoding ascii; byte[] bytes; int byteIndex, byteCount; char[] chars; int charIndex; ascii = new ASCIIEncoding(); bytes = new byte[] { 65, 83, 67, 73, 73, 32, 69, 110, 99, 111, 100, 105, 110, 103, 32, 69, 120, 97, 109, 112, 108 }; byteIndex = _generator.GetInt32(-55) % bytes.Length; byteCount = _generator.GetInt32(-55) % (bytes.Length - byteIndex) + 1; chars = new char[byteCount + _generator.GetInt32(-55) % c_MAX_STRING_LENGTH]; charIndex = chars.Length - byteCount + 1 + _generator.GetInt32(-55) % (int.MaxValue - chars.Length + byteCount); DoNegAOORTest(ascii, bytes, byteIndex, byteCount, chars, charIndex); } private void DoNegAOORTest(ASCIIEncoding ascii, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { Assert.Throws<ArgumentOutOfRangeException>(() => { ascii.GetChars(bytes, byteIndex, byteCount, chars, charIndex); }); } } }
using System; using System.Collections; using System.IO; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests { [TestFixture] public class PgpClearSignedSignatureTest : SimpleTest { private static readonly byte[] publicKey = Base64.Decode( "mQELBEQh2+wBCAD26kte0hO6flr7Y2aetpPYutHY4qsmDPy+GwmmqVeCDkX+" + "r1g7DuFbMhVeu0NkKDnVl7GsJ9VarYsFYyqu0NzLa9XS2qlTIkmJV+2/xKa1" + "tzjn18fT/cnAWL88ZLCOWUr241aPVhLuIc6vpHnySpEMkCh4rvMaimnTrKwO" + "42kgeDGd5cXfs4J4ovRcTbc4hmU2BRVsRjiYMZWWx0kkyL2zDVyaJSs4yVX7" + "Jm4/LSR1uC/wDT0IJJuZT/gQPCMJNMEsVCziRgYkAxQK3OWojPSuv4rXpyd4" + "Gvo6IbvyTgIskfpSkCnQtORNLIudQSuK7pW+LkL62N+ohuKdMvdxauOnAAYp" + "tBNnZ2dnZ2dnZyA8Z2dnQGdnZ2c+iQE2BBMBAgAgBQJEIdvsAhsDBgsJCAcD" + "AgQVAggDBBYCAwECHgECF4AACgkQ4M/Ier3f9xagdAf/fbKWBjLQM8xR7JkR" + "P4ri8YKOQPhK+VrddGUD59/wzVnvaGyl9MZE7TXFUeniQq5iXKnm22EQbYch" + "v2Jcxyt2H9yptpzyh4tP6tEHl1C887p2J4qe7F2ATua9CzVGwXQSUbKtj2fg" + "UZP5SsNp25guhPiZdtkf2sHMeiotmykFErzqGMrvOAUThrO63GiYsRk4hF6r" + "cQ01d+EUVpY/sBcCxgNyOiB7a84sDtrxnX5BTEZDTEj8LvuEyEV3TMUuAjx1" + "7Eyd+9JtKzwV4v3hlTaWOvGro9nPS7YaPuG+RtufzXCUJPbPfTjTvtGOqvEz" + "oztls8tuWA0OGHba9XfX9rfgorACAAM="); private static readonly byte[] secretKey = Base64.Decode( "lQOWBEQh2+wBCAD26kte0hO6flr7Y2aetpPYutHY4qsmDPy+GwmmqVeCDkX+" + "r1g7DuFbMhVeu0NkKDnVl7GsJ9VarYsFYyqu0NzLa9XS2qlTIkmJV+2/xKa1" + "tzjn18fT/cnAWL88ZLCOWUr241aPVhLuIc6vpHnySpEMkCh4rvMaimnTrKwO" + "42kgeDGd5cXfs4J4ovRcTbc4hmU2BRVsRjiYMZWWx0kkyL2zDVyaJSs4yVX7" + "Jm4/LSR1uC/wDT0IJJuZT/gQPCMJNMEsVCziRgYkAxQK3OWojPSuv4rXpyd4" + "Gvo6IbvyTgIskfpSkCnQtORNLIudQSuK7pW+LkL62N+ohuKdMvdxauOnAAYp" + "AAf+JCJJeAXEcrTVHotsrRR5idzmg6RK/1MSQUijwPmP7ZGy1BmpAmYUfbxn" + "B56GvXyFV3Pbj9PgyJZGS7cY+l0BF4ZqN9USiQtC9OEpCVT5LVMCFXC/lahC" + "/O3EkjQy0CYK+GwyIXa+Flxcr460L/Hvw2ZEXJZ6/aPdiR+DU1l5h99Zw8V1" + "Y625MpfwN6ufJfqE0HLoqIjlqCfi1iwcKAK2oVx2SwnT1W0NwUUXjagGhD2s" + "VzJVpLqhlwmS0A+RE9Niqrf80/zwE7QNDF2DtHxmMHJ3RY/pfu5u1rrFg9YE" + "lmS60mzOe31CaD8Li0k5YCJBPnmvM9mN3/DWWprSZZKtmQQA96C2/VJF5EWm" + "+/Yxi5J06dG6Bkz311Ui4p2zHm9/4GvTPCIKNpGx9Zn47YFD3tIg3fIBVPOE" + "ktG38pEPx++dSSFF9Ep5UgmYFNOKNUVq3yGpatBtCQBXb1LQLAMBJCJ5TQmk" + "68hMOEaqjMHSOa18cS63INgA6okb/ueAKIHxYQcEAP9DaXu5n9dZQw7pshbN" + "Nu/T5IP0/D/wqM+W5r+j4P1N7PgiAnfKA4JjKrUgl8PGnI2qM/Qu+g3qK++c" + "F1ESHasnJPjvNvY+cfti06xnJVtCB/EBOA2UZkAr//Tqa76xEwYAWRBnO2Y+" + "KIVOT+nMiBFkjPTrNAD6fSr1O4aOueBhBAC6aA35IfjC2h5MYk8+Z+S4io2o" + "mRxUZ/dUuS+kITvWph2e4DT28Xpycpl2n1Pa5dCDO1lRqe/5JnaDYDKqxfmF" + "5tTG8GR4d4nVawwLlifXH5Ll7t5NcukGNMCsGuQAHMy0QHuAaOvMdLs5kGHn" + "8VxfKEVKhVrXsvJSwyXXSBtMtUcRtBNnZ2dnZ2dnZyA8Z2dnQGdnZ2c+iQE2" + "BBMBAgAgBQJEIdvsAhsDBgsJCAcDAgQVAggDBBYCAwECHgECF4AACgkQ4M/I" + "er3f9xagdAf/fbKWBjLQM8xR7JkRP4ri8YKOQPhK+VrddGUD59/wzVnvaGyl" + "9MZE7TXFUeniQq5iXKnm22EQbYchv2Jcxyt2H9yptpzyh4tP6tEHl1C887p2" + "J4qe7F2ATua9CzVGwXQSUbKtj2fgUZP5SsNp25guhPiZdtkf2sHMeiotmykF" + "ErzqGMrvOAUThrO63GiYsRk4hF6rcQ01d+EUVpY/sBcCxgNyOiB7a84sDtrx" + "nX5BTEZDTEj8LvuEyEV3TMUuAjx17Eyd+9JtKzwV4v3hlTaWOvGro9nPS7Ya" + "PuG+RtufzXCUJPbPfTjTvtGOqvEzoztls8tuWA0OGHba9XfX9rfgorACAAA="); private static readonly string crOnlyMessage = "\r" + " hello world!\r" + "\r" + "- dash\r"; private static readonly string nlOnlyMessage = "\n" + " hello world!\n" + "\n" + "- dash\n"; private static readonly string crNlMessage = "\r\n" + " hello world!\r\n" + "\r\n" + "- dash\r\n"; private static readonly string crOnlySignedMessage = "-----BEGIN PGP SIGNED MESSAGE-----\r" + "Hash: SHA256\r" + "\r" + "\r" + " hello world!\r" + "\r" + "- - dash\r" + "-----BEGIN PGP SIGNATURE-----\r" + "Version: GnuPG v1.4.2.1 (GNU/Linux)\r" + "\r" + "iQEVAwUBRCNS8+DPyHq93/cWAQi6SwgAj3ItmSLr/sd/ixAQLW7/12jzEjfNmFDt\r" + "WOZpJFmXj0fnMzTrOILVnbxHv2Ru+U8Y1K6nhzFSR7d28n31/XGgFtdohDEaFJpx\r" + "Fl+KvASKIonnpEDjFJsPIvT1/G/eCPalwO9IuxaIthmKj0z44SO1VQtmNKxdLAfK\r" + "+xTnXGawXS1WUE4CQGPM45mIGSqXcYrLtJkAg3jtRa8YRUn2d7b2BtmWH+jVaVuC\r" + "hNrXYv7iHFOu25yRWhUQJisvdC13D/gKIPRvARXPgPhAC2kovIy6VS8tDoyG6Hm5\r" + "dMgLEGhmqsgaetVq1ZIuBZj5S4j2apBJCDpF6GBfpBOfwIZs0Tpmlw==\r" + "=84Nd\r" + "-----END PGP SIGNATURE-----\r"; private static readonly string nlOnlySignedMessage = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA256\n" + "\n" + "\n" + " hello world!\n" + "\n" + "- - dash\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1.4.2.1 (GNU/Linux)\n" + "\n" + "iQEVAwUBRCNS8+DPyHq93/cWAQi6SwgAj3ItmSLr/sd/ixAQLW7/12jzEjfNmFDt\n" + "WOZpJFmXj0fnMzTrOILVnbxHv2Ru+U8Y1K6nhzFSR7d28n31/XGgFtdohDEaFJpx\n" + "Fl+KvASKIonnpEDjFJsPIvT1/G/eCPalwO9IuxaIthmKj0z44SO1VQtmNKxdLAfK\n" + "+xTnXGawXS1WUE4CQGPM45mIGSqXcYrLtJkAg3jtRa8YRUn2d7b2BtmWH+jVaVuC\n" + "hNrXYv7iHFOu25yRWhUQJisvdC13D/gKIPRvARXPgPhAC2kovIy6VS8tDoyG6Hm5\n" + "dMgLEGhmqsgaetVq1ZIuBZj5S4j2apBJCDpF6GBfpBOfwIZs0Tpmlw==\n" + "=84Nd\n" + "-----END PGP SIGNATURE-----\n"; private static readonly string crNlSignedMessage = "-----BEGIN PGP SIGNED MESSAGE-----\r\n" + "Hash: SHA256\r\n" + "\r\n" + "\r\n" + " hello world!\r\n" + "\r\n" + "- - dash\r\n" + "-----BEGIN PGP SIGNATURE-----\r\n" + "Version: GnuPG v1.4.2.1 (GNU/Linux)\r\n" + "\r\n" + "iQEVAwUBRCNS8+DPyHq93/cWAQi6SwgAj3ItmSLr/sd/ixAQLW7/12jzEjfNmFDt\r\n" + "WOZpJFmXj0fnMzTrOILVnbxHv2Ru+U8Y1K6nhzFSR7d28n31/XGgFtdohDEaFJpx\r\n" + "Fl+KvASKIonnpEDjFJsPIvT1/G/eCPalwO9IuxaIthmKj0z44SO1VQtmNKxdLAfK\r\n" + "+xTnXGawXS1WUE4CQGPM45mIGSqXcYrLtJkAg3jtRa8YRUn2d7b2BtmWH+jVaVuC\r\n" + "hNrXYv7iHFOu25yRWhUQJisvdC13D/gKIPRvARXPgPhAC2kovIy6VS8tDoyG6Hm5\r\n" + "dMgLEGhmqsgaetVq1ZIuBZj5S4j2apBJCDpF6GBfpBOfwIZs0Tpmlw==\r\n" + "=84Nd\r" + "-----END PGP SIGNATURE-----\r\n"; private static readonly string crNlSignedMessageTrailingWhiteSpace = "-----BEGIN PGP SIGNED MESSAGE-----\r\n" + "Hash: SHA256\r\n" + "\r\n" + "\r\n" + " hello world! \t\r\n" + "\r\n" + "- - dash\r\n" + "-----BEGIN PGP SIGNATURE-----\r\n" + "Version: GnuPG v1.4.2.1 (GNU/Linux)\r\n" + "\r\n" + "iQEVAwUBRCNS8+DPyHq93/cWAQi6SwgAj3ItmSLr/sd/ixAQLW7/12jzEjfNmFDt\r\n" + "WOZpJFmXj0fnMzTrOILVnbxHv2Ru+U8Y1K6nhzFSR7d28n31/XGgFtdohDEaFJpx\r\n" + "Fl+KvASKIonnpEDjFJsPIvT1/G/eCPalwO9IuxaIthmKj0z44SO1VQtmNKxdLAfK\r\n" + "+xTnXGawXS1WUE4CQGPM45mIGSqXcYrLtJkAg3jtRa8YRUn2d7b2BtmWH+jVaVuC\r\n" + "hNrXYv7iHFOu25yRWhUQJisvdC13D/gKIPRvARXPgPhAC2kovIy6VS8tDoyG6Hm5\r\n" + "dMgLEGhmqsgaetVq1ZIuBZj5S4j2apBJCDpF6GBfpBOfwIZs0Tpmlw==\r\n" + "=84Nd\r" + "-----END PGP SIGNATURE-----\r\n"; public override string Name { get { return "PGPClearSignedSignature"; } } private void messageTest( string message, string type) { ArmoredInputStream aIn = new ArmoredInputStream( new MemoryStream(Encoding.ASCII.GetBytes(message))); string[] headers = aIn.GetArmorHeaders(); if (headers == null || headers.Length != 1) { Fail("wrong number of headers found"); } if (!"Hash: SHA256".Equals(headers[0])) { Fail("header value wrong: " + headers[0]); } // // read the input, making sure we ingore the last newline. // MemoryStream bOut = new MemoryStream(); int ch; while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText()) { bOut.WriteByte((byte)ch); } PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey); PgpObjectFactory pgpFact = new PgpObjectFactory(aIn); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId)); MemoryStream lineOut = new MemoryStream(); Stream sigIn = new MemoryStream(bOut.ToArray(), false); int lookAhead = ReadInputLine(lineOut, sigIn); ProcessLine(sig, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, sigIn); sig.Update((byte) '\r'); sig.Update((byte) '\n'); ProcessLine(sig, lineOut.ToArray()); } while (lookAhead != -1); } if (!sig.Verify()) { Fail("signature failed to verify m_in " + type); } } private PgpSecretKey ReadSecretKey( Stream inputStream) { PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(inputStream); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // // // iterate through the key rings. // foreach (PgpSecretKeyRing kRing in pgpSec.GetKeyRings()) { foreach (PgpSecretKey k in kRing.GetSecretKeys()) { if (k.IsSigningKey) { return k; } } } throw new ArgumentException("Can't find signing key in key ring."); } private void generateTest( string message, string type) { IPgpSecretKey pgpSecKey = ReadSecretKey(new MemoryStream(secretKey)); IPgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey("".ToCharArray()); PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); IEnumerator it = pgpSecKey.PublicKey.GetUserIds().GetEnumerator(); if (it.MoveNext()) { spGen.SetSignerUserId(false, (string)it.Current); sGen.SetHashedSubpackets(spGen.Generate()); } MemoryStream bOut = new MemoryStream(); ArmoredOutputStream aOut = new ArmoredOutputStream(bOut); MemoryStream bIn = new MemoryStream(Encoding.ASCII.GetBytes(message), false); aOut.BeginClearText(HashAlgorithmTag.Sha256); // // note the last \n m_in the file is ignored // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, bIn); ProcessLine(aOut, sGen, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, bIn); sGen.Update((byte) '\r'); sGen.Update((byte) '\n'); ProcessLine(aOut, sGen, lineOut.ToArray()); } while (lookAhead != -1); } aOut.EndClearText(); BcpgOutputStream bcpgOut = new BcpgOutputStream(aOut); sGen.Generate().Encode(bcpgOut); aOut.Close(); byte[] bs = bOut.ToArray(); messageTest(Encoding.ASCII.GetString(bs, 0, bs.Length), type); } private static int ReadInputLine( MemoryStream bOut, Stream fIn) { bOut.SetLength(0); int lookAhead = -1; int ch; while ((ch = fIn.ReadByte()) >= 0) { bOut.WriteByte((byte) ch); if (ch == '\r' || ch == '\n') { lookAhead = ReadPassedEol(bOut, ch, fIn); break; } } return lookAhead; } private static int ReadInputLine( MemoryStream bOut, int lookAhead, Stream fIn) { bOut.SetLength(0); int ch = lookAhead; do { bOut.WriteByte((byte) ch); if (ch == '\r' || ch == '\n') { lookAhead = ReadPassedEol(bOut, ch, fIn); break; } } while ((ch = fIn.ReadByte()) >= 0); return lookAhead; } private static int ReadPassedEol( MemoryStream bOut, int lastCh, Stream fIn) { int lookAhead = fIn.ReadByte(); if (lastCh == '\r' && lookAhead == '\n') { bOut.WriteByte((byte) lookAhead); lookAhead = fIn.ReadByte(); } return lookAhead; } private static void ProcessLine( PgpSignature sig, byte[] line) { int length = GetLengthWithoutWhiteSpace(line); if (length > 0) { sig.Update(line, 0, length); } } private static void ProcessLine( Stream aOut, PgpSignatureGenerator sGen, byte[] line) { int length = GetLengthWithoutWhiteSpace(line); if (length > 0) { sGen.Update(line, 0, length); } aOut.Write(line, 0, line.Length); } private static int GetLengthWithoutWhiteSpace( byte[] line) { int end = line.Length - 1; while (end >= 0 && IsWhiteSpace(line[end])) { end--; } return end + 1; } private static bool IsWhiteSpace( byte b) { return b == '\r' || b == '\n' || b == '\t' || b == ' '; } public override void PerformTest() { messageTest(crOnlySignedMessage, "\\r"); messageTest(nlOnlySignedMessage, "\\n"); messageTest(crNlSignedMessage, "\\r\\n"); messageTest(crNlSignedMessageTrailingWhiteSpace, "\\r\\n"); generateTest(nlOnlyMessage, "\\r"); generateTest(crOnlyMessage, "\\n"); generateTest(crNlMessage, "\\r\\n"); } public static void Main( string[] args) { RunTest(new PgpClearSignedSignatureTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using System; using System.IO; using System.Text; namespace mp3info { /// <summary> /// Piece of ID3v2 reader. reads frmes one at a time given the proper position in a binary stream /// </summary> public class id3v2Frame { public string frameName; public byte[] frameContents; public ulong frameSize; public int MajorVersion; public bool F_TagAlterPreservation; public bool F_FileAlterPreservation; public bool F_ReadOnly; public bool F_Compression; public bool F_Encryption; public bool F_GroupingIdentity; public bool F_Unsynchronisation; public bool F_DataLengthIndicator; public bool padding; public id3v2Frame() { this.padding = false; this.frameName =""; this.frameSize = 0; this.MajorVersion = 0; this.F_TagAlterPreservation = false; this.F_FileAlterPreservation = false; this.F_ReadOnly = false; this.F_Compression= false; this.F_Encryption = false; this.F_GroupingIdentity = false; this.F_Unsynchronisation = false; this.F_DataLengthIndicator = false; } public id3v2Frame ReadFrame (BinaryReader br, int version) { char[] tagSize; // I use this to read the bytes in from the file int[] bytes; // for bit shifting ulong newSize = 0; // for the final number int nameSize = 4; if (version == 2) { nameSize = 3; } else if ((version == 3) || (version == 4)) { nameSize = 4; } id3v2Frame f1 = new id3v2Frame(); f1.frameName = new string (br.ReadChars(nameSize)); f1.MajorVersion = version; // in order to check for padding I have to build a string of 4 (or 3 if v2.2) null bytes // there must be a better way to do this char nullChar = System.Convert.ToChar(0); StringBuilder sb = new StringBuilder(0,nameSize); sb.Append(nullChar); sb.Append(nullChar); sb.Append(nullChar); if (nameSize == 4) { sb.Append(nullChar); } if (f1.frameName == sb.ToString()) { f1.padding = true; return f1; } if (version == 2) { // only have 3 bytes for size ; tagSize = br.ReadChars(3); // I use this to read the bytes in from the file bytes = new int[3]; // for bit shifting newSize = 0; // for the final number // The ID3v2 tag size is encoded with four bytes // where the most significant bit (bit 7) // is set to zero in every byte, // making a total of 28 bits. // The zeroed bits are ignored // // Some bit grinding is necessary. Hang on. bytes[3] = tagSize[2] | ((tagSize[1] & 1) << 7) ; bytes[2] = ((tagSize[1] >> 1) & 63) | ((tagSize[0] & 3) << 6) ; bytes[1] = ((tagSize[0] >> 2) & 31) ; newSize = ((UInt64)bytes[3] | ((UInt64)bytes[2] << 8) | ((UInt64)bytes[1] << 16)); //End Dan Code } else if (version == 3 || version == 4) { // version 2.4 tagSize = br.ReadChars(4); // I use this to read the bytes in from the file bytes = new int[4]; // for bit shifting newSize = 0; // for the final number // The ID3v2 tag size is encoded with four bytes // where the most significant bit (bit 7) // is set to zero in every byte, // making a total of 28 bits. // The zeroed bits are ignored // // Some bit grinding is necessary. Hang on. bytes[3] = tagSize[3] | ((tagSize[2] & 1) << 7) ; bytes[2] = ((tagSize[2] >> 1) & 63) | ((tagSize[1] & 3) << 6) ; bytes[1] = ((tagSize[1] >> 2) & 31) | ((tagSize[0] & 7) << 5) ; bytes[0] = ((tagSize[0] >> 3) & 15) ; newSize = ((UInt64)bytes[3] | ((UInt64)bytes[2] << 8) | ((UInt64)bytes[1] << 16) | ((UInt64)bytes[0] << 24)) ; //End Dan Code } f1.frameSize = newSize; if (version > 2) { // versions 3+ have frame tags. if (version == 3) { bool [] c; // read teh tags c = BitReader.ToBitBool(br.ReadByte()); f1.F_TagAlterPreservation = c[0]; f1.F_FileAlterPreservation= c[1]; f1.F_ReadOnly= c[2]; c = BitReader.ToBitBool(br.ReadByte()); f1.F_Compression= c[0]; f1.F_Encryption= c[1]; f1.F_GroupingIdentity= c[2]; } else if (version == 4) { //%0abc0000 %0h00kmnp //a - Tag alter preservation // 0 Frame should be preserved. // 1 Frame should be discarded. // b - File alter preservation // 0 Frame should be preserved. //1 Frame should be discarded. // c - Read only // h - Grouping identity // 0 Frame does not contain group information // 1 Frame contains group information // k - Compression // 0 Frame is not compressed. // 1 Frame is compressed using zlib [zlib] deflate method. // If set, this requires the 'Data Length Indicator' bit // to be set as well. // m - Encryption // 0 Frame is not encrypted. // 1 Frame is encrypted. // n - Unsynchronisation // 0 Frame has not been unsynchronised. // 1 Frame has been unsyrchronised. // p - Data length indicator // 0 There is no Data Length Indicator. // 1 A data length Indicator has been added to the frame. bool [] c; // read teh tags c = BitReader.ToBitBool(br.ReadByte()); f1.F_TagAlterPreservation = c[1]; f1.F_FileAlterPreservation= c[2]; f1.F_ReadOnly= c[3]; c = BitReader.ToBitBool(br.ReadByte()); f1.F_GroupingIdentity= c[1]; f1.F_Compression= c[4]; f1.F_Encryption= c[5]; f1.F_Unsynchronisation = c[6]; f1.F_DataLengthIndicator = c[7]; } if (f1.frameSize > 0) { f1.frameContents = br.ReadBytes((int)f1.frameSize); } } return f1; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Threading; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class is an implementation of IEngineCallback which is used on the child nodes to receive calls from /// the child to the parent. /// </summary> internal class LocalNodeCallback : IEngineCallback { /// <summary> /// All the necessary data required for a reply to a call /// </summary> internal class ReplyData { // The call descriptor for the actual reply internal LocalReplyCallDescriptor reply; // wait event on which the requesting thread waits and which should be set by the replying thread internal ManualResetEvent waitEvent; } #region Constructors /// <summary> /// This class is an implementation of IEngineCallback which is used on the child nodes /// </summary> internal LocalNodeCallback(ManualResetEvent exitCommunicationThreads, LocalNode localNode) { this.localNode = localNode; this.exitCommunicationThreads = exitCommunicationThreads; this.nodeCommandQueue = new DualQueue<LocalCallDescriptor>(); this.nodeHiPriCommandQueue = new DualQueue<LocalCallDescriptor>(); // Initalize the reply infrastructur this.repliesFromParent = new Hashtable(); } internal void StartWriterThread(int nodeNumber) { this.writerThreadHasExited = false; this.sharedMemory = new SharedMemory ( LocalNodeProviderGlobalNames.NodeOutputMemoryName(nodeNumber), SharedMemoryType.WriteOnly, true ); ErrorUtilities.VerifyThrow(this.sharedMemory.IsUsable, "Failed to create shared memory for engine callback."); // Start the thread that will be processing the calls to the parent engine ThreadStart threadState = new ThreadStart(this.SharedMemoryWriterThread); writerThread = new Thread(threadState); writerThread.Name = "MSBuild Child->Parent Writer"; writerThread.Start(); } #endregion #region Methods /// <summary> /// This method is used to post calls to the parent engine by the Localnode class /// </summary> internal void PostMessageToParent(LocalCallDescriptor callDescriptor, bool waitForCompletion) { nodeCommandQueue.Enqueue(callDescriptor); try { if (waitForCompletion) { // We should not be on the running on the callback writer thread ErrorUtilities.VerifyThrow(Thread.CurrentThread != writerThread, "Should never call this function from the writer thread"); // We need to block until the event we posted has been processed, but if the writer thread // exit due to an error the shared memory is no longer valid so there is no way to send the message while (!writerThreadHasExited && nodeCommandQueue.Count > 0) { nodeCommandQueue.QueueEmptyEvent.WaitOne(1000, false); // Check if the communication threads are supposed to exit if (exitCommunicationThreads.WaitOne(0, false)) { break; } } } } catch (Exception e) { // Clear the current queue since something in the queue has caused a problem nodeCommandQueue.Clear(); // Try to send the exception back to the parent localNode.ReportNonFatalCommunicationError(e); } } /// <summary> /// This method is used to post replies from the parent engine by the Localnode class /// </summary> internal void PostReplyFromParent(LocalReplyCallDescriptor reply) { int requestingCallNumber = reply.RequestingCallNumber; lock (repliesFromParent) { ReplyData replyData = (ReplyData) repliesFromParent[requestingCallNumber]; ErrorUtilities.VerifyThrow(replyData?.waitEvent != null, "We must have an event for this call at this point"); replyData.reply = reply; replyData.waitEvent.Set(); } } /// <summary> /// This method is reset the state of shared memory when the node is reused for a different /// build /// </summary> internal void Reset() { // Make sure there nothing left over in the command queues nodeCommandQueue.Clear(); nodeHiPriCommandQueue.Clear(); sharedMemory.Reset(); ErrorUtilities.VerifyThrow(nodeCommandQueue.Count == 0, "Expect all event to be flushed"); } internal Thread GetWriterThread() { return writerThread; } /// <summary> /// This method is used to write to shared memory /// </summary> private void SharedMemoryWriterThread() { // Create an array of event to the node thread responds WaitHandle[] waitHandles = new WaitHandle[3]; waitHandles[0] = exitCommunicationThreads; waitHandles[1] = nodeCommandQueue.QueueReadyEvent; waitHandles[2] = nodeHiPriCommandQueue.QueueReadyEvent; bool continueExecution = true; try { while (continueExecution) { // Wait for the next work item or an exit command int eventType = WaitHandle.WaitAny(waitHandles); if (eventType == 0) { // Exit node event continueExecution = false; } else { sharedMemory.Write(nodeCommandQueue, nodeHiPriCommandQueue, true); } } } catch (Exception e) { // Will rethrow the exception if necessary localNode.ReportFatalCommunicationError(e); } finally { writerThreadHasExited = true; } // Dispose of the shared memory buffer if (sharedMemory != null) { sharedMemory.Dispose(); sharedMemory = null; } } #region IEngineCallback implementation /// <summary> /// This method is called by the node to post build /// requests into a queue in the parent engine /// </summary> public void PostBuildRequestsToHost(BuildRequest[] buildRequests) { LocalCallDescriptorForPostBuildRequests callDescriptor = new LocalCallDescriptorForPostBuildRequests(buildRequests); nodeCommandQueue.Enqueue(callDescriptor); } /// <summary> /// This method is used by the child node to post results of a build request back to the /// parent node. The parent node then decides if need to re-route the results to another node /// that requested the evaluation or if it will consume the result locally /// </summary> public void PostBuildResultToHost(BuildResult buildResult) { LocalCallDescriptorForPostBuildResult callDescriptor = new LocalCallDescriptorForPostBuildResult(buildResult); nodeCommandQueue.Enqueue(callDescriptor); } /// <summary> /// Submit the logging message to the engine queue. /// </summary> public void PostLoggingMessagesToHost(int nodeProviderId, NodeLoggingEvent[] nodeLoggingEventArray) { LocalCallDescriptorForPostLoggingMessagesToHost callDescriptor = new LocalCallDescriptorForPostLoggingMessagesToHost(nodeLoggingEventArray); nodeCommandQueue.Enqueue(callDescriptor); } /// <summary> /// Given a non-void call descriptor, calls it and retrieves the return value. /// </summary> /// <param name="callDescriptor"></param> /// <returns></returns> private object GetReplyForCallDescriptor(LocalCallDescriptor callDescriptor) { // ReplyFromParentArrived is a TLS field, so initialize it if it's empty if (replyFromParentArrived == null) { replyFromParentArrived = new ManualResetEvent(false); } replyFromParentArrived.Reset(); int requestingCallNumber = callDescriptor.CallNumber; ReplyData replyData = new ReplyData(); replyData.waitEvent = replyFromParentArrived; // Register our wait event for the call id lock (repliesFromParent) { repliesFromParent[requestingCallNumber] = replyData; } nodeCommandQueue.Enqueue(callDescriptor); replyFromParentArrived.WaitOne(); LocalCallDescriptor reply = null; // Unregister the wait event lock (repliesFromParent) { // Get the reply reply = replyData.reply; ErrorUtilities.VerifyThrow(reply != null, "We must have a reply if the wait event was set"); repliesFromParent.Remove(requestingCallNumber); } return reply.GetReplyData(); } /// <summary> /// This method retrieves the cache entries from the master cache /// </summary> /// <param name="nodeId"></param> /// <param name="names"></param> /// <param name="scopeName"></param> /// <param name="scopeProperties"></param> /// <returns></returns> public CacheEntry[] GetCachedEntriesFromHost(int nodeId, string[] names, string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType) { LocalCallDescriptorForGettingCacheEntriesFromHost callDescriptor = new LocalCallDescriptorForGettingCacheEntriesFromHost(names, scopeName, scopeProperties, scopeToolsVersion, cacheContentType); return (CacheEntry[])GetReplyForCallDescriptor(callDescriptor); } /// <summary> /// Send the cache entries to the parent engine /// </summary> /// <param name="nodeId"></param> /// <param name="entries"></param> /// <param name="scopeName"></param> /// <param name="scopeProperties"></param> public Exception PostCacheEntriesToHost(int nodeId, CacheEntry[] entries, string scopeName, BuildPropertyGroup scopeProperties, string scopeToolsVersion, CacheContentType cacheContentType) { LocalCallDescriptorForPostingCacheEntriesToHost callDescriptor = new LocalCallDescriptorForPostingCacheEntriesToHost(entries, scopeName, scopeProperties, scopeToolsVersion, cacheContentType); return (Exception)GetReplyForCallDescriptor(callDescriptor); } /// <summary> /// This method is called to post the status of the node. Because status is used /// to report errors and to respond to inactivity notices, we use a separate queue /// to deliver status event to the shared memory. Otherwise status maybe be delayed /// if it is stuck behind a large number of other events. We also wait for the status /// to be sent before returning. /// </summary> public void PostStatus(int nodeId, NodeStatus nodeStatus, bool blockUntilSent) { // We should not be on the running on the callback writer thread ErrorUtilities.VerifyThrow(Thread.CurrentThread != writerThread, "Should never call this function from the writer thread"); LocalCallDescriptorForPostStatus callDescriptor = new LocalCallDescriptorForPostStatus(nodeStatus); nodeHiPriCommandQueue.Enqueue(callDescriptor); // We need to block until the event we posted has been processed, but if the writer thread // exit due to an error the shared memory is no longer valid so there is no way to send the message while (blockUntilSent && !writerThreadHasExited && nodeHiPriCommandQueue.Count > 0) { nodeHiPriCommandQueue.QueueEmptyEvent.WaitOne(1000, false); // Check if the communication threads are supposed to exit if (exitCommunicationThreads.WaitOne(0, false)) { break; } } } #endregion #endregion #region Data private LocalNode localNode; private DualQueue<LocalCallDescriptor> nodeCommandQueue; private DualQueue<LocalCallDescriptor> nodeHiPriCommandQueue; private SharedMemory sharedMemory; private ManualResetEvent exitCommunicationThreads; private bool writerThreadHasExited; private Thread writerThread; [ThreadStatic] private static ManualResetEvent replyFromParentArrived; // K: call id; V: ReplyData class with the wait event and reply call descriptor private Hashtable repliesFromParent; #endregion } }
/*************************************************************************** * * CurlS#arp * * Copyright (c) 2013 Dr. Masroor Ehsan (masroore@gmail.com) * Portions copyright (c) 2004, 2005 Jeff Phillips (jeff@jeffp.net) * * This software is licensed as described in the file LICENSE, which you * should have received as part of this distribution. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of this Software, and permit persons to whom the Software is * furnished to do so, under the terms of the LICENSE file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF * ANY KIND, either express or implied. * **************************************************************************/ using System; using System.Runtime.InteropServices; namespace CurlSharp { /// <summary> /// This class provides an infrastructure for serializing access to data /// shared by multiple <see cref="CurlEasy" /> objects, including cookie data /// and Dns hosts. It implements the <c>curl_share_xxx</c> API. /// </summary> public class CurlShare : IDisposable { // private members private GCHandle _hThis; // for handle extraction #if USE_LIBCURLSHIM private NativeMethods._ShimLockCallback _pDelLock; // lock delegate private NativeMethods._ShimUnlockCallback _pDelUnlock; // unlock delegate #endif private IntPtr _pShare; // share handle private IntPtr _ptrThis; // numeric handle /// <summary> /// Constructor /// </summary> /// <exception cref="System.InvalidOperationException"> /// This is thrown /// if <see cref="Curl" /> hasn't bee properly initialized. /// </exception> /// <exception cref="System.NullReferenceException"> /// This is thrown if /// the native <c>share</c> handle wasn't created successfully. /// </exception> public CurlShare() { Curl.EnsureCurl(); _pShare = NativeMethods.curl_share_init(); EnsureHandle(); LockFunction = null; UnlockFunction = null; UserData = null; installDelegates(); } public object UserData { get; set; } public CurlShareUnlockCallback UnlockFunction { get; set; } public CurlShareLockCallback LockFunction { get; set; } public CurlLockData Share { set { setShareOption(CurlShareOption.Share, value); } } public CurlLockData Unshare { set { setShareOption(CurlShareOption.Unshare, value); } } public CurlShareCode LastErrorCode { get; private set; } public string LastErrorDescription { get; private set; } /// <summary> /// Cleanup unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Destructor /// </summary> ~CurlShare() { Dispose(false); } /// <summary> /// Set options for this object. /// </summary> /// <param name="option"> /// One of the values in the <see cref="CurlShareOption" /> /// enumeration. /// </param> /// <param name="parameter"> /// An appropriate object based on the value passed in the /// <c>option</c> argument. See <see cref="CurlShareOption" /> /// for more information about the appropriate parameter type. /// </param> /// <returns> /// A <see cref="CurlShareCode" />, hopefully /// <c>CurlShareCode.Ok</c>. /// </returns> /// <exception cref="System.NullReferenceException"> /// This is thrown if /// the native <c>share</c> handle wasn't created successfully. /// </exception> public CurlShareCode SetOpt(CurlShareOption option, object parameter) { EnsureHandle(); var retCode = CurlShareCode.Ok; switch (option) { case CurlShareOption.LockFunction: var lf = parameter as CurlShareLockCallback; if (lf == null) return CurlShareCode.BadOption; LockFunction = lf; break; case CurlShareOption.UnlockFunction: var ulf = parameter as CurlShareUnlockCallback; if (ulf == null) return CurlShareCode.BadOption; UnlockFunction = ulf; break; case CurlShareOption.Share: case CurlShareOption.Unshare: { var opt = (CurlLockData) Convert.ToInt32(parameter); retCode = setShareOption(option, opt); break; } case CurlShareOption.UserData: UserData = parameter; break; default: retCode = CurlShareCode.BadOption; break; } return retCode; } private void setLastError(CurlShareCode code, CurlShareOption opt) { if ((LastErrorCode == CurlShareCode.Ok) && (code != CurlShareCode.Ok)) { LastErrorCode = code; LastErrorDescription = $"Error: {StrError(code)} setting option {opt}"; } } private CurlShareCode setShareOption(CurlShareOption option, CurlLockData value) { var retCode = (value != CurlLockData.Cookie) && (value != CurlLockData.Dns) ? CurlShareCode.BadOption : NativeMethods.curl_share_setopt(_pShare, option, (IntPtr) value); setLastError(retCode, option); return retCode; } /// <summary> /// Return a String description of an error code. /// </summary> /// <param name="errorNum"> /// The <see cref="CurlShareCode" /> for which to obtain the error /// string description. /// </param> /// <returns>The string description.</returns> public string StrError(CurlShareCode errorNum) => Marshal.PtrToStringAnsi(NativeMethods.curl_share_strerror(errorNum)); private void Dispose(bool disposing) { lock (this) { // if (disposing) cleanup managed objects if (_pShare != IntPtr.Zero) { #if USE_LIBCURLSHIM NativeMethods.curl_shim_cleanup_share_delegates(_pShare); #endif NativeMethods.curl_share_cleanup(_pShare); _hThis.Free(); _ptrThis = IntPtr.Zero; _pShare = IntPtr.Zero; } } } internal IntPtr GetHandle() => _pShare; private void EnsureHandle() { if (_pShare == IntPtr.Zero) throw new NullReferenceException("No internal share handle"); } private void installDelegates() { _hThis = GCHandle.Alloc(this); _ptrThis = (IntPtr) _hThis; #if USE_LIBCURLSHIM _pDelLock = LockDelegate; _pDelUnlock = UnlockDelegate; NativeMethods.curl_shim_install_share_delegates(_pShare, _ptrThis, _pDelLock, _pDelUnlock); #endif } internal static void LockDelegate(int data, int access, IntPtr userPtr) { var gch = (GCHandle) userPtr; var share = (CurlShare) gch.Target; share?.LockFunction?.Invoke((CurlLockData) data, (CurlLockAccess) access, share.UserData); } internal static void UnlockDelegate(int data, IntPtr userPtr) { var gch = (GCHandle) userPtr; var share = (CurlShare) gch.Target; share?.UnlockFunction?.Invoke((CurlLockData) data, share.UserData); } } }