content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// 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 Analyzer.Utilities; using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Analyzers.UnitTests.MetaAnalyzers { public class DiagnosticDescriptorCreationAnalyzerTests : DiagnosticAnalyzerTestBase { #region RS1007 (UseLocalizableStringsInDescriptorRuleId) and RS1015 (ProvideHelpUriInDescriptorRuleId) [Fact] public void RS1007_RS1015_CSharp_VerifyDiagnostic() { var source = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor); } } public override void Initialize(AnalysisContext context) { } }"; DiagnosticResult[] expected = new[] { GetCSharpRS1007ExpectedDiagnostic(11, 9), GetCSharpRS1015ExpectedDiagnostic(11, 9) }; VerifyCSharp(source, expected); } [Fact] public void RS1007_RS1015_VisualBasic_VerifyDiagnostic() { var source = @" Imports System Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Class MyAnalyzer Inherits DiagnosticAnalyzer Private Shared ReadOnly descriptor As DiagnosticDescriptor = new DiagnosticDescriptor(""MyDiagnosticId"", ""MyDiagnosticTitle"", ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:= true) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) End Sub End Class "; DiagnosticResult[] expected = new[] { GetBasicRS1007ExpectedDiagnostic(10, 66), GetBasicRS1015ExpectedDiagnostic(10, 70) }; VerifyBasic(source, expected); } [Fact] public void RS1007_RS1015_CSharp_VerifyDiagnostic_NamedArgumentCases() { var source = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(""MyDiagnosticId"", messageFormat: ""MyDiagnosticMessage"", title: ""MyDiagnosticTitle"", helpLinkUri: null, category: ""MyDiagnosticCategory"", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""MyDiagnosticId"", messageFormat: ""MyDiagnosticMessage"", title: ""MyDiagnosticTitle"", category: ""MyDiagnosticCategory"", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor); } } public override void Initialize(AnalysisContext context) { } }"; DiagnosticResult[] expected = new[] { GetCSharpRS1007ExpectedDiagnostic(11, 9), GetCSharpRS1015ExpectedDiagnostic(11, 118), GetCSharpRS1007ExpectedDiagnostic(14, 9), GetCSharpRS1015ExpectedDiagnostic(14, 9) }; VerifyCSharp(source, expected); } [Fact] public void RS1007_RS1015_VisualBasic_VerifyDiagnostic_NamedArgumentCases() { var source = @" Imports System Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Class MyAnalyzer Inherits DiagnosticAnalyzer Private Shared ReadOnly descriptor As DiagnosticDescriptor = new DiagnosticDescriptor(""MyDiagnosticId"", title:=""MyDiagnosticTitle"", helpLinkUri:=Nothing, messageFormat:=""MyDiagnosticMessage"", category:=""MyDiagnosticCategory"", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:= true) Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new DiagnosticDescriptor(""MyDiagnosticId"", title:=""MyDiagnosticTitle"", messageFormat:=""MyDiagnosticMessage"", category:=""MyDiagnosticCategory"", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:= true) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) End Sub End Class "; DiagnosticResult[] expected = new[] { GetBasicRS1007ExpectedDiagnostic(10, 66), GetBasicRS1015ExpectedDiagnostic(10, 137), GetBasicRS1007ExpectedDiagnostic(11, 67), GetBasicRS1015ExpectedDiagnostic(11, 71) }; VerifyBasic(source, expected); } [Fact] public void RS1007_RS1015_CSharp_NoDiagnosticCases() { var source = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer : DiagnosticAnalyzer { private static LocalizableString dummyLocalizableTitle = new LocalizableResourceString(""dummyName"", null, null); private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(""MyDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri = ""HelpLink""); private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""MyDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, true, ""MyDiagnosticDescription"", ""HelpLink""); private static readonly DiagnosticDescriptor descriptor3 = new DiagnosticDescriptor(helpLinkUri: ""HelpLink"", id: ""MyDiagnosticId"", messageFormat:""MyDiagnosticMessage"", title: dummyLocalizableTitle, category: ""MyDiagnosticCategory"", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor descriptor4 = new DiagnosticDescriptor(helpLinkUri: ""HelpLink"", title: dummyLocalizableTitle); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor); } } public override void Initialize(AnalysisContext context) { } } "; VerifyCSharp(source, TestValidationMode.AllowCompileErrors); } [Fact] public void RS1007_RS1015_VisualBasic_NoDiagnosticCases() { var source = @" Imports System Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Class MyAnalyzer Inherits DiagnosticAnalyzer Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = new LocalizableResourceString(""dummyName"", Nothing, Nothing) Private Shared ReadOnly descriptor As DiagnosticDescriptor = new DiagnosticDescriptor(""MyDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new DiagnosticDescriptor(""MyDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, True, ""MyDiagnosticDescription"", ""HelpLink"") Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = new DiagnosticDescriptor(helpLinkUri:=""HelpLink"", id:=""MyDiagnosticId"", title:=dummyLocalizableTitle, messageFormat:=""MyDiagnosticMessage"", category:=""MyDiagnosticCategory"", defaultSeverity:=DiagnosticSeverity.Warning, isEnabledByDefault:=true) Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = new DiagnosticDescriptor(helpLinkUri:=""HelpLink"", title:=dummyLocalizableTitle) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) End Sub End Class "; VerifyBasic(source, TestValidationMode.AllowCompileErrors); } #endregion #region RS1017 (DiagnosticIdMustBeAConstantRuleId) and RS1019 (UseUniqueDiagnosticIdRuleId) [Fact] public void RS1017_RS1019_CSharp_VerifyDiagnostic() { var source = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer : DiagnosticAnalyzer { private static readonly string NonConstantDiagnosticId = ""NonConstantDiagnosticId""; private static LocalizableResourceString dummyLocalizableTitle = null; private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(NonConstantDiagnosticId, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor, descriptor2); } } public override void Initialize(AnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer2 : DiagnosticAnalyzer { private static LocalizableString dummyLocalizableTitle = null; private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor); } } public override void Initialize(AnalysisContext context) { } }"; DiagnosticResult[] expected = new[] { // Test0.cs(14,34): warning RS1017: Diagnostic Id for rule 'descriptor' must be a non-null constant. GetCSharpRS1017ExpectedDiagnostic(14, 34, "descriptor"), // Test0.cs(38,34): warning RS1019: Diagnostic Id 'DuplicateDiagnosticId' is already used by analyzer 'MyAnalyzer'. Please use a different diagnostic ID. GetCSharpRS1019ExpectedDiagnostic(38, 34, "DuplicateDiagnosticId", "MyAnalyzer") }; VerifyCSharp(source, expected); } [Fact] public void RS1017_RS1019_VisualBasic_VerifyDiagnostic() { var source = @" Imports System Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Class MyAnalyzer Inherits DiagnosticAnalyzer Private Shared ReadOnly NonConstantDiagnosticId = ""NonConstantDiagnosticId"" Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing Private Shared ReadOnly descriptor As DiagnosticDescriptor = new DiagnosticDescriptor(NonConstantDiagnosticId, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(descriptor, descriptor2) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) End Sub End Class <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Class MyAnalyzer2 Inherits DiagnosticAnalyzer Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing Private Shared ReadOnly descriptor As DiagnosticDescriptor = new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) End Sub End Class "; DiagnosticResult[] expected = new[] { // Test0.vb(12,91): warning RS1017: Diagnostic Id for rule 'descriptor' must be a non-null constant. GetBasicRS1017ExpectedDiagnostic(12, 91, "descriptor"), // Test0.vb(29,91): warning RS1019: Diagnostic Id 'DuplicateDiagnosticId' is already used by analyzer 'MyAnalyzer'. Please use a different diagnostic ID. GetBasicRS1019ExpectedDiagnostic(29, 91, "DuplicateDiagnosticId", "MyAnalyzer") }; VerifyBasic(source, expected); } [Fact] public void RS1017_RS1019_CSharp_NoDiagnosticCases() { var source = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer : DiagnosticAnalyzer { private const string ConstantDiagnosticId = ""ConstantDiagnosticId""; private static LocalizableString dummyLocalizableTitle = null; private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(ConstantDiagnosticId, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); // Allow multiple descriptors with same rule ID in the same analyzer. private static readonly DiagnosticDescriptor descriptor3 = new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage2"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor, descriptor2, descriptor3); } } public override void Initialize(AnalysisContext context) { } } "; VerifyCSharp(source); } [Fact] public void RS1017_RS1019_VisualBasic_NoDiagnosticCases() { var source = @" Imports System Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Class MyAnalyzer Inherits DiagnosticAnalyzer Const ConstantDiagnosticId As String = ""ConstantDiagnosticId"" Private Shared ReadOnly dummyLocalizableTitle As LocalizableString = Nothing Private Shared ReadOnly descriptor As DiagnosticDescriptor = new DiagnosticDescriptor(ConstantDiagnosticId, dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") ' Allow multiple descriptors with same rule ID in the same analyzer. Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = new DiagnosticDescriptor(""DuplicateDiagnosticId"", dummyLocalizableTitle, ""MyDiagnosticMessage2"", ""MyDiagnosticCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=true, helpLinkUri:=""HelpLink"") Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(descriptor, descriptor2, descriptor3) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) End Sub End Class "; VerifyBasic(source); } #endregion #region RS1018 (DiagnosticIdMustBeInSpecifiedFormatRuleId) and RS1020 (UseCategoriesFromSpecifiedRangeRuleId) [Fact] public void RS1018_RS1020_CSharp_VerifyDiagnostic() { var source = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer : DiagnosticAnalyzer { private static LocalizableResourceString dummyLocalizableTitle = null; private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""DifferentPrefixId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor3 = new DiagnosticDescriptor(""Prefix200"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor4 = new DiagnosticDescriptor(""Prefix101"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor5 = new DiagnosticDescriptor(""MySecondPrefix400"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor6 = new DiagnosticDescriptor(""MyThirdPrefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6); } } public override void Initialize(AnalysisContext context) { } } "; string additionalText = @" # FORMAT: # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' CategoryWithNoIdRangeOrFormat CategoryWithPrefix: Prefix CategoryWithRange: Prefix000-Prefix099 CategoryWithId: Prefix100 CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 "; DiagnosticResult[] expected = new[] { // Test0.cs(13,87): warning RS1020: Category 'NotAllowedCategory' is not from the allowed categories specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetCSharpRS1020ExpectedDiagnostic(13, 87, "NotAllowedCategory", AdditionalFileName), // Test0.cs(16,34): warning RS1018: Diagnostic Id 'DifferentPrefixId' belonging to category 'CategoryWithPrefix' is not in the required range and/or format 'PrefixXXXX' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetCSharpRS1018ExpectedDiagnostic(16, 34, "DifferentPrefixId", "CategoryWithPrefix", "PrefixXXXX", AdditionalFileName), // Test0.cs(19,34): warning RS1018: Diagnostic Id 'Prefix200' belonging to category 'CategoryWithRange' is not in the required range and/or format 'Prefix0-Prefix99' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetCSharpRS1018ExpectedDiagnostic(19, 34, "Prefix200", "CategoryWithRange", "Prefix0-Prefix99", AdditionalFileName), // Test0.cs(22,34): warning RS1018: Diagnostic Id 'Prefix101' belonging to category 'CategoryWithId' is not in the required range and/or format 'Prefix100-Prefix100' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetCSharpRS1018ExpectedDiagnostic(22, 34, "Prefix101", "CategoryWithId", "Prefix100-Prefix100", AdditionalFileName), // Test0.cs(25,34): warning RS1018: Diagnostic Id 'MySecondPrefix400' belonging to category 'CategoryWithPrefixRangeAndId' is not in the required range and/or format 'MyFirstPrefixXXXX, MySecondPrefix0-MySecondPrefix99, MySecondPrefix300-MySecondPrefix300' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetCSharpRS1018ExpectedDiagnostic(25, 34, "MySecondPrefix400", "CategoryWithPrefixRangeAndId", "MyFirstPrefixXXXX, MySecondPrefix0-MySecondPrefix99, MySecondPrefix300-MySecondPrefix300", AdditionalFileName), // Test0.cs(28,34): warning RS1018: Diagnostic Id 'MyThirdPrefix' belonging to category 'CategoryWithPrefixRangeAndId' is not in the required range and/or format 'MyFirstPrefixXXXX, MySecondPrefix0-MySecondPrefix99, MySecondPrefix300-MySecondPrefix300' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetCSharpRS1018ExpectedDiagnostic(28, 34, "MyThirdPrefix", "CategoryWithPrefixRangeAndId", "MyFirstPrefixXXXX, MySecondPrefix0-MySecondPrefix99, MySecondPrefix300-MySecondPrefix300", AdditionalFileName) }; VerifyCSharp(source, GetAdditionalFile(additionalText), expected); } [Fact] public void RS1018_RS1020_VisualBasic_VerifyDiagnostic() { var source = @" Imports System Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Class MyAnalyzer Inherits DiagnosticAnalyzer Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing Private Shared ReadOnly descriptor As DiagnosticDescriptor = New DiagnosticDescriptor(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor(""DifferentPrefixId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New DiagnosticDescriptor(""Prefix200"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New DiagnosticDescriptor(""Prefix101"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New DiagnosticDescriptor(""MySecondPrefix400"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New DiagnosticDescriptor(""MyThirdPrefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6) End Get End Property Public Overrides Sub Initialize(ByVal context As AnalysisContext) End Sub End Class "; string additionalText = @" # FORMAT: # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' CategoryWithNoIdRangeOrFormat CategoryWithPrefix: Prefix CategoryWithRange: Prefix000-Prefix099 CategoryWithId: Prefix100 CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 "; DiagnosticResult[] expected = new[] { // Test0.vb(12,144): warning RS1020: Category 'NotAllowedCategory' is not from the allowed categories specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetBasicRS1020ExpectedDiagnostic(12, 144, "NotAllowedCategory", AdditionalFileName), // Test0.vb(13,92): warning RS1018: Diagnostic Id 'DifferentPrefixId' belonging to category 'CategoryWithPrefix' is not in the required range and/or format 'PrefixXXXX' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetBasicRS1018ExpectedDiagnostic(13, 92, "DifferentPrefixId", "CategoryWithPrefix", "PrefixXXXX", AdditionalFileName), // Test0.vb(14,92): warning RS1018: Diagnostic Id 'Prefix200' belonging to category 'CategoryWithRange' is not in the required range and/or format 'Prefix0-Prefix99' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetBasicRS1018ExpectedDiagnostic(14, 92, "Prefix200", "CategoryWithRange", "Prefix0-Prefix99", AdditionalFileName), // Test0.vb(15,92): warning RS1018: Diagnostic Id 'Prefix101' belonging to category 'CategoryWithId' is not in the required range and/or format 'Prefix100-Prefix100' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetBasicRS1018ExpectedDiagnostic(15, 92, "Prefix101", "CategoryWithId", "Prefix100-Prefix100", AdditionalFileName), // Test0.vb(16,92): warning RS1018: Diagnostic Id 'MySecondPrefix400' belonging to category 'CategoryWithPrefixRangeAndId' is not in the required range and/or format 'MyFirstPrefixXXXX, MySecondPrefix0-MySecondPrefix99, MySecondPrefix300-MySecondPrefix300' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetBasicRS1018ExpectedDiagnostic(16, 92, "MySecondPrefix400", "CategoryWithPrefixRangeAndId", "MyFirstPrefixXXXX, MySecondPrefix0-MySecondPrefix99, MySecondPrefix300-MySecondPrefix300", AdditionalFileName), // Test0.vb(17,92): warning RS1018: Diagnostic Id 'MyThirdPrefix' belonging to category 'CategoryWithPrefixRangeAndId' is not in the required range and/or format 'MyFirstPrefixXXXX, MySecondPrefix0-MySecondPrefix99, MySecondPrefix300-MySecondPrefix300' specified in the file 'DiagnosticCategoryAndIdRanges.txt'. GetBasicRS1018ExpectedDiagnostic(17, 92, "MyThirdPrefix", "CategoryWithPrefixRangeAndId", "MyFirstPrefixXXXX, MySecondPrefix0-MySecondPrefix99, MySecondPrefix300-MySecondPrefix300", AdditionalFileName), }; VerifyBasic(source, GetAdditionalFile(additionalText), expected); } [Fact] public void RS1018_RS1020_CSharp_NoDiagnosticCases() { var source = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer : DiagnosticAnalyzer { private static LocalizableResourceString dummyLocalizableTitle = null; private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithNoIdRangeOrFormat"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor2_2 = new DiagnosticDescriptor(""Prefix101"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor3 = new DiagnosticDescriptor(""Prefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor4 = new DiagnosticDescriptor(""Prefix100"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor5 = new DiagnosticDescriptor(""MyFirstPrefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor6 = new DiagnosticDescriptor(""MySecondPrefix050"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor7 = new DiagnosticDescriptor(""MySecondPrefix300"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7); } } public override void Initialize(AnalysisContext context) { } } "; string additionalText = @" # FORMAT: # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' CategoryWithNoIdRangeOrFormat CategoryWithPrefix: Prefix CategoryWithRange: Prefix000-Prefix099 CategoryWithId: Prefix100 CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 "; VerifyCSharp(source, GetAdditionalFile(additionalText)); } [Fact] public void RS1018_RS1020_VisualBasic_NoDiagnosticCases() { var source = @" Imports System Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics <DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)> Class MyAnalyzer Inherits DiagnosticAnalyzer Private Shared dummyLocalizableTitle As LocalizableResourceString = Nothing Private Shared ReadOnly descriptor As DiagnosticDescriptor = New DiagnosticDescriptor(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithNoIdRangeOrFormat"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor2 As DiagnosticDescriptor = New DiagnosticDescriptor(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor2_2 As DiagnosticDescriptor = New DiagnosticDescriptor(""Prefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor3 As DiagnosticDescriptor = New DiagnosticDescriptor(""Prefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor4 As DiagnosticDescriptor = New DiagnosticDescriptor(""Prefix100"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor5 As DiagnosticDescriptor = New DiagnosticDescriptor(""MyFirstPrefix001"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor6 As DiagnosticDescriptor = New DiagnosticDescriptor(""MySecondPrefix050"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Private Shared ReadOnly descriptor7 As DiagnosticDescriptor = New DiagnosticDescriptor(""MySecondPrefix300"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault:=True, helpLinkUri:=""HelpLink"") Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(descriptor, descriptor2, descriptor2_2, descriptor3, descriptor4, descriptor5, descriptor6, descriptor7) End Get End Property Public Overrides Sub Initialize(ByVal context As AnalysisContext) End Sub End Class "; string additionalText = @" # FORMAT: # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' CategoryWithNoIdRangeOrFormat CategoryWithPrefix: Prefix CategoryWithRange: Prefix000-Prefix099 CategoryWithId: Prefix100 CategoryWithPrefixRangeAndId: MyFirstPrefix, MySecondPrefix000-MySecondPrefix099, MySecondPrefix300 "; VerifyBasic(source, GetAdditionalFile(additionalText)); } #endregion #region RS1021 (AnalyzerCategoryAndIdRangeFileInvalidRuleId) [Fact] public void RS1021_VerifyDiagnostic() { var source = @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] class MyAnalyzer : DiagnosticAnalyzer { private static LocalizableResourceString dummyLocalizableTitle = null; private static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor(""Id1"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""NotAllowedCategory"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor2 = new DiagnosticDescriptor(""DifferentPrefixId"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefix"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor3 = new DiagnosticDescriptor(""Prefix200"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithRange"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor4 = new DiagnosticDescriptor(""Prefix101"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor5 = new DiagnosticDescriptor(""MySecondPrefix400"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); private static readonly DiagnosticDescriptor descriptor6 = new DiagnosticDescriptor(""MyThirdPrefix"", dummyLocalizableTitle, ""MyDiagnosticMessage"", ""CategoryWithPrefixRangeAndId"", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: ""HelpLink""); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(descriptor, descriptor2, descriptor3, descriptor4, descriptor5, descriptor6); } } public override void Initialize(AnalysisContext context) { } } "; string additionalText = @" # FORMAT: # 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix' # Illegal: spaces in category name Category with spaces Category with spaces and range: Prefix100-Prefix199 # Illegal: Multiple colons CategoryMultipleColons: IdWithColon:100 # Illegal: Duplicate category DuplicateCategory1 DuplicateCategory1 DuplicateCategory2: Prefix100-Prefix199 DuplicateCategory2: Prefix200-Prefix299 # Illegal: ID cannot be non-alphanumeric CategoryWithBadId1: Prefix_100 CategoryWithBadId2: Prefix_100-Prefix_199 # Illegal: Id cannot have letters after number CategoryWithBadId3: Prefix000NotAllowed CategoryWithBadId4: Prefix000NotAllowed-Prefix099NotAllowed # Illegal: Different prefixes in ID range CategoryWithBadId5: Prefix000-DifferentPrefix099 "; DiagnosticResult[] expected = new[] { // DiagnosticCategoryAndIdRanges.txt(6,1): warning RS1021: Invalid entry 'Category with spaces' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(6, 1, "Category with spaces", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(7,1): warning RS1021: Invalid entry 'Category with spaces and range: Prefix100-Prefix199' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(7, 1, "Category with spaces and range: Prefix100-Prefix199", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(10,1): warning RS1021: Invalid entry 'CategoryMultipleColons: IdWithColon:100' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(10, 1, "CategoryMultipleColons: IdWithColon:100", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(14,1): warning RS1021: Invalid entry 'DuplicateCategory1' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(14, 1, "DuplicateCategory1", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(16,1): warning RS1021: Invalid entry 'DuplicateCategory2: Prefix200-Prefix299' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(16, 1, "DuplicateCategory2: Prefix200-Prefix299", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(19,1): warning RS1021: Invalid entry 'CategoryWithBadId1: Prefix_100' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(19, 1, "CategoryWithBadId1: Prefix_100", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(20,1): warning RS1021: Invalid entry 'CategoryWithBadId2: Prefix_100-Prefix_199' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(20, 1, "CategoryWithBadId2: Prefix_100-Prefix_199", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(23,1): warning RS1021: Invalid entry 'CategoryWithBadId3: Prefix000NotAllowed' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(23, 1, "CategoryWithBadId3: Prefix000NotAllowed", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(24,1): warning RS1021: Invalid entry 'CategoryWithBadId4: Prefix000NotAllowed-Prefix099NotAllowed' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(24, 1, "CategoryWithBadId4: Prefix000NotAllowed-Prefix099NotAllowed", AdditionalFileName), // DiagnosticCategoryAndIdRanges.txt(27,1): warning RS1021: Invalid entry 'CategoryWithBadId5: Prefix000-DifferentPrefix099' in analyzer category and diagnostic ID range specification file 'DiagnosticCategoryAndIdRanges.txt'. GetRS1021ExpectedDiagnostic(27, 1, "CategoryWithBadId5: Prefix000-DifferentPrefix099", AdditionalFileName), }; VerifyCSharp(source, GetAdditionalFile(additionalText), expected); } #endregion #region Helpers protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new DiagnosticDescriptorCreationAnalyzer(); } protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new DiagnosticDescriptorCreationAnalyzer(); } private static DiagnosticResult GetCSharpRS1015ExpectedDiagnostic(int line, int column) { return GetRS1015ExpectedDiagnostic(LanguageNames.CSharp, line, column); } private static DiagnosticResult GetBasicRS1015ExpectedDiagnostic(int line, int column) { return GetRS1015ExpectedDiagnostic(LanguageNames.VisualBasic, line, column); } private static DiagnosticResult GetCSharpRS1007ExpectedDiagnostic(int line, int column) { return GetRS1007ExpectedDiagnostic(LanguageNames.CSharp, line, column); } private static DiagnosticResult GetCSharpRS1017ExpectedDiagnostic(int line, int column, string descriptorName) { return GetRS1017ExpectedDiagnostic(LanguageNames.CSharp, line, column, descriptorName); } private static DiagnosticResult GetCSharpRS1018ExpectedDiagnostic(int line, int column, string diagnosticId, string category, string format, string additionalFile) { return GetRS1018ExpectedDiagnostic(LanguageNames.CSharp, line, column, diagnosticId, category, format, additionalFile); } private static DiagnosticResult GetCSharpRS1019ExpectedDiagnostic(int line, int column, string duplicateId, string otherAnalyzerName) { return GetRS1019ExpectedDiagnostic(LanguageNames.CSharp, line, column, duplicateId, otherAnalyzerName); } private static DiagnosticResult GetCSharpRS1020ExpectedDiagnostic(int line, int column, string category, string additionalFile) { return GetRS1020ExpectedDiagnostic(LanguageNames.CSharp, line, column, category, additionalFile); } private static DiagnosticResult GetBasicRS1007ExpectedDiagnostic(int line, int column) { return GetRS1007ExpectedDiagnostic(LanguageNames.VisualBasic, line, column); } private static DiagnosticResult GetBasicRS1017ExpectedDiagnostic(int line, int column, string descriptorName) { return GetRS1017ExpectedDiagnostic(LanguageNames.VisualBasic, line, column, descriptorName); } private static DiagnosticResult GetBasicRS1018ExpectedDiagnostic(int line, int column, string diagnosticId, string category, string format, string additionalFile) { return GetRS1018ExpectedDiagnostic(LanguageNames.VisualBasic, line, column, diagnosticId, category, format, additionalFile); } private static DiagnosticResult GetBasicRS1019ExpectedDiagnostic(int line, int column, string duplicateId, string otherAnalyzerName) { return GetRS1019ExpectedDiagnostic(LanguageNames.VisualBasic, line, column, duplicateId, otherAnalyzerName); } private static DiagnosticResult GetBasicRS1020ExpectedDiagnostic(int line, int column, string category, string additionalFile) { return GetRS1020ExpectedDiagnostic(LanguageNames.VisualBasic, line, column, category, additionalFile); } private static DiagnosticResult GetRS1007ExpectedDiagnostic(string language, int line, int column) { string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb"; return new DiagnosticResult(DiagnosticIds.UseLocalizableStringsInDescriptorRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity) .WithLocation(fileName, line, column) .WithMessageFormat(CodeAnalysisDiagnosticsResources.UseLocalizableStringsInDescriptorMessage) .WithArguments(DiagnosticAnalyzerCorrectnessAnalyzer.LocalizableStringFullName); } private static DiagnosticResult GetRS1015ExpectedDiagnostic(string language, int line, int column) { string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb"; return new DiagnosticResult(DiagnosticIds.ProvideHelpUriInDescriptorRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity) .WithLocation(fileName, line, column) .WithMessageFormat(CodeAnalysisDiagnosticsResources.ProvideHelpUriInDescriptorMessage); } private static DiagnosticResult GetRS1017ExpectedDiagnostic(string language, int line, int column, string descriptorName) { string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb"; return new DiagnosticResult(DiagnosticIds.DiagnosticIdMustBeAConstantRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity) .WithLocation(fileName, line, column) .WithMessageFormat(CodeAnalysisDiagnosticsResources.DiagnosticIdMustBeAConstantMessage) .WithArguments(descriptorName); } private static DiagnosticResult GetRS1018ExpectedDiagnostic(string language, int line, int column, string diagnosticId, string category, string format, string additionalFile) { string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb"; return new DiagnosticResult(DiagnosticIds.DiagnosticIdMustBeInSpecifiedFormatRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity) .WithLocation(fileName, line, column) .WithMessageFormat(CodeAnalysisDiagnosticsResources.DiagnosticIdMustBeInSpecifiedFormatMessage) .WithArguments(diagnosticId, category, format, additionalFile); } private static DiagnosticResult GetRS1019ExpectedDiagnostic(string language, int line, int column, string duplicateId, string otherAnalyzerName) { string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb"; return new DiagnosticResult(DiagnosticIds.UseUniqueDiagnosticIdRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity) .WithLocation(fileName, line, column) .WithMessageFormat(CodeAnalysisDiagnosticsResources.UseUniqueDiagnosticIdMessage) .WithArguments(duplicateId, otherAnalyzerName); } private static DiagnosticResult GetRS1020ExpectedDiagnostic(string language, int line, int column, string category, string additionalFile) { string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb"; return new DiagnosticResult(DiagnosticIds.UseCategoriesFromSpecifiedRangeRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity) .WithLocation(fileName, line, column) .WithMessageFormat(CodeAnalysisDiagnosticsResources.UseCategoriesFromSpecifiedRangeMessage) .WithArguments(category, additionalFile); } private static DiagnosticResult GetRS1021ExpectedDiagnostic(int line, int column, string invalidEntry, string additionalFile) { return new DiagnosticResult(DiagnosticIds.AnalyzerCategoryAndIdRangeFileInvalidRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity) .WithLocation(AdditionalFileName, line, column) .WithMessageFormat(CodeAnalysisDiagnosticsResources.AnalyzerCategoryAndIdRangeFileInvalidMessage) .WithArguments(invalidEntry, additionalFile); } private const string AdditionalFileName = "DiagnosticCategoryAndIdRanges.txt"; private FileAndSource GetAdditionalFile(string source) => new FileAndSource() { Source = source, FilePath = AdditionalFileName }; #endregion } }
56.059471
331
0.75718
[ "Apache-2.0" ]
LingxiaChen/roslyn-analyzers
src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzerTests.cs
50,904
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Online.API; using osu.Game.Overlays.Settings; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osu.Game.Users; using osuTK; namespace osu.Game.Tournament.Screens.Editors { public class TeamEditorScreen : TournamentEditorScreen<TeamEditorScreen.TeamRow, TournamentTeam> { [Resolved] private TournamentGameBase game { get; set; } protected override BindableList<TournamentTeam> Storage => LadderInfo.Teams; [BackgroundDependencyLoader] private void load() { ControlPanel.Add(new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Add all countries", Action = addAllCountries }); } protected override TeamRow CreateDrawable(TournamentTeam model) => new TeamRow(model); private void addAllCountries() { List<TournamentTeam> countries; using (Stream stream = game.Resources.GetStream("Resources/countries.json")) using (var sr = new StreamReader(stream)) countries = JsonConvert.DeserializeObject<List<TournamentTeam>>(sr.ReadToEnd()); foreach (var c in countries) Storage.Add(c); } public class TeamRow : CompositeDrawable, IModelBacked<TournamentTeam> { public TournamentTeam Model { get; } private readonly Container drawableContainer; [Resolved] private LadderInfo ladderInfo { get; set; } public TeamRow(TournamentTeam team) { Model = team; Masking = true; CornerRadius = 10; PlayerEditor playerEditor = new PlayerEditor(Model) { Width = 0.95f }; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.1f), RelativeSizeAxes = Axes.Both, }, drawableContainer = new Container { Size = new Vector2(100, 50), Margin = new MarginPadding(10), Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, new FillFlowContainer { Margin = new MarginPadding(5), Spacing = new Vector2(5), Direction = FillDirection.Full, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new SettingsTextBox { LabelText = "Name", Width = 0.2f, Bindable = Model.FullName }, new SettingsTextBox { LabelText = "Acronym", Width = 0.2f, Bindable = Model.Acronym }, new SettingsTextBox { LabelText = "Flag", Width = 0.2f, Bindable = Model.FlagName }, new SettingsButton { Width = 0.11f, Margin = new MarginPadding(10), Text = "Add player", Action = () => playerEditor.CreateNew() }, new DangerousSettingsButton { Width = 0.11f, Text = "Delete Team", Margin = new MarginPadding(10), Action = () => { Expire(); ladderInfo.Teams.Remove(Model); }, }, playerEditor } }, }; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Model.FlagName.BindValueChanged(updateDrawable, true); } private void updateDrawable(ValueChangedEvent<string> flag) { drawableContainer.Child = new DrawableTeamFlag(Model); } private class DrawableTeamFlag : DrawableTournamentTeam { public DrawableTeamFlag(TournamentTeam team) : base(team) { InternalChild = Flag; RelativeSizeAxes = Axes.Both; Flag.Anchor = Anchor.Centre; Flag.Origin = Anchor.Centre; } } public class PlayerEditor : CompositeDrawable { private readonly TournamentTeam team; private readonly FillFlowContainer flow; public PlayerEditor(TournamentTeam team) { this.team = team; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = flow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, LayoutDuration = 200, LayoutEasing = Easing.OutQuint, ChildrenEnumerable = team.Players.Select(p => new PlayerRow(team, p)) }; } public void CreateNew() { var user = new User(); team.Players.Add(user); flow.Add(new PlayerRow(team, user)); } public class PlayerRow : CompositeDrawable { private readonly User user; [Resolved] protected IAPIProvider API { get; private set; } [Resolved] private TournamentGameBase game { get; set; } private readonly Bindable<string> userId = new Bindable<string>(); private readonly Container drawableContainer; public PlayerRow(TournamentTeam team, User user) { this.user = user; Margin = new MarginPadding(10); RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Masking = true; CornerRadius = 5; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.2f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new SettingsNumberBox { LabelText = "User ID", RelativeSizeAxes = Axes.None, Width = 200, Bindable = userId, }, drawableContainer = new Container { Size = new Vector2(100, 70), }, } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete Player", Action = () => { Expire(); team.Players.Remove(user); }, } }; } [BackgroundDependencyLoader] private void load() { userId.Value = user.Id.ToString(); userId.BindValueChanged(idString => { long.TryParse(idString.NewValue, out var parsed); user.Id = parsed; if (idString.NewValue != idString.OldValue) user.Username = string.Empty; if (!string.IsNullOrEmpty(user.Username)) { updatePanel(); return; } game.PopulateUser(user, updatePanel, updatePanel); }, true); } private void updatePanel() { drawableContainer.Child = new UserPanel(user) { Width = 300 }; } } } } } }
38.064189
101
0.381823
[ "MIT" ]
Altenhh/osu
osu.Game.Tournament/Screens/Editors/TeamEditorScreen.cs
10,972
C#
namespace StoryTeller.Util { public class TableRowTag : HtmlTag { public TableRowTag() : base("tr") { } public HtmlTag Header(string text) => new HtmlTag("th", this).Text(text); public HtmlTag Header() => new HtmlTag("th", this); public HtmlTag Cell(string text) => new HtmlTag("td", this).Text(text); public HtmlTag Cell() => new HtmlTag("td", this); } }
24.388889
81
0.56492
[ "Apache-2.0" ]
SergeiGolos/Storyteller
src/StoryTeller/Util/TableRowTag.cs
439
C#
using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Core.DomainModel; using Core.DomainModel.Organization; using Presentation.Web.Models.API.V1; using Tests.Integration.Presentation.Web.Tools; using Tests.Toolkit.Patterns; using Xunit; namespace Tests.Integration.Presentation.Web.ItSystem { public class ItSystemHierarchy : WithAutoFixture { [Theory] [InlineData(OrganizationRole.GlobalAdmin)] [InlineData(OrganizationRole.User)] public async Task Api_User_Can_Get_It_System_Hierarchy_Information(OrganizationRole role) { var token = await HttpApi.GetTokenAsync(role); var url = TestEnvironment.CreateUrl($"api/itsystem/{TestEnvironment.DefaultItSystemId}?hierarchy=true"); //Act using (var httpResponse = await HttpApi.GetWithTokenAsync(url, token.Token)) { var response = await httpResponse.ReadResponseBodyAsKitosApiResponseAsync<IEnumerable<ItSystemDTO>>(); //Assert Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); Assert.NotEmpty(response); } } [Theory] [InlineData(OrganizationRole.GlobalAdmin)] public async Task Api_User_Can_Get_It_System_ParentId(OrganizationRole role) { //Arrange var login = await HttpApi.GetCookieAsync(role); const int organizationId = TestEnvironment.DefaultOrganizationId; var mainSystem = await ItSystemHelper.CreateItSystemInOrganizationAsync(A<string>(), organizationId, AccessModifier.Public); var childSystem = await ItSystemHelper.CreateItSystemInOrganizationAsync(A<string>(), organizationId, AccessModifier.Public); await ItSystemHelper.SendSetParentSystemRequestAsync(childSystem.Id, mainSystem.Id, organizationId, login).DisposeAsync(); var token = await HttpApi.GetTokenAsync(role); var url = TestEnvironment.CreateUrl($"api/itsystem/{childSystem.Id}?hierarchy=true"); //Act using (var httpResponse = await HttpApi.GetWithTokenAsync(url, token.Token)) { //Assert var response = await httpResponse.ReadResponseBodyAsKitosApiResponseAsync<IEnumerable<ItSystemDTO>>(); Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); var itSystemDtos = response.ToList(); Assert.NotEmpty(itSystemDtos); Assert.Equal(mainSystem.Id, itSystemDtos.First(x => x.Id == childSystem.Id).ParentId); } } } }
42.555556
137
0.675494
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Strongminds/kitos
Tests.Integration.Presentation.Web/ItSystem/ItSystemHierarchy.cs
2,683
C#
using System; using System.Linq; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using System.IO; using Microsoft.DotNet; namespace VisualStudio { sealed class CommandFactory { readonly Config config; Dictionary<string, (bool IsSystem, Func<CommandDescriptor> CreateDescriptor, Func<CommandDescriptor, Command> CreateCommand)> factories = new Dictionary<string, (bool IsSystem, Func<CommandDescriptor> CreateDescriptor, Func<CommandDescriptor, Command> CreateCommand)>(); public CommandFactory() : this(Commands.DotNetConfig.GetConfig()) { } public CommandFactory(Config config) { this.config = config; var whereService = new WhereService(); var installerService = new InstallerService(); RegisterCommand<RunCommandDescriptor>(Commands.Run, x => new RunCommand(x, whereService)); RegisterCommand(Commands.Where, () => new WhereCommandDescriptor(whereService), x => new WhereCommand(x, whereService)); RegisterCommand<InstallCommandDescriptor>(Commands.Install, x => new InstallCommand(x, installerService)); RegisterCommand<UpdateCommandDescriptor>(Commands.Update, x => new UpdateCommand(x, whereService, installerService)); RegisterCommand<ModifyCommandDescriptor>(Commands.Modify, x => new ModifyCommand(x, whereService, installerService)); RegisterCommand<KillCommandDescriptor>(Commands.Kill, x => new KillCommand(x, whereService)); RegisterCommand<ConfigCommandDescriptor>(Commands.Config, x => new ConfigCommand(x, whereService)); RegisterCommand<LogCommandDescriptor>(Commands.Log, x => new LogCommand(x, whereService)); RegisterCommand<AliasCommandDescriptor>(Commands.Alias, x => new AliasCommand(x)); RegisterCommand<ClientCommandDescriptor>(Commands.Client, x => new ClientCommand(x, whereService)); // System commands RegisterCommand( Commands.System.GenerateReadme, () => new GenerateReadmeCommandDescriptor(factories.Where(x => !x.Value.IsSystem).ToDictionary(x => x.Key, x => x.Value.CreateDescriptor())), x => new GenerateReadmeCommand(x), isSystem: true); RegisterCommand<SaveCommandDescriptor>(Commands.System.Save, x => new SaveCommand(x), isSystem: true); RegisterCommand<UpdateSelfCommandDescriptor>(Commands.System.UpdateSelf, x => new UpdateSelfCommand(x), isSystem: true); } public Dictionary<string, CommandDescriptor> GetRegisteredCommands(bool includeSystemCommands = false) => factories.Where(x => includeSystemCommands || !x.Value.IsSystem).ToDictionary(x => x.Key, x => x.Value.CreateDescriptor()); public void RegisterCommand<TDescriptor>(string command, Func<TDescriptor, Command> commandFactory, bool isSystem = false) where TDescriptor : CommandDescriptor, new() => RegisterCommand(command, () => new TDescriptor(), commandFactory, isSystem); public void RegisterCommand<TDescriptor>(string command, Func<TDescriptor> descriptorFactory, Func<TDescriptor, Command> commandFactory, bool isSystem = false) where TDescriptor : CommandDescriptor => factories.Add(command, (isSystem, descriptorFactory, x => commandFactory((TDescriptor)x))); public Task<Command> CreateCommandAsync(string command, ImmutableArray<string> args) { // Check if we should save the command if (SaveOption.IsDefined(args) && factories.ContainsKey(Commands.System.Save)) { args = ImmutableArray.Create(args.Prepend(command).ToArray()); command = Commands.System.Save; } // Or update self else if (command == Commands.Update && SelfOption.IsDefined(args) && factories.ContainsKey(Commands.System.UpdateSelf)) { command = Commands.System.UpdateSelf; } // Try to get the command factory if (!factories.TryGetValue(command, out var factory)) { // Or check if exists a saved command var savedCommand = config.GetString(Commands.DotNetConfig.Section, Commands.DotNetConfig.SubSection, command); if (!string.IsNullOrEmpty(savedCommand)) { // Initially the args contains the command name and the args var savedCommandArgs = savedCommand.Split('|', StringSplitOptions.RemoveEmptyEntries); // It's a saved command => the first argument should be the command name var savedCommandName = savedCommandArgs.FirstOrDefault(); if (!string.IsNullOrEmpty(savedCommandName)) { if (factories.TryGetValue(savedCommandName, out factory)) { // Restore the saved args args = ImmutableArray.Create(savedCommandArgs.Skip(1).ToArray()); command = savedCommandName; } // If the factory is still null, use the Run command as the default else if (factories.TryGetValue(Commands.Run, out factory)) { args = ImmutableArray.Create(savedCommandArgs.ToArray()); command = Commands.Run; } } } } // If the factory is still null, use the Run command as the default if (factory == default && factories.TryGetValue(Commands.Run, out factory)) { // Run is the default command if another one is not specified. args = ImmutableArray.Create(args.Prepend(command).ToArray()); command = Commands.Run; } if (factory == default) throw new InvalidOperationException($"The command '{command}' is not registered"); // Create the descriptor var commandDescriptor = factory.CreateDescriptor(); // Parse the arguments commandDescriptor.Parse(args); // And create the command return Task.FromResult(factory.CreateCommand(commandDescriptor)); } } }
51.480315
208
0.623432
[ "MIT" ]
augustoproiete-forks/devlooped--dotnet-vs
VisualStudio/CommandFactory.cs
6,540
C#
//Build Date: July 22, 2014 #region "Header" #if (UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_ANDROID || UNITY_IOS) #define USE_JSONFX_UNITY_IOS #endif #if (__MonoCS__ && !UNITY_STANDALONE && !UNITY_WEBPLAYER) #define TRACE #endif using System; using System.IO; using System.Text; using System.Net; using System.Collections; using System.Collections.Generic; #if !NETFX_CORE using System.Security.Cryptography; #endif using System.ComponentModel; using System.Reflection; using System.Threading; using System.Diagnostics; #if WINDOWS_PHONE && WP7 using System.Collections.Concurrent; #elif WINDOWS_PHONE using TvdP.Collections; #else using System.Collections.Concurrent; #endif using System.Globalization; using System.Linq; using System.Text.RegularExpressions; #if USE_JSONFX || USE_JSONFX_UNITY using JsonFx.Json; #elif (USE_DOTNET_SERIALIZATION) using System.Runtime.Serialization.Json; using System.Web.Script.Serialization; #elif (USE_MiniJSON) using MiniJSON; #elif (USE_JSONFX_UNITY_IOS) using Pathfinding.Serialization.JsonFx; #else using Newtonsoft.Json; using Newtonsoft.Json.Linq; #endif #endregion namespace PubNubMessaging.Core { // INotifyPropertyChanged provides a standard event for objects to notify clients that one of its properties has changed internal abstract class PubnubCore : INotifyPropertyChanged { #region "Events" // Common property changed event public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion #region "Class variables" int _pubnubWebRequestCallbackIntervalInSeconds = 310; int _pubnubOperationTimeoutIntervalInSeconds = 15; int _pubnubNetworkTcpCheckIntervalInSeconds = 15; int _pubnubNetworkCheckRetries = 50; int _pubnubWebRequestRetryIntervalInSeconds = 10; int _pubnubPresenceHeartbeatInSeconds = 0; int _presenceHeartbeatIntervalInSeconds = 0; bool _enableResumeOnReconnect = true; bool _uuidChanged = false; protected bool overrideTcpKeepAlive = true; bool _enableJsonEncodingForPublish = true; LoggingMethod.Level _pubnubLogLevel = LoggingMethod.Level.Off; PubnubErrorFilter.Level _errorLevel = PubnubErrorFilter.Level.Info; protected ConcurrentDictionary<string, long> multiChannelSubscribe = new ConcurrentDictionary<string, long>(); ConcurrentDictionary<string, PubnubWebRequest> _channelRequest = new ConcurrentDictionary<string, PubnubWebRequest>(); protected ConcurrentDictionary<string, bool> channelInternetStatus = new ConcurrentDictionary<string, bool>(); protected ConcurrentDictionary<string, int> channelInternetRetry = new ConcurrentDictionary<string, int>(); ConcurrentDictionary<string, Timer> _channelReconnectTimer = new ConcurrentDictionary<string, Timer>(); protected ConcurrentDictionary<Uri, Timer> channelLocalClientHeartbeatTimer = new ConcurrentDictionary<Uri, Timer>(); protected ConcurrentDictionary<PubnubChannelCallbackKey, object> channelCallbacks = new ConcurrentDictionary<PubnubChannelCallbackKey, object>(); ConcurrentDictionary<string, Dictionary<string, object>> _channelLocalUserState = new ConcurrentDictionary<string, Dictionary<string, object>>(); ConcurrentDictionary<string, Dictionary<string, object>> _channelUserState = new ConcurrentDictionary<string, Dictionary<string, object>>(); ConcurrentDictionary<string, List<string>> _channelSubscribedAuthKeys = new ConcurrentDictionary<string, List<string>>(); protected System.Threading.Timer localClientHeartBeatTimer; protected System.Threading.Timer presenceHeartbeatTimer = null; protected static bool pubnetSystemActive = true; // History of Messages (Obsolete) private List<object> _history = new List<object>(); public List<object> History { get { return _history; } set { _history = value; RaisePropertyChanged("History"); } } private static long lastSubscribeTimetoken = 0; // Pubnub Core API implementation private string _origin = "pubsub.pubnub.com"; protected string publishKey = ""; protected string subscribeKey = ""; protected string secretKey = ""; protected string cipherKey = ""; protected bool ssl = false; protected string parameters = ""; private string subscribeParameters = ""; private string presenceHeartbeatParameters = ""; private string hereNowParameters = ""; private string setUserStateparameters = ""; private string globalHereNowParameters = ""; #endregion #region "Properties" internal int SubscribeTimeout { get { return _pubnubWebRequestCallbackIntervalInSeconds; } set { _pubnubWebRequestCallbackIntervalInSeconds = value; } } internal int NonSubscribeTimeout { get { return _pubnubOperationTimeoutIntervalInSeconds; } set { _pubnubOperationTimeoutIntervalInSeconds = value; } } internal int NetworkCheckMaxRetries { get { return _pubnubNetworkCheckRetries; } set { _pubnubNetworkCheckRetries = value; } } internal int NetworkCheckRetryInterval { get { return _pubnubWebRequestRetryIntervalInSeconds; } set { _pubnubWebRequestRetryIntervalInSeconds = value; } } internal int LocalClientHeartbeatInterval { get { return _pubnubNetworkTcpCheckIntervalInSeconds; } set { _pubnubNetworkTcpCheckIntervalInSeconds = value; } } internal bool EnableResumeOnReconnect { get { return _enableResumeOnReconnect; } set { _enableResumeOnReconnect = value; } } public bool EnableJsonEncodingForPublish { get { return _enableJsonEncodingForPublish; } set { _enableJsonEncodingForPublish = value; } } private string _authenticationKey = ""; public string AuthenticationKey { get { return _authenticationKey; } set { _authenticationKey = value; } } private IPubnubUnitTest _pubnubUnitTest; public virtual IPubnubUnitTest PubnubUnitTest { get { return _pubnubUnitTest; } set { _pubnubUnitTest = value; } } private IJsonPluggableLibrary _jsonPluggableLibrary = null; public IJsonPluggableLibrary JsonPluggableLibrary { get { return _jsonPluggableLibrary; } set { _jsonPluggableLibrary = value; if (_jsonPluggableLibrary is IJsonPluggableLibrary) { ClientNetworkStatus.JsonPluggableLibrary = _jsonPluggableLibrary; } else { _jsonPluggableLibrary = null; throw new ArgumentException("Missing or Incorrect JsonPluggableLibrary value"); } } } public string Origin { get { return _origin; } set { _origin = value; } } private string sessionUUID = ""; public string SessionUUID { get { return sessionUUID; } set { sessionUUID = value; } } /// <summary> /// This property sets presence expiry timeout. /// Presence expiry value in seconds. /// </summary> internal int PresenceHeartbeat { get { return _pubnubPresenceHeartbeatInSeconds; } set { if (value <= 0 || value > 320) { _pubnubPresenceHeartbeatInSeconds = 0; } else { _pubnubPresenceHeartbeatInSeconds = value; } if (_pubnubPresenceHeartbeatInSeconds != 0) { _presenceHeartbeatIntervalInSeconds = (_pubnubPresenceHeartbeatInSeconds / 2) - 1; } } } internal int PresenceHeartbeatInterval { get { return _presenceHeartbeatIntervalInSeconds; } set { _presenceHeartbeatIntervalInSeconds = value; if (_presenceHeartbeatIntervalInSeconds >= _pubnubPresenceHeartbeatInSeconds) { _presenceHeartbeatIntervalInSeconds = (_pubnubPresenceHeartbeatInSeconds / 2) - 1; } } } protected LoggingMethod.Level PubnubLogLevel { get { return _pubnubLogLevel; } set { _pubnubLogLevel = value; LoggingMethod.LogLevel = _pubnubLogLevel; } } protected PubnubErrorFilter.Level PubnubErrorLevel { get { return _errorLevel; } set { _errorLevel = value; PubnubErrorFilter.ErrorLevel = _errorLevel; } } #endregion #region "Init" /** * Pubnub instance initialization function * * @param string publishKey. * @param string subscribeKey. * @param string secretKey. * @param bool sslOn */ protected virtual void Init(string publishKey, string subscribeKey, string secretKey, string cipherKey, bool sslOn) { #if (USE_JSONFX) || (USE_JSONFX_UNITY) LoggingMethod.WriteToLog ("USE_JSONFX", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new JsonFXDotNet(); #elif (USE_DOTNET_SERIALIZATION) LoggingMethod.WriteToLog("USE_DOTNET_SERIALIZATION", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new JscriptSerializer(); #elif (USE_MiniJSON) LoggingMethod.WriteToLog("USE_MiniJSON", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new MiniJSONObjectSerializer(); #elif (USE_JSONFX_UNITY_IOS) LoggingMethod.WriteToLog("USE_JSONFX_UNITY_IOS", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new JsonFxUnitySerializer(); #else LoggingMethod.WriteToLog("NewtonsoftJsonDotNet", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new NewtonsoftJsonDotNet(); #endif LoggingMethod.LogLevel = _pubnubLogLevel; PubnubErrorFilter.ErrorLevel = _errorLevel; this.publishKey = publishKey; this.subscribeKey = subscribeKey; this.secretKey = secretKey; this.cipherKey = cipherKey; this.ssl = sslOn; VerifyOrSetSessionUUID(); } #endregion #region "Internet connection and Reconnect Network" protected virtual void ReconnectFromSuspendMode(object netState) { if (netState == null) return; ReconnectFromSuspendModeCallback<string>(netState); } protected virtual void ReconnectNetwork<T>(ReconnectState<T> netState) { System.Threading.Timer timer = new Timer(new TimerCallback(ReconnectNetworkCallback<T>), netState, 0, (-1 == _pubnubNetworkTcpCheckIntervalInSeconds) ? Timeout.Infinite : _pubnubNetworkTcpCheckIntervalInSeconds * 1000); if (netState != null && netState.Channels != null) { _channelReconnectTimer.AddOrUpdate(string.Join(",", netState.Channels), timer, (key, oldState) => timer); } } protected virtual void ReconnectNetworkCallback<T>(System.Object reconnectState) { string channel = ""; ReconnectState<T> netState = reconnectState as ReconnectState<T>; try { if (netState != null && netState.Channels != null) { channel = string.Join(",", netState.Channels); if (channelInternetStatus.ContainsKey(channel) && (netState.Type == ResponseType.Subscribe || netState.Type == ResponseType.Presence)) { if (channelInternetStatus[channel]) { //Reset Retry if previous state is true channelInternetRetry.AddOrUpdate(channel, 0, (key, oldValue) => 0); } else { channelInternetRetry.AddOrUpdate(channel, 1, (key, oldValue) => oldValue + 1); LoggingMethod.WriteToLog(string.Format("DateTime {0}, {1} {2} reconnectNetworkCallback. Retry {3} of {4}", DateTime.Now.ToString(), channel, netState.Type, channelInternetRetry[channel], _pubnubNetworkCheckRetries), LoggingMethod.LevelInfo); if (netState.Channels != null) { for (int index = 0; index < netState.Channels.Length; index++) { string activeChannel = netState.Channels[index].ToString(); string message = string.Format("Detected internet connection problem. Retrying connection attempt {0} of {1}", channelInternetRetry[channel], _pubnubNetworkCheckRetries); PubnubChannelCallbackKey callbackKey = new PubnubChannelCallbackKey(); callbackKey.Channel = activeChannel; callbackKey.Type = netState.Type; if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey(callbackKey)) { PubnubChannelCallback<T> currentPubnubCallback = channelCallbacks[callbackKey] as PubnubChannelCallback<T>; if (currentPubnubCallback != null && currentPubnubCallback.ErrorCallback != null) { CallErrorCallback (PubnubErrorSeverity.Warn, PubnubMessageSource.Client, activeChannel, currentPubnubCallback.ErrorCallback, message, PubnubErrorCode.NoInternet, null, null); } } } } } } if (channelInternetStatus[channel]) { if (_channelReconnectTimer.ContainsKey(channel)) { _channelReconnectTimer[channel].Change(Timeout.Infinite, Timeout.Infinite); _channelReconnectTimer[channel].Dispose(); } string multiChannel = (netState.Channels != null) ? string.Join(",", netState.Channels) : ""; string message = "Internet connection available"; CallErrorCallback (PubnubErrorSeverity.Warn, PubnubMessageSource.Client, multiChannel, netState.ErrorCallback, message, PubnubErrorCode.YesInternet, null, null); LoggingMethod.WriteToLog(string.Format("DateTime {0}, {1} {2} reconnectNetworkCallback. Internet Available : {3}", DateTime.Now.ToString(), channel, netState.Type, channelInternetStatus[channel]), LoggingMethod.LevelInfo); switch (netState.Type) { case ResponseType.Subscribe: case ResponseType.Presence: MultiChannelSubscribeRequest<T>(netState.Type, netState.Channels, netState.Timetoken, netState.Callback, netState.ConnectCallback, netState.ErrorCallback, true); break; default: break; } } else if (channelInternetRetry[channel] >= _pubnubNetworkCheckRetries) { if (_channelReconnectTimer.ContainsKey(channel)) { _channelReconnectTimer[channel].Change(Timeout.Infinite, Timeout.Infinite); _channelReconnectTimer[channel].Dispose(); } switch (netState.Type) { case ResponseType.Subscribe: case ResponseType.Presence: MultiplexExceptionHandler(netState.Type, netState.Channels, netState.Callback, netState.ConnectCallback, netState.ErrorCallback, true, false); break; default: break; } } } else { LoggingMethod.WriteToLog(string.Format("DateTime {0}, Unknown request state in reconnectNetworkCallback", DateTime.Now.ToString()), LoggingMethod.LevelError); } } catch (Exception ex) { if (netState != null) { string multiChannel = (netState.Channels != null) ? string.Join(",", netState.Channels) : ""; CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, multiChannel, netState.ErrorCallback, ex, null, null); } LoggingMethod.WriteToLog(string.Format("DateTime {0} method:reconnectNetworkCallback \n Exception Details={1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelError); } } private bool InternetConnectionStatusWithUnitTestCheck<T>(string channel, Action<PubnubClientError> errorCallback, string[] rawChannels) { bool networkConnection; if (_pubnubUnitTest is IPubnubUnitTest && _pubnubUnitTest.EnableStubTest) { networkConnection = true; } else { networkConnection = InternetConnectionStatus<T>(channel, errorCallback, rawChannels); if (!networkConnection) { string message = "Network connnect error - Internet connection is not available."; CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, channel, errorCallback, message, PubnubErrorCode.NoInternet, null, null); } } return networkConnection; } protected virtual bool InternetConnectionStatus<T>(string channel, Action<PubnubClientError> errorCallback, string[] rawChannels) { bool networkConnection; networkConnection = ClientNetworkStatus.CheckInternetStatus<T>(pubnetSystemActive, errorCallback, rawChannels); return networkConnection; } private void ResetInternetCheckSettings(string[] channels) { if (channels == null) return; string multiChannel = string.Join(",", channels); if (channelInternetStatus.ContainsKey(multiChannel)) { channelInternetStatus.AddOrUpdate(multiChannel, true, (key, oldValue) => true); } else { channelInternetStatus.GetOrAdd(multiChannel, true); //Set to true for internet connection } if (channelInternetRetry.ContainsKey(multiChannel)) { channelInternetRetry.AddOrUpdate(multiChannel, 0, (key, oldValue) => 0); } else { channelInternetRetry.GetOrAdd(multiChannel, 0); //Initialize the internet retry count } } protected virtual bool ReconnectNetworkIfOverrideTcpKeepAlive<T>(ResponseType type, string[] channels, object timetoken, Action<T> userCallback, Action<T> connectCallback, Action<PubnubClientError> errorCallback, string multiChannel) { if (overrideTcpKeepAlive) { LoggingMethod.WriteToLog(string.Format ("DateTime {0}, Subscribe - No internet connection for {1}", DateTime.Now.ToString(), multiChannel), LoggingMethod.LevelInfo); ReconnectState<T> netState = new ReconnectState<T>(); netState.Channels = channels; netState.Type = type; netState.Callback = userCallback; netState.ErrorCallback = errorCallback; netState.ConnectCallback = connectCallback; netState.Timetoken = timetoken; ReconnectNetwork<T>(netState); return true; } else { return false; } } protected virtual void ReconnectFromSuspendModeCallback<T>(System.Object reconnectState) { string channel = ""; if (PubnubWebRequest.MachineSuspendMode && ClientNetworkStatus.MachineSuspendMode) { return; } LoggingMethod.WriteToLog(string.Format("DateTime {0}, Reconnect from Machine Suspend Mode.", DateTime.Now.ToString()), LoggingMethod.LevelInfo); ReconnectState<T> netState = reconnectState as ReconnectState<T>; try { if (netState != null && netState.Channels != null) { channel = string.Join(",", netState.Channels); switch (netState.Type) { case ResponseType.Subscribe: case ResponseType.Presence: MultiChannelSubscribeRequest<T>(netState.Type, netState.Channels, netState.Timetoken, netState.Callback, netState.ConnectCallback, netState.ErrorCallback, netState.Reconnect); break; default: break; } } else { LoggingMethod.WriteToLog(string.Format("DateTime {0}, Unknown request state in ReconnectFromSuspendModeCallback", DateTime.Now.ToString()), LoggingMethod.LevelError); } } catch (Exception ex) { if (netState != null) { string multiChannel = (netState.Channels != null) ? string.Join(",", netState.Channels) : ""; CallErrorCallback(PubnubErrorSeverity.Critical, PubnubMessageSource.Client, multiChannel, netState.ErrorCallback, ex, null, null); } LoggingMethod.WriteToLog(string.Format("DateTime {0} method:ReconnectFromSuspendModeCallback \n Exception Details={1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelError); } } #endregion #region "Error Callbacks" protected PubnubClientError CallErrorCallback (PubnubErrorSeverity errSeverity, PubnubMessageSource msgSource, string channel, Action<PubnubClientError> errorCallback, string message, PubnubErrorCode errorType, PubnubWebRequest req, PubnubWebResponse res) { int statusCode = (int)errorType; string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (errorType); PubnubClientError error = new PubnubClientError (statusCode, errSeverity, message, msgSource, req, res, errorDescription, channel); GoToCallback (error, errorCallback); return error; } protected PubnubClientError CallErrorCallback (PubnubErrorSeverity errSeverity, PubnubMessageSource msgSource, string channel, Action<PubnubClientError> errorCallback, string message, int currentHttpStatusCode, string statusMessage, PubnubWebRequest req, PubnubWebResponse res) { PubnubErrorCode pubnubErrorType = PubnubErrorCodeHelper.GetErrorType ((int)currentHttpStatusCode, statusMessage); int statusCode = (int)pubnubErrorType; string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (pubnubErrorType); PubnubClientError error = new PubnubClientError (statusCode, errSeverity, message, msgSource, req, res, errorDescription, channel); GoToCallback (error, errorCallback); return error; } protected PubnubClientError CallErrorCallback (PubnubErrorSeverity errSeverity, PubnubMessageSource msgSource, string channel, Action<PubnubClientError> errorCallback, Exception ex, PubnubWebRequest req, PubnubWebResponse res) { PubnubErrorCode errorType = PubnubErrorCodeHelper.GetErrorType (ex); int statusCode = (int)errorType; string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (errorType); PubnubClientError error = new PubnubClientError (statusCode, errSeverity, true, ex.Message, ex, msgSource, req, res, errorDescription, channel); GoToCallback (error, errorCallback); return error; } protected PubnubClientError CallErrorCallback (PubnubErrorSeverity errSeverity, PubnubMessageSource msgSource, string channel, Action<PubnubClientError> errorCallback, WebException webex, PubnubWebRequest req, PubnubWebResponse res) { PubnubErrorCode errorType = PubnubErrorCodeHelper.GetErrorType (webex.Status, webex.Message); int statusCode = (int)errorType; string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (errorType); PubnubClientError error = new PubnubClientError (statusCode, errSeverity, true, webex.Message, webex, msgSource, req, res, errorDescription, channel); GoToCallback (error, errorCallback); return error; } #endregion #region "Terminate requests and Timers" protected void TerminatePendingWebRequest () { TerminatePendingWebRequest<object> (null); } protected void TerminatePendingWebRequest<T> (RequestState<T> state) { if (state != null && state.Request != null) { if (state.Channels != null && state.Channels.Length > 0) { string activeChannel = state.Channels [0].ToString (); //Assuming one channel exist, else will refactor later PubnubChannelCallbackKey callbackKey = new PubnubChannelCallbackKey (); callbackKey.Channel = (state.Type == ResponseType.Subscribe) ? activeChannel.Replace ("-pnpres", "") : activeChannel; callbackKey.Type = state.Type; if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey (callbackKey)) { object callbackObject; bool channelAvailable = channelCallbacks.TryGetValue (callbackKey, out callbackObject); PubnubChannelCallback<T> currentPubnubCallback = null; if (channelAvailable) { currentPubnubCallback = callbackObject as PubnubChannelCallback<T>; } if (currentPubnubCallback != null && currentPubnubCallback.ErrorCallback != null) { state.Request.Abort (currentPubnubCallback.ErrorCallback, _errorLevel); } } } } else { ICollection<string> keyCollection = _channelRequest.Keys; foreach (string key in keyCollection) { PubnubWebRequest currentRequest = _channelRequest [key]; if (currentRequest != null) { TerminatePendingWebRequest(currentRequest, null); } } } } private void TerminatePendingWebRequest(PubnubWebRequest request, Action<PubnubClientError> errorCallback) { if (request != null) { request.Abort(errorCallback, _errorLevel); } } private void RemoveChannelDictionary() { RemoveChannelDictionary<object>(null); } private void RemoveChannelDictionary<T>(RequestState<T> state) { if (state != null && state.Request != null) { string channel = (state.Channels != null) ? string.Join (",", state.Channels) : ""; if (_channelRequest.ContainsKey (channel)) { PubnubWebRequest removedRequest; bool removeKey = _channelRequest.TryRemove (channel, out removedRequest); if (removeKey) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} Remove web request from dictionary in RemoveChannelDictionary for channel= {1}", DateTime.Now.ToString (), channel), LoggingMethod.LevelInfo); } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0} Unable to remove web request from dictionary in RemoveChannelDictionary for channel= {1}", DateTime.Now.ToString (), channel), LoggingMethod.LevelError); } } } else { ICollection<string> keyCollection = _channelRequest.Keys; foreach (string key in keyCollection) { PubnubWebRequest currentRequest = _channelRequest [key]; if (currentRequest != null) { bool removeKey = _channelRequest.TryRemove (key, out currentRequest); if (removeKey) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} Remove web request from dictionary in RemoveChannelDictionary for channel= {1}", DateTime.Now.ToString (), key), LoggingMethod.LevelInfo); } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0} Unable to remove web request from dictionary in RemoveChannelDictionary for channel= {1}", DateTime.Now.ToString (), key), LoggingMethod.LevelError); } } } } } private void RemoveChannelCallback() { ICollection<PubnubChannelCallbackKey> channelCollection = channelCallbacks.Keys; foreach (PubnubChannelCallbackKey keyChannel in channelCollection) { if (channelCallbacks.ContainsKey (keyChannel)) { object tempChannelCallback; bool removeKey = channelCallbacks.TryRemove (keyChannel, out tempChannelCallback); if (removeKey) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} RemoveChannelCallback from dictionary in RemoveChannelCallback for channel= {1}", DateTime.Now.ToString (), removeKey), LoggingMethod.LevelInfo); } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0} Unable to RemoveChannelCallback from dictionary in RemoveChannelCallback for channel= {1}", DateTime.Now.ToString (), removeKey), LoggingMethod.LevelError); } } } } private void RemoveUserState() { ICollection<string> channelLocalUserStateCollection = _channelLocalUserState.Keys; ICollection<string> channelUserStateCollection = _channelUserState.Keys; foreach (string key in channelLocalUserStateCollection) { if (_channelLocalUserState.ContainsKey(key)) { Dictionary<string, object> tempUserState; bool removeKey = _channelLocalUserState.TryRemove(key, out tempUserState); if (removeKey) { LoggingMethod.WriteToLog(string.Format("DateTime {0} RemoveUserState from local user state dictionary for channel= {1}", DateTime.Now.ToString(), removeKey), LoggingMethod.LevelInfo); } else { LoggingMethod.WriteToLog(string.Format("DateTime {0} Unable to RemoveUserState from local user state dictionary for channel= {1}", DateTime.Now.ToString(), removeKey), LoggingMethod.LevelError); } } } foreach (string key in channelUserStateCollection) { if (_channelUserState.ContainsKey(key)) { Dictionary<string, object> tempUserState; bool removeKey = _channelUserState.TryRemove(key, out tempUserState); if (removeKey) { LoggingMethod.WriteToLog(string.Format("DateTime {0} RemoveUserState from user state dictionary for channel= {1}", DateTime.Now.ToString(), removeKey), LoggingMethod.LevelInfo); } else { LoggingMethod.WriteToLog(string.Format("DateTime {0} Unable to RemoveUserState from user state dictionary for channel= {1}", DateTime.Now.ToString(), removeKey), LoggingMethod.LevelError); } } } } protected virtual void TerminatePresenceHeartbeatTimer() { if (presenceHeartbeatTimer != null) { presenceHeartbeatTimer.Dispose(); presenceHeartbeatTimer = null; } } protected virtual void TerminateLocalClientHeartbeatTimer() { TerminateLocalClientHeartbeatTimer(null); } protected virtual void TerminateLocalClientHeartbeatTimer(Uri requestUri) { if (requestUri != null) { if (channelLocalClientHeartbeatTimer.ContainsKey (requestUri)) { Timer requestHeatbeatTimer = channelLocalClientHeartbeatTimer [requestUri]; if (requestHeatbeatTimer != null) { try { requestHeatbeatTimer.Change ( (-1 == _pubnubNetworkTcpCheckIntervalInSeconds) ? -1 : _pubnubNetworkTcpCheckIntervalInSeconds * 1000, (-1 == _pubnubNetworkTcpCheckIntervalInSeconds) ? -1 : _pubnubNetworkTcpCheckIntervalInSeconds * 1000); requestHeatbeatTimer.Dispose (); } catch (ObjectDisposedException ex) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} Error while accessing requestHeatbeatTimer object in TerminateLocalClientHeartbeatTimer {1}", DateTime.Now.ToString (), ex.ToString ()), LoggingMethod.LevelInfo); } Timer removedTimer = null; bool removed = channelLocalClientHeartbeatTimer.TryRemove (requestUri, out removedTimer); if (removed) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} Remove local client heartbeat reference from collection for {1}", DateTime.Now.ToString (), requestUri.ToString ()), LoggingMethod.LevelInfo); } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0} Unable to remove local client heartbeat reference from collection for {1}", DateTime.Now.ToString (), requestUri.ToString ()), LoggingMethod.LevelInfo); } } } } else { ConcurrentDictionary<Uri, Timer> timerCollection = channelLocalClientHeartbeatTimer; ICollection<Uri> keyCollection = timerCollection.Keys; foreach (Uri key in keyCollection) { if (channelLocalClientHeartbeatTimer.ContainsKey (key)) { Timer currentTimer = channelLocalClientHeartbeatTimer [key]; currentTimer.Dispose (); Timer removedTimer = null; bool removed = channelLocalClientHeartbeatTimer.TryRemove (key, out removedTimer); if (!removed) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} TerminateLocalClientHeartbeatTimer(null) - Unable to remove local client heartbeat reference from collection for {1}", DateTime.Now.ToString (), key.ToString ()), LoggingMethod.LevelInfo); } } } } } private void TerminateReconnectTimer() { TerminateReconnectTimer(null); } private void TerminateReconnectTimer(string channelName) { if (channelName != null) { if (_channelReconnectTimer.ContainsKey (channelName)) { Timer channelReconnectTimer = _channelReconnectTimer [channelName]; channelReconnectTimer.Change ( (-1 == _pubnubNetworkTcpCheckIntervalInSeconds) ? -1 : _pubnubNetworkTcpCheckIntervalInSeconds * 1000, (-1 == _pubnubNetworkTcpCheckIntervalInSeconds) ? -1 : _pubnubNetworkTcpCheckIntervalInSeconds * 1000); channelReconnectTimer.Dispose (); Timer removedTimer = null; bool removed = _channelReconnectTimer.TryRemove (channelName, out removedTimer); if (!removed) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} TerminateReconnectTimer - Unable to remove reconnect timer reference from collection for {1}", DateTime.Now.ToString (), channelName), LoggingMethod.LevelInfo); } } } else { ConcurrentDictionary<string, Timer> reconnectCollection = _channelReconnectTimer; ICollection<string> keyCollection = reconnectCollection.Keys; foreach (string key in keyCollection) { if (_channelReconnectTimer.ContainsKey (key)) { Timer currentTimer = _channelReconnectTimer [key]; currentTimer.Dispose (); Timer removedTimer = null; bool removed = _channelReconnectTimer.TryRemove (key, out removedTimer); if (!removed) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} TerminateReconnectTimer(null) - Unable to remove reconnect timer reference from collection for {1}", DateTime.Now.ToString (), key.ToString ()), LoggingMethod.LevelInfo); } } } } } public void EndPendingRequests() { RemoveChannelDictionary(); TerminatePendingWebRequest(); TerminateLocalClientHeartbeatTimer(); TerminateReconnectTimer(); RemoveChannelCallback(); RemoveUserState(); TerminatePresenceHeartbeatTimer(); } public void TerminateCurrentSubscriberRequest() { string[] channels = GetCurrentSubscriberChannels (); if (channels != null) { string multiChannel = string.Join (",", channels); PubnubWebRequest request = (_channelRequest.ContainsKey (multiChannel)) ? _channelRequest [multiChannel] : null; if (request != null) { request.Abort (null, _errorLevel); LoggingMethod.WriteToLog (string.Format ("DateTime {0} TerminateCurrentSubsciberRequest {1}", DateTime.Now.ToString (), request.RequestUri.ToString ()), LoggingMethod.LevelInfo); } } } #endregion #region "Change UUID" public void ChangeUUID(string newUUID) { if (string.IsNullOrEmpty (newUUID) || sessionUUID == newUUID) { return; } _uuidChanged = true; string oldUUID = sessionUUID; sessionUUID = newUUID; string[] channels = GetCurrentSubscriberChannels(); if (channels != null && channels.Length > 0) { Uri request = BuildMultiChannelLeaveRequest(channels, oldUUID); RequestState<string> requestState = new RequestState<string>(); requestState.Channels = channels; requestState.Type = ResponseType.Leave; requestState.UserCallback = null; requestState.ErrorCallback = null; requestState.ConnectCallback = null; requestState.Reconnect = false; UrlProcessRequest<string>(request, requestState); // connectCallback = null } TerminateCurrentSubscriberRequest(); } #endregion #region "Constructors" /** * PubNub 3.0 API * * Prepare Pubnub messaging class initial state * * @param string publishKey. * @param string subscribeKey. * @param string secretKey. * @param bool sslOn */ public PubnubCore (string publishKey, string subscribeKey, string secretKey, string cipherKey, bool sslOn) { this.Init (publishKey, subscribeKey, secretKey, cipherKey, sslOn); } /** * PubNub 2.0 Compatibility * * Prepare Pubnub messaging class initial state * * @param string publishKey. * @param string subscribeKey. */ public PubnubCore (string publishKey, string subscribeKey) { this.Init (publishKey, subscribeKey, "", "", false); } /// <summary> /// PubNub without SSL /// Prepare Pubnub messaging class initial state /// </summary> /// <param name="publishKey"></param> /// <param name="subscribeKey"></param> /// <param name="secretKey"></param> public PubnubCore (string publishKey, string subscribeKey, string secretKey) { this.Init (publishKey, subscribeKey, secretKey, "", false); } #endregion #region History (obsolete) /// <summary> /// History (Obsolete) /// Load history from a channel /// </summary> /// <param name="channel"></param> /// <param name="limit"></param> /// <returns></returns> [Obsolete ("This method should no longer be used, please use DetailedHistory() instead.")] public bool history (string channel, int limit) { List<string> url = new List<string> (); url.Add ("history"); url.Add (this.subscribeKey); url.Add (channel); url.Add ("0"); url.Add (limit.ToString ()); return ProcessRequest (url, ResponseType.History); } /// <summary> /// Http Get Request process /// </summary> /// <param name="urlComponents"></param> /// <param name="type"></param> /// <returns></returns> private bool ProcessRequest (List<string> urlComponents, ResponseType type) { string channelName = GetChannelName (urlComponents, type); StringBuilder url = new StringBuilder (); // Add Origin To The Request url.Append (this._origin); // Generate URL with UTF-8 Encoding foreach (string url_bit in urlComponents) { url.Append ("/"); url.Append (EncodeUricomponent (url_bit, type, true)); } VerifyOrSetSessionUUID (); if (type == ResponseType.Presence || type == ResponseType.Subscribe) { url.Append ("?uuid="); url.Append (this.sessionUUID); } if (type == ResponseType.DetailedHistory) url.Append (parameters); Uri requestUri = new Uri (url.ToString ()); ForceCanonicalPathAndQuery (requestUri); // Create Request HttpWebRequest request = (HttpWebRequest)WebRequest.Create (requestUri); try { // Make request with the following inline Asynchronous callback request.BeginGetResponse (new AsyncCallback ((asynchronousResult) => { HttpWebRequest asyncWebRequest = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse asyncWebResponse = (HttpWebResponse)asyncWebRequest.EndGetResponse (asynchronousResult); using (StreamReader streamReader = new StreamReader (asyncWebResponse.GetResponseStream ())) { // Deserialize the result string jsonString = streamReader.ReadToEnd (); Action<PubnubClientError> dummyCallback = obj => { }; WrapResultBasedOnResponseType<string> (type, jsonString, new string[] { channelName }, false, 0, dummyCallback); } }), request ); return true; } catch (System.Exception) { return false; } } #endregion #region "Detailed History" /** * Detailed History */ public bool DetailedHistory (string channel, long start, long end, int count, bool reverse, Action<object> userCallback, Action<PubnubClientError> errorCallback) { return DetailedHistory<object> (channel, start, end, count, reverse, userCallback, errorCallback); } public bool DetailedHistory<T> (string channel, long start, long end, int count, bool reverse, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (channel) || string.IsNullOrEmpty (channel.Trim ())) { throw new ArgumentException ("Missing Channel"); } if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } Uri request = BuildDetailedHistoryRequest (channel, start, end, count, reverse); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = new string[] { channel }; requestState.Type = ResponseType.DetailedHistory; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; return UrlProcessRequest<T> (request, requestState); } public bool DetailedHistory (string channel, long start, Action<object> userCallback, Action<PubnubClientError> errorCallback, bool reverse) { return DetailedHistory<object> (channel, start, -1, -1, reverse, userCallback, errorCallback); } public bool DetailedHistory<T> (string channel, long start, Action<T> userCallback, Action<PubnubClientError> errorCallback, bool reverse) { return DetailedHistory<T> (channel, start, -1, -1, reverse, userCallback, errorCallback); } public bool DetailedHistory (string channel, int count, Action<object> userCallback, Action<PubnubClientError> errorCallback) { return DetailedHistory<object> (channel, -1, -1, count, false, userCallback, errorCallback); } public bool DetailedHistory<T> (string channel, int count, Action<T> userCallback, Action<PubnubClientError> errorCallback) { return DetailedHistory<T> (channel, -1, -1, count, false, userCallback, errorCallback); } private Uri BuildDetailedHistoryRequest (string channel, long start, long end, int count, bool reverse) { parameters = ""; if (count <= -1) count = 100; parameters = "?count=" + count; if (reverse) parameters = parameters + "&" + "reverse=" + reverse.ToString ().ToLower (); if (start != -1) parameters = parameters + "&" + "start=" + start.ToString ().ToLower (); if (end != -1) parameters = parameters + "&" + "end=" + end.ToString ().ToLower (); if (!string.IsNullOrEmpty (_authenticationKey)) { parameters = parameters + "&" + "auth=" + _authenticationKey; } List<string> url = new List<string> (); url.Add ("v2"); url.Add ("history"); url.Add ("sub-key"); url.Add (this.subscribeKey); url.Add ("channel"); url.Add (channel); return BuildRestApiRequest<Uri> (url, ResponseType.DetailedHistory); } #endregion #region "Publish" /// <summary> /// Publish /// Send a message to a channel /// </summary> /// <param name="channel"></param> /// <param name="message"></param> /// <param name="userCallback"></param> /// <returns></returns> public bool Publish (string channel, object message, Action<object> userCallback, Action<PubnubClientError> errorCallback) { return Publish<object> (channel, message, userCallback, errorCallback); } public bool Publish<T> (string channel, object message, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (channel) || string.IsNullOrEmpty (channel.Trim ()) || message == null) { throw new ArgumentException ("Missing Channel or Message"); } if (string.IsNullOrEmpty (this.publishKey) || string.IsNullOrEmpty (this.publishKey.Trim ()) || this.publishKey.Length <= 0) { throw new MissingMemberException("Invalid publish key"); } if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } Uri request = BuildPublishRequest (channel, message); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = new string[] { channel }; requestState.Type = ResponseType.Publish; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; return UrlProcessRequest<T> (request, requestState); } private Uri BuildPublishRequest (string channel, object originalMessage) { string message = (_enableJsonEncodingForPublish) ? JsonEncodePublishMsg (originalMessage) : originalMessage.ToString (); // Generate String to Sign string signature = "0"; if (this.secretKey.Length > 0) { StringBuilder string_to_sign = new StringBuilder (); string_to_sign .Append (this.publishKey) .Append ('/') .Append (this.subscribeKey) .Append ('/') .Append (this.secretKey) .Append ('/') .Append (channel) .Append ('/') .Append (message); // 1 // Sign Message signature = Md5 (string_to_sign.ToString ()); } // Build URL List<string> url = new List<string> (); url.Add ("publish"); url.Add (this.publishKey); url.Add (this.subscribeKey); url.Add (signature); url.Add (channel); url.Add ("0"); url.Add (message); return BuildRestApiRequest<Uri> (url, ResponseType.Publish); } #endregion #region "Encoding and Crypto" private string JsonEncodePublishMsg (object originalMessage) { string message = _jsonPluggableLibrary.SerializeToJsonString (originalMessage); if (this.cipherKey.Length > 0) { PubnubCrypto aes = new PubnubCrypto (this.cipherKey); string encryptMessage = aes.Encrypt (message); message = _jsonPluggableLibrary.SerializeToJsonString (encryptMessage); } return message; } //TODO: Identify refactoring private List<object> DecodeDecryptLoop (List<object> message, string[] channels, Action<PubnubClientError> errorCallback) { List<object> returnMessage = new List<object> (); if (this.cipherKey.Length > 0) { PubnubCrypto aes = new PubnubCrypto (this.cipherKey); var myObjectArray = (from item in message select item as object).ToArray (); IEnumerable enumerable = myObjectArray [0] as IEnumerable; if (enumerable != null) { List<object> receivedMsg = new List<object> (); foreach (object element in enumerable) { string decryptMessage = ""; try { decryptMessage = aes.Decrypt (element.ToString ()); } catch (Exception ex) { decryptMessage = "**DECRYPT ERROR**"; string multiChannel = string.Join (",", channels); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, multiChannel, errorCallback, ex, null, null); } object decodeMessage = (decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : _jsonPluggableLibrary.DeserializeToObject (decryptMessage); receivedMsg.Add (decodeMessage); } returnMessage.Add (receivedMsg); } for (int index = 1; index < myObjectArray.Length; index++) { returnMessage.Add (myObjectArray [index]); } return returnMessage; } else { var myObjectArray = (from item in message select item as object).ToArray (); IEnumerable enumerable = myObjectArray [0] as IEnumerable; if (enumerable != null) { List<object> receivedMessage = new List<object> (); foreach (object element in enumerable) { receivedMessage.Add (element); } returnMessage.Add (receivedMessage); } for (int index = 1; index < myObjectArray.Length; index++) { returnMessage.Add (myObjectArray [index]); } return returnMessage; } } private static string Md5 (string text) { MD5 md5 = new MD5CryptoServiceProvider (); byte[] data = Encoding.Unicode.GetBytes (text); byte[] hash = md5.ComputeHash (data); string hexaHash = ""; foreach (byte b in hash) hexaHash += String.Format ("{0:x2}", b); return hexaHash; } protected virtual string EncodeUricomponent (string s, ResponseType type, bool ignoreComma) { string encodedUri = ""; StringBuilder o = new StringBuilder (); foreach (char ch in s) { if (IsUnsafe (ch, ignoreComma)) { o.Append ('%'); o.Append (ToHex (ch / 16)); o.Append (ToHex (ch % 16)); } else { if (ch == ',' && ignoreComma) { o.Append (ch.ToString ()); } else if (Char.IsSurrogate (ch)) { o.Append (ch); } else { string escapeChar = System.Uri.EscapeDataString (ch.ToString ()); o.Append (escapeChar); } } } encodedUri = o.ToString (); if (type == ResponseType.Here_Now || type == ResponseType.DetailedHistory || type == ResponseType.Leave || type == ResponseType.PresenceHeartbeat) { encodedUri = encodedUri.Replace ("%2F", "%252F"); } return encodedUri; } protected char ToHex (int ch) { return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10); } #endregion #region "Presence And Subscribe" /// <summary> /// Subscribe /// Listen for a message on a channel /// </summary> /// <param name="channel"></param> /// <param name="userCallback"></param> /// <param name="connectCallback"></param> public void Subscribe (string channel, Action<object> userCallback, Action<object> connectCallback, Action<PubnubClientError> errorCallback) { Subscribe<object> (channel, userCallback, connectCallback, errorCallback); } public void Subscribe<T> (string channel, Action<T> userCallback, Action<T> connectCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (channel) || string.IsNullOrEmpty (channel.Trim ())) { throw new ArgumentException ("Missing Channel"); } if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (connectCallback == null) { throw new ArgumentException ("Missing connectCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, requested subscribe for channel={1}", DateTime.Now.ToString (), channel), LoggingMethod.LevelInfo); MultiChannelSubscribeInit<T> (ResponseType.Subscribe, channel, userCallback, connectCallback, errorCallback); } /// <summary> /// Presence /// Listen for a presence message on a channel or comma delimited channels /// </summary> /// <param name="channel"></param> /// <param name="userCallback"></param> /// <param name="connectCallback"></param> /// <param name="errorCallback"></param> public void Presence (string channel, Action<object> userCallback, Action<object> connectCallback, Action<PubnubClientError> errorCallback) { Presence<object> (channel, userCallback, connectCallback, errorCallback); } public void Presence<T> (string channel, Action<T> userCallback, Action<T> connectCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (channel) || string.IsNullOrEmpty (channel.Trim ())) { throw new ArgumentException ("Missing Channel"); } if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, requested presence for channel={1}", DateTime.Now.ToString (), channel), LoggingMethod.LevelInfo); MultiChannelSubscribeInit<T> (ResponseType.Presence, channel, userCallback, connectCallback, errorCallback); } private void MultiChannelSubscribeInit<T> (ResponseType type, string channel, Action<T> userCallback, Action<T> connectCallback, Action<PubnubClientError> errorCallback) { string[] rawChannels = channel.Split (','); List<string> validChannels = new List<string> (); bool networkConnection = InternetConnectionStatusWithUnitTestCheck<T> (channel, errorCallback, rawChannels); if (rawChannels.Length > 0 && networkConnection) { if (rawChannels.Length != rawChannels.Distinct ().Count ()) { rawChannels = rawChannels.Distinct ().ToArray (); string message = "Detected and removed duplicate channels"; CallErrorCallback (PubnubErrorSeverity.Info, PubnubMessageSource.Client, channel, errorCallback, message, PubnubErrorCode.DuplicateChannel, null, null); } for (int index = 0; index < rawChannels.Length; index++) { if (rawChannels [index].Trim ().Length > 0) { string channelName = rawChannels [index].Trim (); if (type == ResponseType.Presence) { channelName = string.Format ("{0}-pnpres", channelName); } if (multiChannelSubscribe.ContainsKey (channelName)) { string message = string.Format ("{0}Already subscribed", (IsPresenceChannel (channelName)) ? "Presence " : ""); PubnubErrorCode errorType = (IsPresenceChannel (channelName)) ? PubnubErrorCode.AlreadyPresenceSubscribed : PubnubErrorCode.AlreadySubscribed; CallErrorCallback (PubnubErrorSeverity.Info, PubnubMessageSource.Client, channelName.Replace ("-pnpres", ""), errorCallback, message, errorType, null, null); } else { validChannels.Add (channelName); } } } } if (validChannels.Count > 0) { //Retrieve the current channels already subscribed previously and terminate them string[] currentChannels = multiChannelSubscribe.Keys.ToArray<string> (); if (currentChannels != null && currentChannels.Length > 0) { string multiChannelName = string.Join (",", currentChannels); if (_channelRequest.ContainsKey (multiChannelName)) { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Aborting previous subscribe/presence requests having channel(s)={1}", DateTime.Now.ToString (), multiChannelName), LoggingMethod.LevelInfo); PubnubWebRequest webRequest = _channelRequest [multiChannelName]; _channelRequest [multiChannelName] = null; if (webRequest != null) TerminateLocalClientHeartbeatTimer (webRequest.RequestUri); PubnubWebRequest removedRequest; _channelRequest.TryRemove (multiChannelName, out removedRequest); bool removedChannel = _channelRequest.TryRemove (multiChannelName, out removedRequest); if (removedChannel) { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Success to remove channel(s)={1} from _channelRequest (MultiChannelSubscribeInit).", DateTime.Now.ToString (), multiChannelName), LoggingMethod.LevelInfo); } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Unable to remove channel(s)={1} from _channelRequest (MultiChannelSubscribeInit).", DateTime.Now.ToString (), multiChannelName), LoggingMethod.LevelInfo); } if (webRequest != null) TerminatePendingWebRequest (webRequest, errorCallback); } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Unable to capture channel(s)={1} from _channelRequest to abort request.", DateTime.Now.ToString (), multiChannelName), LoggingMethod.LevelInfo); } } //Add the valid channels to the channels subscribe list for tracking for (int index = 0; index < validChannels.Count; index++) { string currentLoopChannel = validChannels [index].ToString (); multiChannelSubscribe.GetOrAdd (currentLoopChannel, 0); PubnubChannelCallbackKey callbackKey = new PubnubChannelCallbackKey (); callbackKey.Channel = currentLoopChannel; callbackKey.Type = type; PubnubChannelCallback<T> pubnubChannelCallbacks = new PubnubChannelCallback<T> (); pubnubChannelCallbacks.Callback = userCallback; pubnubChannelCallbacks.ConnectCallback = connectCallback; pubnubChannelCallbacks.ErrorCallback = errorCallback; channelCallbacks.AddOrUpdate (callbackKey, pubnubChannelCallbacks, (key, oldValue) => pubnubChannelCallbacks); } //Get all the channels string[] channels = multiChannelSubscribe.Keys.ToArray<string> (); RequestState<T> state = new RequestState<T> (); _channelRequest.AddOrUpdate (string.Join (",", channels), state.Request, (key, oldValue) => state.Request); ResetInternetCheckSettings (channels); MultiChannelSubscribeRequest<T> (type, channels, 0, userCallback, connectCallback, errorCallback, false); } } /// <summary> /// Multi-Channel Subscribe Request - private method for Subscribe /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="channels"></param> /// <param name="timetoken"></param> /// <param name="userCallback"></param> /// <param name="connectCallback"></param> /// <param name="errorCallback"></param> /// <param name="reconnect"></param> private void MultiChannelSubscribeRequest<T> (ResponseType type, string[] channels, object timetoken, Action<T> userCallback, Action<T> connectCallback, Action<PubnubClientError> errorCallback, bool reconnect) { //Exit if the channel is unsubscribed if (multiChannelSubscribe != null && multiChannelSubscribe.Count <= 0) { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, All channels are Unsubscribed. Further subscription was stopped", DateTime.Now.ToString ()), LoggingMethod.LevelInfo); return; } string multiChannel = string.Join (",", channels); if (!_channelRequest.ContainsKey (multiChannel)) { return; } if (channelInternetStatus.ContainsKey (multiChannel) && (!channelInternetStatus [multiChannel]) && pubnetSystemActive) { if (channelInternetRetry.ContainsKey (multiChannel) && (channelInternetRetry [multiChannel] >= _pubnubNetworkCheckRetries)) { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Subscribe channel={1} - No internet connection. MAXed retries for internet ", DateTime.Now.ToString (), multiChannel), LoggingMethod.LevelInfo); MultiplexExceptionHandler<T> (type, channels, userCallback, connectCallback, errorCallback, true, false); return; } if (ReconnectNetworkIfOverrideTcpKeepAlive <T> (type, channels, timetoken, userCallback, connectCallback, errorCallback, multiChannel)) { return; } } // Begin recursive subscribe try { long lastTimetoken = 0; long minimumTimetoken = multiChannelSubscribe.Min (token => token.Value); long maximumTimetoken = multiChannelSubscribe.Max (token => token.Value); if (minimumTimetoken == 0 || reconnect || _uuidChanged) { lastTimetoken = 0; _uuidChanged = false; } else { if (lastSubscribeTimetoken == maximumTimetoken) { lastTimetoken = maximumTimetoken; } else { lastTimetoken = lastSubscribeTimetoken; } } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Building request for channel(s)={1} with timetoken={2}", DateTime.Now.ToString (), string.Join (",", channels), lastTimetoken), LoggingMethod.LevelInfo); // Build URL Uri requestUrl = BuildMultiChannelSubscribeRequest (channels, (Convert.ToInt64 (timetoken.ToString ()) == 0) ? Convert.ToInt64 (timetoken.ToString ()) : lastTimetoken); RequestState<T> pubnubRequestState = new RequestState<T> (); pubnubRequestState.Channels = channels; pubnubRequestState.Type = type; pubnubRequestState.ConnectCallback = connectCallback; pubnubRequestState.UserCallback = userCallback; pubnubRequestState.ErrorCallback = errorCallback; pubnubRequestState.Reconnect = reconnect; pubnubRequestState.Timetoken = Convert.ToInt64 (timetoken.ToString ()); // Wait for message UrlProcessRequest<T> (requestUrl, pubnubRequestState); } catch (Exception ex) { LoggingMethod.WriteToLog (string.Format ("DateTime {0} method:_subscribe \n channel={1} \n timetoken={2} \n Exception Details={3}", DateTime.Now.ToString (), string.Join (",", channels), timetoken.ToString (), ex.ToString ()), LoggingMethod.LevelError); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, string.Join (",", channels), errorCallback, ex, null, null); this.MultiChannelSubscribeRequest<T> (type, channels, timetoken, userCallback, connectCallback, errorCallback, false); } } private Uri BuildMultiChannelSubscribeRequest (string[] channels, object timetoken) { subscribeParameters = ""; string channelsJsonState = BuildJsonUserState (channels, false); if (channelsJsonState != "{}" && channelsJsonState != "") { subscribeParameters = string.Format ("&state={0}", EncodeUricomponent (channelsJsonState, ResponseType.Subscribe, false)); } List<string> url = new List<string> (); url.Add ("subscribe"); url.Add (this.subscribeKey); url.Add (string.Join (",", channels)); url.Add ("0"); url.Add (timetoken.ToString ()); return BuildRestApiRequest<Uri> (url, ResponseType.Subscribe); } #endregion #region "Unsubscribe Presence And Subscribe" public void PresenceUnsubscribe (string channel, Action<object> userCallback, Action<object> connectCallback, Action<object> disconnectCallback, Action<PubnubClientError> errorCallback) { PresenceUnsubscribe<object> (channel, userCallback, connectCallback, disconnectCallback, errorCallback); } public void PresenceUnsubscribe<T> (string channel, Action<T> userCallback, Action<T> connectCallback, Action<T> disconnectCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (channel) || string.IsNullOrEmpty (channel.Trim ())) { throw new ArgumentException ("Missing Channel"); } if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (connectCallback == null) { throw new ArgumentException ("Missing connectCallback"); } if (disconnectCallback == null) { throw new ArgumentException ("Missing disconnectCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, requested presence-unsubscribe for channel(s)={1}", DateTime.Now.ToString (), channel), LoggingMethod.LevelInfo); MultiChannelUnSubscribeInit<T> (ResponseType.PresenceUnsubscribe, channel, userCallback, connectCallback, disconnectCallback, errorCallback); } private void MultiChannelUnSubscribeInit<T> (ResponseType type, string channel, Action<T> userCallback, Action<T> connectCallback, Action<T> disconnectCallback, Action<PubnubClientError> errorCallback) { string[] rawChannels = channel.Split (','); List<string> validChannels = new List<string> (); if (rawChannels.Length > 0) { for (int index = 0; index < rawChannels.Length; index++) { if (rawChannels [index].Trim ().Length > 0) { string channelName = rawChannels [index].Trim (); if (type == ResponseType.PresenceUnsubscribe) { channelName = string.Format ("{0}-pnpres", channelName); } if (!multiChannelSubscribe.ContainsKey (channelName)) { string message = string.Format ("{0}Channel Not Subscribed", (IsPresenceChannel (channelName)) ? "Presence " : ""); PubnubErrorCode errorType = (IsPresenceChannel (channelName)) ? PubnubErrorCode.NotPresenceSubscribed : PubnubErrorCode.NotSubscribed; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, channel={1} unsubscribe response={2}", DateTime.Now.ToString (), channelName, message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Info, PubnubMessageSource.Client, channelName, errorCallback, message, errorType, null, null); } else { validChannels.Add (channelName); } } else { string message = "Invalid Channel Name For Unsubscribe"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, channel={1} unsubscribe response={2}", DateTime.Now.ToString (), rawChannels [index], message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Info, PubnubMessageSource.Client, rawChannels [index], errorCallback, message, PubnubErrorCode.InvalidChannel, null, null); } } } if (validChannels.Count > 0) { //Retrieve the current channels already subscribed previously and terminate them string[] currentChannels = multiChannelSubscribe.Keys.ToArray<string> (); if (currentChannels != null && currentChannels.Length > 0) { string multiChannelName = string.Join (",", currentChannels); if (_channelRequest.ContainsKey (multiChannelName)) { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Aborting previous subscribe/presence requests having channel(s)={1}", DateTime.Now.ToString (), multiChannelName), LoggingMethod.LevelInfo); PubnubWebRequest webRequest = _channelRequest [multiChannelName]; _channelRequest [multiChannelName] = null; if (webRequest != null) { TerminateLocalClientHeartbeatTimer (webRequest.RequestUri); } PubnubWebRequest removedRequest; bool removedChannel = _channelRequest.TryRemove (multiChannelName, out removedRequest); if (removedChannel) { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Success to remove channel(s)={1} from _channelRequest (MultiChannelUnSubscribeInit).", DateTime.Now.ToString (), multiChannelName), LoggingMethod.LevelInfo); } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Unable to remove channel(s)={1} from _channelRequest (MultiChannelUnSubscribeInit).", DateTime.Now.ToString (), multiChannelName), LoggingMethod.LevelInfo); } if (webRequest != null) TerminatePendingWebRequest (webRequest, errorCallback); } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Unable to capture channel(s)={1} from _channelRequest to abort request.", DateTime.Now.ToString (), multiChannelName), LoggingMethod.LevelInfo); } if (type == ResponseType.Unsubscribe) { //just fire leave() event to REST API for safeguard Uri request = BuildMultiChannelLeaveRequest (validChannels.ToArray ()); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = new string[] { channel }; requestState.Type = ResponseType.Leave; requestState.UserCallback = null; requestState.ErrorCallback = null; requestState.ConnectCallback = null; requestState.Reconnect = false; UrlProcessRequest<T> (request, requestState); // connectCallback = null } } //Remove the valid channels from subscribe list for unsubscribe for (int index = 0; index < validChannels.Count; index++) { long timetokenValue; string channelToBeRemoved = validChannels [index].ToString (); bool unsubscribeStatus = multiChannelSubscribe.TryRemove (channelToBeRemoved, out timetokenValue); if (unsubscribeStatus) { List<object> result = new List<object> (); string jsonString = string.Format ("[1, \"{0}Unsubscribed from {1}\"]", (IsPresenceChannel (channelToBeRemoved)) ? "Presence " : "", channelToBeRemoved.Replace ("-pnpres", "")); result = _jsonPluggableLibrary.DeserializeToListOfObject (jsonString); result.Add (channelToBeRemoved.Replace ("-pnpres", "")); LoggingMethod.WriteToLog (string.Format ("DateTime {0}, JSON response={1}", DateTime.Now.ToString (), jsonString), LoggingMethod.LevelInfo); GoToCallback<T> (result, disconnectCallback); DeleteLocalUserState (channelToBeRemoved); } else { string message = "Unsubscribe Error. Please retry the unsubscribe operation."; PubnubErrorCode errorType = (IsPresenceChannel (channelToBeRemoved)) ? PubnubErrorCode.PresenceUnsubscribeFailed : PubnubErrorCode.UnsubscribeFailed; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, channel={1} unsubscribe error", DateTime.Now.ToString (), channelToBeRemoved), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, channelToBeRemoved, errorCallback, message, errorType, null, null); } } //Get all the channels string[] channels = multiChannelSubscribe.Keys.ToArray<string> (); if (channels != null && channels.Length > 0) { RequestState<T> state = new RequestState<T> (); _channelRequest.AddOrUpdate (string.Join (",", channels), state.Request, (key, oldValue) => state.Request); ResetInternetCheckSettings (channels); //Modify the value for type ResponseType. Presence or Subscrie is ok, but sending the close value would make sense if (string.Join (",", channels).IndexOf ("-pnpres") > 0) { type = ResponseType.Presence; } else { type = ResponseType.Subscribe; } //Continue with any remaining channels for subscribe/presence MultiChannelSubscribeRequest<T> (type, channels, 0, userCallback, connectCallback, errorCallback, false); } else { if (presenceHeartbeatTimer != null) { // Stop the presence heartbeat timer if there are no channels subscribed presenceHeartbeatTimer.Dispose (); presenceHeartbeatTimer = null; } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, All channels are Unsubscribed. Further subscription was stopped", DateTime.Now.ToString ()), LoggingMethod.LevelInfo); } } } /// <summary> /// To unsubscribe a channel /// </summary> /// <param name="channel"></param> /// <param name="userCallback"></param> /// <param name="connectCallback"></param> /// <param name="disconnectCallback"></param> /// <param name="errorCallback"></param> public void Unsubscribe (string channel, Action<object> userCallback, Action<object> connectCallback, Action<object> disconnectCallback, Action<PubnubClientError> errorCallback) { Unsubscribe<object> (channel, userCallback, connectCallback, disconnectCallback, errorCallback); } /// <summary> /// To unsubscribe a channel /// </summary> /// <typeparam name="T"></typeparam> /// <param name="channel"></param> /// <param name="userCallback"></param> /// <param name="connectCallback"></param> /// <param name="disconnectCallback"></param> /// <param name="errorCallback"></param> public void Unsubscribe<T> (string channel, Action<T> userCallback, Action<T> connectCallback, Action<T> disconnectCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (channel) || string.IsNullOrEmpty (channel.Trim ())) { throw new ArgumentException ("Missing Channel"); } if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (connectCallback == null) { throw new ArgumentException ("Missing connectCallback"); } if (disconnectCallback == null) { throw new ArgumentException ("Missing disconnectCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, requested unsubscribe for channel(s)={1}", DateTime.Now.ToString (), channel), LoggingMethod.LevelInfo); MultiChannelUnSubscribeInit<T> (ResponseType.Unsubscribe, channel, userCallback, connectCallback, disconnectCallback, errorCallback); } private Uri BuildMultiChannelLeaveRequest (string[] channels) { return BuildMultiChannelLeaveRequest (channels, ""); } private Uri BuildMultiChannelLeaveRequest (string[] channels, string uuid) { List<string> url = new List<string> (); url.Add ("v2"); url.Add ("presence"); url.Add ("sub_key"); url.Add (this.subscribeKey); url.Add ("channel"); url.Add (string.Join (",", channels)); url.Add ("leave"); return BuildRestApiRequest<Uri> (url, ResponseType.Leave, uuid); } #endregion #region "HereNow" internal bool HereNow (string channel, Action<object> userCallback, Action<PubnubClientError> errorCallback) { return HereNow<object> (channel, true, false, userCallback, errorCallback); } internal bool HereNow<T> (string channel, Action<T> userCallback, Action<PubnubClientError> errorCallback) { return HereNow<T> (channel, true, false, userCallback, errorCallback); } internal bool HereNow<T> (string channel, bool showUUIDList, bool includeUserState, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (channel) || string.IsNullOrEmpty (channel.Trim ())) { throw new ArgumentException ("Missing Channel"); } if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } Uri request = BuildHereNowRequest (channel, showUUIDList, includeUserState); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = new string[] { channel }; requestState.Type = ResponseType.Here_Now; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; return UrlProcessRequest<T> (request, requestState); } private Uri BuildHereNowRequest (string channel, bool showUUIDList, bool includeUserState) { int disableUUID = (showUUIDList) ? 0 : 1; int userState = (includeUserState) ? 1 : 0; hereNowParameters = string.Format ("?disable_uuids={0}&state={1}", disableUUID, userState); List<string> url = new List<string> (); url.Add ("v2"); url.Add ("presence"); url.Add ("sub_key"); url.Add (this.subscribeKey); url.Add ("channel"); url.Add (channel); return BuildRestApiRequest<Uri> (url, ResponseType.Here_Now); } private Uri BuildPresenceHeartbeatRequest (string[] channels) { presenceHeartbeatParameters = ""; string channelsJsonState = BuildJsonUserState (channels, false); if (channelsJsonState != "{}" && channelsJsonState != "") { presenceHeartbeatParameters = string.Format ("&state={0}", EncodeUricomponent (channelsJsonState, ResponseType.PresenceHeartbeat, false)); } List<string> url = new List<string> (); url.Add ("v2"); url.Add ("presence"); url.Add ("sub_key"); url.Add (this.subscribeKey); url.Add ("channel"); url.Add (string.Join (",", channels)); url.Add ("heartbeat"); return BuildRestApiRequest<Uri> (url, ResponseType.PresenceHeartbeat); } #endregion #region "Global Here Now" internal void GlobalHereNow (Action<object> userCallback, Action<PubnubClientError> errorCallback) { GlobalHereNow<object> (true, false, userCallback, errorCallback); } internal bool GlobalHereNow<T> (Action<T> userCallback, Action<PubnubClientError> errorCallback) { return GlobalHereNow<T> (true, false, userCallback, errorCallback); } internal bool GlobalHereNow<T> (bool showUUIDList, bool includeUserState, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } Uri request = BuildGlobalHereNowRequest (showUUIDList, includeUserState); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = null; requestState.Type = ResponseType.GlobalHere_Now; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; return UrlProcessRequest<T> (request, requestState); } private Uri BuildGlobalHereNowRequest (bool showUUIDList, bool includeUserState) { int disableUUID = (showUUIDList) ? 0 : 1; int userState = (includeUserState) ? 1 : 0; globalHereNowParameters = string.Format ("?disable_uuids={0}&state={1}", disableUUID, userState); List<string> url = new List<string> (); url.Add ("v2"); url.Add ("presence"); url.Add ("sub_key"); url.Add (this.subscribeKey); return BuildRestApiRequest<Uri> (url, ResponseType.GlobalHere_Now); } #endregion #region "WhereNow" internal void WhereNow (string uuid, Action<object> userCallback, Action<PubnubClientError> errorCallback) { WhereNow<object> (uuid, userCallback, errorCallback); } internal void WhereNow<T> (string uuid, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } if (string.IsNullOrEmpty (uuid)) { VerifyOrSetSessionUUID (); uuid = sessionUUID; } Uri request = BuildWhereNowRequest (uuid); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = new string[] { uuid }; requestState.Type = ResponseType.Where_Now; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; UrlProcessRequest<T> (request, requestState); } private Uri BuildWhereNowRequest (string uuid) { List<string> url = new List<string> (); url.Add ("v2"); url.Add ("presence"); url.Add ("sub_key"); url.Add (this.subscribeKey); url.Add ("uuid"); url.Add (uuid); return BuildRestApiRequest<Uri> (url, ResponseType.Where_Now); } #endregion #region "Time" /// <summary> /// Time /// Timestamp from PubNub Cloud /// </summary> /// <param name="userCallback"></param> /// <param name="errorCallback"></param> /// <returns></returns> public bool Time (Action<object> userCallback, Action<PubnubClientError> errorCallback) { return Time<object> (userCallback, errorCallback); } public bool Time<T> (Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } Uri request = BuildTimeRequest (); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = null; requestState.Type = ResponseType.Time; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; return UrlProcessRequest<T> (request, requestState); } public Uri BuildTimeRequest () { List<string> url = new List<string> (); url.Add ("time"); url.Add ("0"); return BuildRestApiRequest<Uri> (url, ResponseType.Time); } #endregion #region "User State" private string AddOrUpdateOrDeleteLocalUserState (string channel, string userStateKey, object userStateValue) { string retJsonUserState = ""; Dictionary<string, object> userStateDictionary = null; if (_channelLocalUserState.ContainsKey (channel)) { userStateDictionary = _channelLocalUserState[channel]; if (userStateDictionary != null) { if (userStateDictionary.ContainsKey (userStateKey)) { if (userStateValue != null) { userStateDictionary[userStateKey] = userStateValue; } else { userStateDictionary.Remove(userStateKey); } } else { if (!string.IsNullOrEmpty (userStateKey) && userStateKey.Trim ().Length > 0 && userStateValue != null) { userStateDictionary.Add (userStateKey, userStateValue); } } } else { userStateDictionary = new Dictionary<string, object> (); userStateDictionary.Add (userStateKey, userStateValue); } _channelLocalUserState.AddOrUpdate(channel, userStateDictionary, (oldData, newData) => userStateDictionary); } else { if (!string.IsNullOrEmpty (userStateKey) && userStateKey.Trim ().Length > 0 && userStateValue != null) { userStateDictionary = new Dictionary<string, object> (); userStateDictionary.Add (userStateKey, userStateValue); _channelLocalUserState.AddOrUpdate (channel, userStateDictionary, (oldData, newData) => userStateDictionary); } } string jsonUserState = BuildJsonUserState(channel, true); if (jsonUserState != "") { retJsonUserState = string.Format("{{{0}}}", jsonUserState); } return retJsonUserState; } private bool DeleteLocalUserState (string channel) { bool userStateDeleted = false; if (_channelLocalUserState.ContainsKey (channel)) { Dictionary<string, object> returnedUserState = null; userStateDeleted = _channelLocalUserState.TryRemove (channel, out returnedUserState); } return userStateDeleted; } private string BuildJsonUserState (string channel, bool local) { Dictionary<string, object> userStateDictionary = null; if (local) { if (_channelLocalUserState.ContainsKey(channel)) { userStateDictionary = _channelLocalUserState[channel]; } } else { if (_channelUserState.ContainsKey(channel)) { userStateDictionary = _channelUserState[channel]; } } StringBuilder jsonStateBuilder = new StringBuilder (); if (userStateDictionary != null) { string[] userStateKeys = userStateDictionary.Keys.ToArray<string> (); for (int keyIndex = 0; keyIndex < userStateKeys.Length; keyIndex++) { string useStateKey = userStateKeys [keyIndex]; object userStateValue = userStateDictionary[useStateKey]; if (userStateValue == null) { jsonStateBuilder.AppendFormat("\"{0}\":{1}", useStateKey, string.Format("\"{0}\"", "null")); } else { jsonStateBuilder.AppendFormat("\"{0}\":{1}", useStateKey, (userStateValue.GetType().ToString() == "System.String") ? string.Format("\"{0}\"", userStateValue) : userStateValue); } if (keyIndex < userStateKeys.Length - 1) { jsonStateBuilder.Append (","); } } } return jsonStateBuilder.ToString(); } private string BuildJsonUserState (string[] channels, bool local) { string retJsonUserState = ""; StringBuilder jsonStateBuilder = new StringBuilder (); if (channels != null) { for (int index = 0; index < channels.Length; index++) { string currentJsonState = BuildJsonUserState(channels[index].ToString(), local); if (!string.IsNullOrEmpty(currentJsonState)) { currentJsonState = string.Format("\"{0}\":{{{1}}}", channels[index].ToString(), currentJsonState); if (jsonStateBuilder.Length > 0) { jsonStateBuilder.Append(","); } jsonStateBuilder.Append(currentJsonState); } } if (jsonStateBuilder.Length > 0) { retJsonUserState = string.Format("{{{0}}}", jsonStateBuilder.ToString()); } } return retJsonUserState; } private string SetLocalUserState (string channel, string userStateKey, int userStateValue) { return AddOrUpdateOrDeleteLocalUserState (channel, userStateKey, userStateValue); } private string SetLocalUserState(string channel, string userStateKey, double userStateValue) { return AddOrUpdateOrDeleteLocalUserState (channel, userStateKey, userStateValue); } private string SetLocalUserState(string channel, string userStateKey, string userStateValue) { return AddOrUpdateOrDeleteLocalUserState (channel, userStateKey, userStateValue); } internal string GetLocalUserState(string channel) { string retJsonUserState = ""; StringBuilder jsonStateBuilder = new StringBuilder(); jsonStateBuilder.Append(BuildJsonUserState(channel, false)); if (jsonStateBuilder.Length > 0) { retJsonUserState = string.Format("{{{0}}}", jsonStateBuilder.ToString()); } return retJsonUserState; } internal void SetUserState<T>(string channel, string uuid, string jsonUserState, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty(channel) || string.IsNullOrEmpty(channel.Trim())) { throw new ArgumentException("Missing Channel"); } if (string.IsNullOrEmpty(jsonUserState) || string.IsNullOrEmpty(jsonUserState.Trim())) { throw new ArgumentException("Missing User State"); } if (userCallback == null) { throw new ArgumentException("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException("Missing Json Pluggable Library for Pubnub Instance"); } if (!_jsonPluggableLibrary.IsDictionaryCompatible(jsonUserState)) { throw new MissingMemberException("Missing json format for user state"); } else { Dictionary<string, object> deserializeUserState = _jsonPluggableLibrary.DeserializeToDictionaryOfObject(jsonUserState); if (deserializeUserState == null) { throw new MissingMemberException("Missing json format user state"); } else { string oldJsonState = GetLocalUserState(channel); if (oldJsonState == jsonUserState) { string message = "No change in User State"; CallErrorCallback(PubnubErrorSeverity.Info, PubnubMessageSource.Client, channel, errorCallback, message, PubnubErrorCode.UserStateUnchanged, null, null); return; } } } SharedSetUserState(channel, uuid, jsonUserState, userCallback, errorCallback); } internal void SetUserState<T>(string channel, string uuid, KeyValuePair<string, object> keyValuePair, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty(channel) || string.IsNullOrEmpty(channel.Trim())) { throw new ArgumentException("Missing Channel"); } if (userCallback == null) { throw new ArgumentException("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException("Missing errorCallback"); } string key = keyValuePair.Key; int valueInt; double valueDouble; string currentUserState = ""; string oldJsonState = GetLocalUserState(channel); if (keyValuePair.Value == null) { currentUserState = SetLocalUserState(channel, key, null); } else if (Int32.TryParse(keyValuePair.Value.ToString(), out valueInt)) { currentUserState = SetLocalUserState(channel, key, valueInt); } else if (Double.TryParse(keyValuePair.Value.ToString(), out valueDouble)) { currentUserState = SetLocalUserState(channel, key, valueDouble); } else { currentUserState = SetLocalUserState(channel, key, keyValuePair.Value.ToString()); } if (oldJsonState == currentUserState) { string message = "No change in User State"; CallErrorCallback(PubnubErrorSeverity.Info, PubnubMessageSource.Client, channel, errorCallback, message, PubnubErrorCode.UserStateUnchanged, null, null); return; } if (currentUserState.Trim() == "") { currentUserState = "{}"; } SharedSetUserState<T>(channel, uuid, currentUserState, userCallback, errorCallback); } private void SharedSetUserState<T>(string channel, string uuid, string jsonUserState, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty(uuid)) { VerifyOrSetSessionUUID(); uuid = this.sessionUUID; } Dictionary<string, object> deserializeUserState = _jsonPluggableLibrary.DeserializeToDictionaryOfObject(jsonUserState); if (_channelUserState != null) { _channelUserState.AddOrUpdate(channel.Trim(), deserializeUserState, (oldState, newState) => deserializeUserState); } if (_channelLocalUserState != null) { _channelLocalUserState.AddOrUpdate(channel.Trim(), deserializeUserState, (oldState, newState) => deserializeUserState); } Uri request = BuildSetUserStateRequest(channel, uuid, jsonUserState); RequestState<T> requestState = new RequestState<T>(); requestState.Channels = new string[] { channel }; requestState.Type = ResponseType.SetUserState; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; UrlProcessRequest<T>(request, requestState); //bounce the long-polling subscribe requests to update user state TerminateCurrentSubscriberRequest(); } internal void GetUserState<T> (string channel, string uuid, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (channel) || string.IsNullOrEmpty (channel.Trim ())) { throw new ArgumentException ("Missing Channel"); } if (userCallback == null) { throw new ArgumentException ("Missing userCallback"); } if (errorCallback == null) { throw new ArgumentException ("Missing errorCallback"); } if (_jsonPluggableLibrary == null) { throw new NullReferenceException ("Missing Json Pluggable Library for Pubnub Instance"); } if (string.IsNullOrEmpty (uuid)) { VerifyOrSetSessionUUID (); uuid = this.sessionUUID; } Uri request = BuildGetUserStateRequest (channel, uuid); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = new string[] { channel }; requestState.Type = ResponseType.GetUserState; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; UrlProcessRequest<T> (request, requestState); } private Uri BuildSetUserStateRequest (string channel, string uuid, string jsonUserState) { setUserStateparameters = string.Format ("?state={0}", EncodeUricomponent (jsonUserState, ResponseType.SetUserState, false)); List<string> url = new List<string> (); url.Add ("v2"); url.Add ("presence"); url.Add ("sub_key"); url.Add (this.subscribeKey); url.Add ("channel"); url.Add (channel); url.Add ("uuid"); url.Add (uuid); url.Add ("data"); return BuildRestApiRequest<Uri> (url, ResponseType.SetUserState); } private Uri BuildGetUserStateRequest (string channel, string uuid) { List<string> url = new List<string> (); url.Add ("v2"); url.Add ("presence"); url.Add ("sub_key"); url.Add (this.subscribeKey); url.Add ("channel"); url.Add (channel); url.Add ("uuid"); url.Add (uuid); return BuildRestApiRequest<Uri> (url, ResponseType.GetUserState); } #endregion #region "Exception handlers" protected void UrlRequestCommonExceptionHandler<T> (ResponseType type, string[] channels, bool requestTimeout, Action<T> userCallback, Action<T> connectCallback, Action<PubnubClientError> errorCallback, bool resumeOnReconnect) { if (type == ResponseType.Subscribe || type == ResponseType.Presence) { MultiplexExceptionHandler<T> (type, channels, userCallback, connectCallback, errorCallback, false, resumeOnReconnect); } else if (type == ResponseType.Publish) { PublishExceptionHandler<T> (channels [0], requestTimeout, errorCallback); } else if (type == ResponseType.Here_Now) { HereNowExceptionHandler<T> (channels [0], requestTimeout, errorCallback); } else if (type == ResponseType.DetailedHistory) { DetailedHistoryExceptionHandler<T> (channels [0], requestTimeout, errorCallback); } else if (type == ResponseType.Time) { TimeExceptionHandler<T> (requestTimeout, errorCallback); } else if (type == ResponseType.Leave) { //no action at this time } else if (type == ResponseType.PresenceHeartbeat) { //no action at this time } else if (type == ResponseType.GrantAccess || type == ResponseType.AuditAccess || type == ResponseType.RevokeAccess) { } else if (type == ResponseType.GetUserState) { GetUserStateExceptionHandler<T> (channels [0], requestTimeout, errorCallback); } else if (type == ResponseType.SetUserState) { SetUserStateExceptionHandler<T> (channels [0], requestTimeout, errorCallback); } else if (type == ResponseType.GlobalHere_Now) { GlobalHereNowExceptionHandler<T> (requestTimeout, errorCallback); } else if (type == ResponseType.Where_Now) { WhereNowExceptionHandler<T> (channels [0], requestTimeout, errorCallback); } } protected void MultiplexExceptionHandler<T> (ResponseType type, string[] channels, Action<T> userCallback, Action<T> connectCallback, Action<PubnubClientError> errorCallback, bool reconnectMaxTried, bool resumeOnReconnect) { string channel = ""; if (channels != null) { channel = string.Join (",", channels); } if (reconnectMaxTried) { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, MAX retries reached. Exiting the subscribe for channel(s) = {1}", DateTime.Now.ToString (), channel), LoggingMethod.LevelInfo); string[] activeChannels = multiChannelSubscribe.Keys.ToArray<string> (); MultiChannelUnSubscribeInit<T> (ResponseType.Unsubscribe, string.Join (",", activeChannels), null, null, null, null); string[] subscribeChannels = activeChannels.Where (filterChannel => !filterChannel.Contains ("-pnpres")).ToArray (); string[] presenceChannels = activeChannels.Where (filterChannel => filterChannel.Contains ("-pnpres")).ToArray (); if (subscribeChannels != null && subscribeChannels.Length > 0) { for (int index = 0; index < subscribeChannels.Length; index++) { string message = string.Format ("Unsubscribed after {0} failed retries", _pubnubNetworkCheckRetries); string activeChannel = subscribeChannels [index].ToString (); PubnubChannelCallbackKey callbackKey = new PubnubChannelCallbackKey (); callbackKey.Channel = activeChannel; callbackKey.Type = type; if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey (callbackKey)) { PubnubChannelCallback<T> currentPubnubCallback = channelCallbacks [callbackKey] as PubnubChannelCallback<T>; if (currentPubnubCallback != null && currentPubnubCallback.Callback != null) { CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, activeChannel, currentPubnubCallback.ErrorCallback, message, PubnubErrorCode.UnsubscribedAfterMaxRetries, null, null); } } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Subscribe JSON network error response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); } } if (presenceChannels != null && presenceChannels.Length > 0) { for (int index = 0; index < presenceChannels.Length; index++) { string message = string.Format ("Presence Unsubscribed after {0} failed retries", _pubnubNetworkCheckRetries); string activeChannel = presenceChannels [index].ToString (); PubnubChannelCallbackKey callbackKey = new PubnubChannelCallbackKey (); callbackKey.Channel = activeChannel; callbackKey.Type = type; if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey (callbackKey)) { PubnubChannelCallback<T> currentPubnubCallback = channelCallbacks [callbackKey] as PubnubChannelCallback<T>; if (currentPubnubCallback != null && currentPubnubCallback.Callback != null) { CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, activeChannel, currentPubnubCallback.ErrorCallback, message, PubnubErrorCode.PresenceUnsubscribedAfterMaxRetries, null, null); } } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Presence-Subscribe JSON network error response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); } } } else { List<object> result = new List<object> (); result.Add ("0"); if (resumeOnReconnect) { result.Add (0); //send 0 time token to enable presence event } else { result.Add (lastSubscribeTimetoken); //get last timetoken } result.Add (channels); //send channel name MultiplexInternalCallback<T> (type, result, userCallback, connectCallback, errorCallback); } } private void PublishExceptionHandler<T> (string channelName, bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, JSON publish response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, channelName, errorCallback, message, PubnubErrorCode.PublishOperationTimeout, null, null); } } private void PAMAccessExceptionHandler<T> (string channelName, bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, PAMAccessExceptionHandler response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, channelName, errorCallback, message, PubnubErrorCode.PAMAccessOperationTimeout, null, null); } } private void WhereNowExceptionHandler<T> (string uuid, bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, WhereNowExceptionHandler response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, uuid, errorCallback, message, PubnubErrorCode.WhereNowOperationTimeout, null, null); } } private void HereNowExceptionHandler<T> (string channelName, bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, HereNowExceptionHandler response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, channelName, errorCallback, message, PubnubErrorCode.HereNowOperationTimeout, null, null); } } private void GlobalHereNowExceptionHandler<T> (bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, GlobalHereNowExceptionHandler response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, "", errorCallback, message, PubnubErrorCode.GlobalHereNowOperationTimeout, null, null); } } private void DetailedHistoryExceptionHandler<T> (string channelName, bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, DetailedHistoryExceptionHandler response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, channelName, errorCallback, message, PubnubErrorCode.DetailedHistoryOperationTimeout, null, null); } } private void TimeExceptionHandler<T> (bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, TimeExceptionHandler response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, "", errorCallback, message, PubnubErrorCode.TimeOperationTimeout, null, null); } } private void SetUserStateExceptionHandler<T> (string channelName, bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, SetUserStateExceptionHandler response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, channelName, errorCallback, message, PubnubErrorCode.SetUserStateTimeout, null, null); } } private void GetUserStateExceptionHandler<T> (string channelName, bool requestTimeout, Action<PubnubClientError> errorCallback) { if (requestTimeout) { string message = (requestTimeout) ? "Operation Timeout" : "Network connnect error"; LoggingMethod.WriteToLog (string.Format ("DateTime {0}, GetUserStateExceptionHandler response={1}", DateTime.Now.ToString (), message), LoggingMethod.LevelInfo); CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, channelName, errorCallback, message, PubnubErrorCode.GetUserStateTimeout, null, null); } } #endregion #region "Callbacks" protected virtual bool CheckInternetConnectionStatus<T> (bool systemActive, Action<PubnubClientError> errorCallback, string[] channels) { return ClientNetworkStatus.CheckInternetStatus<T> (pubnetSystemActive, errorCallback, channels); } protected void OnPresenceHeartbeatIntervalTimeout<T> (System.Object presenceHeartbeatState) { //Make presence heartbeat call RequestState<T> currentState = presenceHeartbeatState as RequestState<T>; if (currentState != null && currentState.Channels != null) { string channel = (currentState.Channels != null) ? string.Join (",", currentState.Channels) : ""; bool networkConnection; if (_pubnubUnitTest is IPubnubUnitTest && _pubnubUnitTest.EnableStubTest) { networkConnection = true; } else { networkConnection = CheckInternetConnectionStatus<T> (pubnetSystemActive, currentState.ErrorCallback, currentState.Channels); if (networkConnection) { string[] subscriberChannels = currentState.Channels.Where (s => s.Contains ("-pnpres") == false).ToArray (); if (subscriberChannels != null && subscriberChannels.Length > 0) { Uri request = BuildPresenceHeartbeatRequest (subscriberChannels); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = currentState.Channels; requestState.Type = ResponseType.PresenceHeartbeat; requestState.UserCallback = null; requestState.ErrorCallback = currentState.ErrorCallback; requestState.Reconnect = false; requestState.Response = null; UrlProcessRequest<T> (request, requestState); } } } } } protected void OnPubnubLocalClientHeartBeatTimeoutCallback<T> (System.Object heartbeatState) { RequestState<T> currentState = heartbeatState as RequestState<T>; if (currentState != null) { string channel = (currentState.Channels != null) ? string.Join(",", currentState.Channels) : ""; if (channelInternetStatus.ContainsKey(channel) && (currentState.Type == ResponseType.Subscribe || currentState.Type == ResponseType.Presence || currentState.Type == ResponseType.PresenceHeartbeat) && overrideTcpKeepAlive) { bool networkConnection; if (_pubnubUnitTest is IPubnubUnitTest && _pubnubUnitTest.EnableStubTest) { networkConnection = true; } else { networkConnection = CheckInternetConnectionStatus<T>(pubnetSystemActive, currentState.ErrorCallback, currentState.Channels); } channelInternetStatus[channel] = networkConnection; LoggingMethod.WriteToLog(string.Format ("DateTime: {0}, OnPubnubLocalClientHeartBeatTimeoutCallback - Internet connection = {1}", DateTime.Now.ToString (), networkConnection), LoggingMethod.LevelVerbose); if (!networkConnection) { TerminatePendingWebRequest(currentState); } } } } /// <summary> /// Check the response of the REST API and call for re-subscribe /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="multiplexResult"></param> /// <param name="userCallback"></param> /// <param name="connectCallback"></param> /// <param name="errorCallback"></param> protected void MultiplexInternalCallback<T> (ResponseType type, object multiplexResult, Action<T> userCallback, Action<T> connectCallback, Action<PubnubClientError> errorCallback) { List<object> message = multiplexResult as List<object>; string[] channels = null; if (message != null && message.Count >= 3) { if (message [message.Count - 1] is string[]) { channels = message [message.Count - 1] as string[]; } else { channels = message [message.Count - 1].ToString ().Split (',') as string[]; } } else { LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Lost Channel Name for resubscribe", DateTime.Now.ToString ()), LoggingMethod.LevelError); return; } if (message != null && message.Count >= 3) { MultiChannelSubscribeRequest<T> (type, channels, (object)message [1], userCallback, connectCallback, errorCallback, false); } } private void ResponseToConnectCallback<T> (List<object> result, ResponseType type, string[] channels, Action<T> connectCallback) { //Check callback exists and make sure previous timetoken = 0 if (channels != null && connectCallback != null && channels.Length > 0) { IEnumerable<string> newChannels = from channel in multiChannelSubscribe where channel.Value == 0 select channel.Key; foreach (string channel in newChannels) { string jsonString = ""; List<object> connectResult = new List<object> (); switch (type) { case ResponseType.Subscribe: jsonString = string.Format ("[1, \"Connected\"]"); connectResult = _jsonPluggableLibrary.DeserializeToListOfObject (jsonString); connectResult.Add (channel); PubnubChannelCallbackKey callbackKey = new PubnubChannelCallbackKey (); callbackKey.Channel = channel; callbackKey.Type = type; if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey (callbackKey)) { PubnubChannelCallback<T> currentPubnubCallback = channelCallbacks [callbackKey] as PubnubChannelCallback<T>; if (currentPubnubCallback != null && currentPubnubCallback.ConnectCallback != null) { GoToCallback<T> (connectResult, currentPubnubCallback.ConnectCallback); } } break; case ResponseType.Presence: jsonString = string.Format ("[1, \"Presence Connected\"]"); connectResult = _jsonPluggableLibrary.DeserializeToListOfObject (jsonString); connectResult.Add (channel.Replace ("-pnpres", "")); PubnubChannelCallbackKey pCallbackKey = new PubnubChannelCallbackKey (); pCallbackKey.Channel = channel; pCallbackKey.Type = type; if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey (pCallbackKey)) { PubnubChannelCallback<T> currentPubnubCallback = channelCallbacks [pCallbackKey] as PubnubChannelCallback<T>; if (currentPubnubCallback != null && currentPubnubCallback.ConnectCallback != null) { GoToCallback<T> (connectResult, currentPubnubCallback.ConnectCallback); } } break; default: break; } } } } protected abstract void ProcessResponseCallbackExceptionHandler<T> (Exception ex, RequestState<T> asynchRequestState); protected abstract bool HandleWebException<T> (WebException webEx, RequestState<T> asynchRequestState, string channel); protected abstract void ProcessResponseCallbackWebExceptionHandler<T> (WebException webEx, RequestState<T> asynchRequestState, string channel); protected void ProcessResponseCallbacks<T> (List<object> result, RequestState<T> asynchRequestState) { if (result != null && result.Count >= 1 && asynchRequestState.UserCallback != null) { ResponseToConnectCallback<T> (result, asynchRequestState.Type, asynchRequestState.Channels, asynchRequestState.ConnectCallback); ResponseToUserCallback<T> (result, asynchRequestState.Type, asynchRequestState.Channels, asynchRequestState.UserCallback); } } //#if (!UNITY_IOS) //TODO:refactor protected abstract void UrlProcessResponseCallback<T> (IAsyncResult asynchronousResult); //#endif //TODO:refactor private void ResponseToUserCallback<T> (List<object> result, ResponseType type, string[] channels, Action<T> userCallback) { string[] messageChannels; switch (type) { case ResponseType.Subscribe: case ResponseType.Presence: var messages = (from item in result select item as object).ToArray (); if (messages != null && messages.Length > 0) { object[] messageList = messages [0] as object[]; #if (USE_MiniJSON) int i=0; foreach (object o in result){ if(i==0) { IList collection = (IList)o; messageList = new object[collection.Count]; collection.CopyTo(messageList, 0); } i++; } #endif messageChannels = messages [2].ToString ().Split (','); if (messageList != null && messageList.Length > 0) { for (int messageIndex = 0; messageIndex < messageList.Length; messageIndex++) { string currentChannel = (messageChannels.Length == 1) ? (string)messageChannels [0] : (string)messageChannels [messageIndex]; List<object> itemMessage = new List<object> (); if (currentChannel.Contains ("-pnpres")) { itemMessage.Add (messageList [messageIndex]); } else { //decrypt the subscriber message if cipherkey is available if (this.cipherKey.Length > 0) { PubnubCrypto aes = new PubnubCrypto (this.cipherKey); string decryptMessage = aes.Decrypt (messageList [messageIndex].ToString ()); object decodeMessage = (decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : _jsonPluggableLibrary.DeserializeToObject (decryptMessage); itemMessage.Add (decodeMessage); } else { itemMessage.Add (messageList [messageIndex]); } } itemMessage.Add (messages [1].ToString ()); itemMessage.Add (currentChannel.Replace ("-pnpres", "")); PubnubChannelCallbackKey callbackKey = new PubnubChannelCallbackKey (); callbackKey.Channel = currentChannel; callbackKey.Type = (currentChannel.LastIndexOf ("-pnpres") == -1) ? ResponseType.Subscribe : ResponseType.Presence; if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey (callbackKey)) { if ((typeof(T) == typeof(string) && channelCallbacks [callbackKey].GetType().Name.Contains ("[System.String]")) || (typeof(T) == typeof(object) && channelCallbacks [callbackKey].GetType().Name.Contains ("[System.Object]"))) { PubnubChannelCallback<T> currentPubnubCallback = channelCallbacks [callbackKey] as PubnubChannelCallback<T>; if (currentPubnubCallback != null && currentPubnubCallback.Callback != null) { GoToCallback<T>(itemMessage, currentPubnubCallback.Callback); } } else if (channelCallbacks [callbackKey].GetType ().FullName.Contains("[System.String")) { PubnubChannelCallback<string> retryPubnubCallback = channelCallbacks [callbackKey] as PubnubChannelCallback<string>; if (retryPubnubCallback != null && retryPubnubCallback.Callback != null) { GoToCallback(itemMessage, retryPubnubCallback.Callback); } } else if (channelCallbacks[callbackKey].GetType().FullName.Contains("[System.Object")) { PubnubChannelCallback<object> retryPubnubCallback = channelCallbacks[callbackKey] as PubnubChannelCallback<object>; if (retryPubnubCallback != null && retryPubnubCallback.Callback != null) { GoToCallback(itemMessage, retryPubnubCallback.Callback); } } } } } } break; case ResponseType.Publish: if (result != null && result.Count > 0) { GoToCallback<T> (result, userCallback); } break; case ResponseType.DetailedHistory: if (result != null && result.Count > 0) { GoToCallback<T> (result, userCallback); } break; case ResponseType.Here_Now: if (result != null && result.Count > 0) { GoToCallback<T> (result, userCallback); } break; case ResponseType.GlobalHere_Now: if (result != null && result.Count > 0) { GoToCallback<T> (result, userCallback); } break; case ResponseType.Where_Now: if (result != null && result.Count > 0) { GoToCallback<T> (result, userCallback); } break; case ResponseType.Time: if (result != null && result.Count > 0) { GoToCallback<T> (result, userCallback); } break; case ResponseType.Leave: //No response to callback break; case ResponseType.GrantAccess: case ResponseType.AuditAccess: case ResponseType.RevokeAccess: case ResponseType.GetUserState: case ResponseType.SetUserState: if (result != null && result.Count > 0) { GoToCallback<T> (result, userCallback); } break; default: break; } } private void JsonResponseToCallback<T> (List<object> result, Action<T> callback) { string callbackJson = ""; if (typeof(T) == typeof(string)) { callbackJson = _jsonPluggableLibrary.SerializeToJsonString (result); Action<string> castCallback = callback as Action<string>; castCallback (callbackJson); } } private void JsonResponseToCallback<T> (object result, Action<T> callback) { string callbackJson = ""; if (typeof(T) == typeof(string)) { callbackJson = _jsonPluggableLibrary.SerializeToJsonString (result); Action<string> castCallback = callback as Action<string>; castCallback (callbackJson); } } protected void GoToCallback<T> (object result, Action<T> Callback) { if (Callback != null) { if (typeof(T) == typeof(string)) { JsonResponseToCallback (result, Callback); } else { Callback ((T)(object)result); } } } protected void GoToCallback (object result, Action<string> Callback) { if (Callback != null) { JsonResponseToCallback (result, Callback); } } protected void GoToCallback (object result, Action<object> Callback) { if (Callback != null) { Callback (result); } } protected void GoToCallback(PubnubClientError error, Action<PubnubClientError> Callback) { if (Callback != null && error != null) { if ((int)error.Severity <= (int)_errorLevel) { //Checks whether the error serverity falls in the range of error filter level //Do not send 107 = PubnubObjectDisposedException //Do not send 105 = WebRequestCancelled //Do not send 130 = PubnubClientMachineSleep if (error.StatusCode != 107 && error.StatusCode != 105 && error.StatusCode != 130 && error.StatusCode != 4040) //Error Code that should not go out { Callback (error); } } } } #endregion #region "Simulate network fail and machine sleep" /// <summary> /// FOR TESTING ONLY - To Enable Simulation of Network Non-Availability /// </summary> public void EnableSimulateNetworkFailForTestingOnly () { ClientNetworkStatus.SimulateNetworkFailForTesting = true; PubnubWebRequest.SimulateNetworkFailForTesting = true; } /// <summary> /// FOR TESTING ONLY - To Disable Simulation of Network Non-Availability /// </summary> public void DisableSimulateNetworkFailForTestingOnly () { ClientNetworkStatus.SimulateNetworkFailForTesting = false; PubnubWebRequest.SimulateNetworkFailForTesting = false; } protected abstract void GeneratePowerSuspendEvent (); protected abstract void GeneratePowerResumeEvent (); public void EnableMachineSleepModeForTestingOnly () { GeneratePowerSuspendEvent (); pubnetSystemActive = false; } public void DisableMachineSleepModeForTestingOnly () { GeneratePowerResumeEvent (); pubnetSystemActive = true; } #endregion #region "Helpers" protected void VerifyOrSetSessionUUID () { if (string.IsNullOrEmpty (this.sessionUUID) || string.IsNullOrEmpty (this.sessionUUID.Trim ())) { this.sessionUUID = Guid.NewGuid ().ToString (); } } protected bool IsUnsafe (char ch, bool ignoreComma) { if (ignoreComma) { return " ~`!@#$%^&*()+=[]\\{}|;':\"/<>?".IndexOf (ch) >= 0; } else { return " ~`!@#$%^&*()+=[]\\{}|;':\",/<>?".IndexOf (ch) >= 0; } } public virtual Guid GenerateGuid () { return Guid.NewGuid (); } protected int GetTimeoutInSecondsForResponseType (ResponseType type) { int timeout; if (type == ResponseType.Subscribe || type == ResponseType.Presence) { timeout = _pubnubWebRequestCallbackIntervalInSeconds; } else { timeout = _pubnubOperationTimeoutIntervalInSeconds; } return timeout; } public static long TranslateDateTimeToSeconds (DateTime dotNetUTCDateTime) { TimeSpan timeSpan = dotNetUTCDateTime - new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long timeStamp = Convert.ToInt64 (timeSpan.TotalSeconds); return timeStamp; } /// <summary> /// Convert the UTC/GMT DateTime to Unix Nano Seconds format /// </summary> /// <param name="dotNetUTCDateTime"></param> /// <returns></returns> public static long TranslateDateTimeToPubnubUnixNanoSeconds (DateTime dotNetUTCDateTime) { TimeSpan timeSpan = dotNetUTCDateTime - new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long timeStamp = Convert.ToInt64 (timeSpan.TotalSeconds) * 10000000; return timeStamp; } /// <summary> /// Convert the Unix Nano Seconds format time to UTC/GMT DateTime /// </summary> /// <param name="unixNanoSecondTime"></param> /// <returns></returns> public static DateTime TranslatePubnubUnixNanoSecondsToDateTime (long unixNanoSecondTime) { double timeStamp = unixNanoSecondTime / 10000000; DateTime dateTime = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds (timeStamp); return dateTime; } private bool IsPresenceChannel (string channel) { if (channel.LastIndexOf ("-pnpres") > 0) { return true; } else { return false; } } private string[] GetCurrentSubscriberChannels () { string[] channels = null; if (multiChannelSubscribe != null && multiChannelSubscribe.Keys.Count > 0) { channels = multiChannelSubscribe.Keys.ToArray<string> (); } return channels; } /// <summary> /// Retrieves the channel name from the url components /// </summary> /// <param name="urlComponents"></param> /// <param name="type"></param> /// <returns></returns> private string GetChannelName (List<string> urlComponents, ResponseType type) { string channelName = ""; switch (type) { case ResponseType.Subscribe: case ResponseType.Presence: channelName = urlComponents [2]; break; case ResponseType.Publish: channelName = urlComponents [4]; break; case ResponseType.DetailedHistory: channelName = urlComponents [5]; break; case ResponseType.Here_Now: channelName = urlComponents [5]; break; case ResponseType.Leave: channelName = urlComponents [5]; break; case ResponseType.Where_Now: channelName = urlComponents [5]; break; default: break; } ; return channelName; } #endregion #region "PAM" private Uri BuildGrantAccessRequest(string channel, string authenticationKey, bool read, bool write, int ttl) { string signature = "0"; long timeStamp = TranslateDateTimeToSeconds (DateTime.UtcNow); string queryString = ""; StringBuilder queryStringBuilder = new StringBuilder (); if (!string.IsNullOrEmpty(authenticationKey)) { queryStringBuilder.AppendFormat("auth={0}", EncodeUricomponent(authenticationKey, ResponseType.GrantAccess, false)); } if (!string.IsNullOrEmpty(channel)) { queryStringBuilder.AppendFormat ("{0}channel={1}", (queryStringBuilder.Length > 0) ? "&" : "", EncodeUricomponent(channel, ResponseType.GrantAccess, false)); } queryStringBuilder.AppendFormat ("{0}", (queryStringBuilder.Length > 0) ? "&" : ""); queryStringBuilder.AppendFormat ("r={0}&timestamp={1}{2}&w={3}", Convert.ToInt32 (read), timeStamp.ToString (), (ttl > -1) ? "&ttl=" + ttl.ToString () : "", Convert.ToInt32 (write)); if (this.secretKey.Length > 0) { StringBuilder string_to_sign = new StringBuilder(); string_to_sign.Append (this.subscribeKey) .Append("\n") .Append(this.publishKey) .Append("\n") .Append("grant") .Append("\n") .Append(queryStringBuilder.ToString()); PubnubCrypto pubnubCrypto = new PubnubCrypto (this.cipherKey); signature = pubnubCrypto.PubnubAccessManagerSign (this.secretKey, string_to_sign.ToString()); queryString = string.Format("signature={0}&{1}", signature, queryStringBuilder.ToString()); } parameters = ""; parameters += "?" + queryString; List<string> url = new List<string>(); url.Add("v1"); url.Add("auth"); url.Add("grant"); url.Add("sub-key"); url.Add(this.subscribeKey); return BuildRestApiRequest<Uri>(url, ResponseType.GrantAccess); } private Uri BuildAuditAccessRequest(string channel, string authenticationKey) { string signature = "0"; long timeStamp = ((_pubnubUnitTest == null) || (_pubnubUnitTest is IPubnubUnitTest && !_pubnubUnitTest.EnableStubTest)) ? TranslateDateTimeToSeconds (DateTime.UtcNow) : TranslateDateTimeToSeconds (new DateTime (2013, 01, 01)); string queryString = ""; StringBuilder queryStringBuilder = new StringBuilder (); if (!string.IsNullOrEmpty(authenticationKey)) { queryStringBuilder.AppendFormat("auth={0}", EncodeUricomponent(authenticationKey, ResponseType.AuditAccess, false)); } if (!string.IsNullOrEmpty (channel)) { queryStringBuilder.AppendFormat ("{0}channel={1}", (queryStringBuilder.Length > 0) ? "&" : "", EncodeUricomponent (channel, ResponseType.AuditAccess, false)); } queryStringBuilder.AppendFormat ("{0}timestamp={1}", (queryStringBuilder.Length > 0) ? "&" : "", timeStamp.ToString ()); if (this.secretKey.Length > 0) { StringBuilder string_to_sign = new StringBuilder (); string_to_sign.Append (this.subscribeKey) .Append ("\n") .Append (this.publishKey) .Append ("\n") .Append ("audit") .Append ("\n") .Append (queryStringBuilder.ToString ()); PubnubCrypto pubnubCrypto = new PubnubCrypto (this.cipherKey); signature = pubnubCrypto.PubnubAccessManagerSign (this.secretKey, string_to_sign.ToString ()); queryString = string.Format ("signature={0}&{1}", signature, queryStringBuilder.ToString ()); } parameters = ""; parameters += "?" + queryString; List<string> url = new List<string> (); url.Add ("v1"); url.Add ("auth"); url.Add ("audit"); url.Add ("sub-key"); url.Add (this.subscribeKey); return BuildRestApiRequest<Uri> (url, ResponseType.AuditAccess); } public bool GrantAccess<T> (string channel, bool read, bool write, Action<T> userCallback, Action<PubnubClientError> errorCallback) { return GrantAccess (channel, "", read, write, -1, userCallback, errorCallback); } public bool GrantAccess<T>(string channel, bool read, bool write, int ttl, Action<T> userCallback, Action<PubnubClientError> errorCallback) { return GrantAccess<T>(channel, "", read, write, ttl, userCallback, errorCallback); } public bool GrantAccess<T>(string channel, string authenticationKey, bool read, bool write, Action<T> userCallback, Action<PubnubClientError> errorCallback) { return GrantAccess(channel, authenticationKey, read, write, -1, userCallback, errorCallback); } public bool GrantAccess<T> (string channel, string authenticationKey, bool read, bool write, int ttl, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty (this.secretKey) || string.IsNullOrEmpty (this.secretKey.Trim ()) || this.secretKey.Length <= 0) { throw new MissingMemberException("Invalid secret key"); } Uri request = BuildGrantAccessRequest(channel, authenticationKey, read, write, ttl); RequestState<T> requestState = new RequestState<T> (); requestState.Channels = new string[] { channel }; requestState.Type = ResponseType.GrantAccess; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; return UrlProcessRequest<T> (request, requestState); } public bool GrantPresenceAccess<T> (string channel, bool read, bool write, Action<T> userCallback, Action<PubnubClientError> errorCallback) { return GrantPresenceAccess (channel, "", read, write, -1, userCallback, errorCallback); } public bool GrantPresenceAccess<T>(string channel, bool read, bool write, int ttl, Action<T> userCallback, Action<PubnubClientError> errorCallback) { return GrantPresenceAccess(channel, "", read, write, ttl, userCallback, errorCallback); } public bool GrantPresenceAccess<T>(string channel, string authenticationKey, bool read, bool write, Action<T> userCallback, Action<PubnubClientError> errorCallback) { return GrantPresenceAccess<T>(channel, authenticationKey, read, write, -1, userCallback, errorCallback); } public bool GrantPresenceAccess<T>(string channel, string authenticationKey, bool read, bool write, int ttl, Action<T> userCallback, Action<PubnubClientError> errorCallback) { string[] multiChannels = channel.Split (','); if (multiChannels.Length > 0) { for (int index = 0; index < multiChannels.Length; index++) { if (!string.IsNullOrEmpty (multiChannels [index]) && multiChannels [index].Trim ().Length > 0) { multiChannels [index] = string.Format ("{0}-pnpres", multiChannels [index]); } else { throw new MissingMemberException("Invalid channel"); } } } string presenceChannel = string.Join (",", multiChannels); return GrantAccess(presenceChannel, authenticationKey, read, write, ttl, userCallback, errorCallback); } public void AuditAccess<T> (Action<T> userCallback, Action<PubnubClientError> errorCallback) { AuditAccess("", "", userCallback, errorCallback); } public void AuditAccess<T> (string channel, Action<T> userCallback, Action<PubnubClientError> errorCallback) { AuditAccess(channel, "", userCallback, errorCallback); } public void AuditAccess<T>(string channel, string authenticationKey, Action<T> userCallback, Action<PubnubClientError> errorCallback) { if (string.IsNullOrEmpty(this.secretKey) || string.IsNullOrEmpty(this.secretKey.Trim()) || this.secretKey.Length <= 0) { throw new MissingMemberException("Invalid secret key"); } Uri request = BuildAuditAccessRequest(channel, authenticationKey); RequestState<T> requestState = new RequestState<T>(); if (!string.IsNullOrEmpty(channel)) { requestState.Channels = new string[] { channel }; } requestState.Type = ResponseType.AuditAccess; requestState.UserCallback = userCallback; requestState.ErrorCallback = errorCallback; requestState.Reconnect = false; UrlProcessRequest<T>(request, requestState); } public void AuditPresenceAccess<T> (string channel, Action<T> userCallback, Action<PubnubClientError> errorCallback) { AuditPresenceAccess(channel, "", userCallback, errorCallback); } public void AuditPresenceAccess<T>(string channel, string authenticationKey, Action<T> userCallback, Action<PubnubClientError> errorCallback) { string[] multiChannels = channel.Split(','); if (multiChannels.Length > 0) { for (int index = 0; index < multiChannels.Length; index++) { multiChannels[index] = string.Format("{0}-pnpres", multiChannels[index]); } } string presenceChannel = string.Join(",", multiChannels); AuditAccess(presenceChannel, authenticationKey, userCallback, errorCallback); } #endregion #region "Response" protected void OnPubnubWebRequestTimeout<T> (object state, bool timeout) { if (timeout && state != null) { RequestState<T> currentState = state as RequestState<T>; if (currentState != null) { PubnubWebRequest request = currentState.Request; if (request != null) { string currentMultiChannel = (currentState.Channels == null) ? "" : string.Join (",", currentState.Channels); LoggingMethod.WriteToLog (string.Format ("DateTime: {0}, OnPubnubWebRequestTimeout: client request timeout reached.Request abort for channel = {1}", DateTime.Now.ToString (), currentMultiChannel), LoggingMethod.LevelInfo); currentState.Timeout = true; TerminatePendingWebRequest (currentState); } } else { LoggingMethod.WriteToLog (string.Format ("DateTime: {0}, OnPubnubWebRequestTimeout: client request timeout reached. However state is unknown", DateTime.Now.ToString ()), LoggingMethod.LevelError); } } } protected void OnPubnubWebRequestTimeout<T> (System.Object requestState) { RequestState<T> currentState = requestState as RequestState<T>; if (currentState != null && currentState.Response == null && currentState.Request != null) { currentState.Timeout = true; TerminatePendingWebRequest (currentState); LoggingMethod.WriteToLog (string.Format ("DateTime: {0}, **WP7 OnPubnubWebRequestTimeout**", DateTime.Now.ToString ()), LoggingMethod.LevelError); } } /// <summary> /// Gets the result by wrapping the json response based on the request /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="jsonString"></param> /// <param name="channels"></param> /// <param name="reconnect"></param> /// <param name="lastTimetoken"></param> /// <param name="errorCallback"></param> /// <returns></returns> protected List<object> WrapResultBasedOnResponseType<T> (ResponseType type, string jsonString, string[] channels, bool reconnect, long lastTimetoken, Action<PubnubClientError> errorCallback) { List<object> result = new List<object> (); try { string multiChannel = (channels != null) ? string.Join (",", channels) : ""; if (!string.IsNullOrEmpty (jsonString)) { if (!string.IsNullOrEmpty (jsonString)) { object deSerializedResult = _jsonPluggableLibrary.DeserializeToObject (jsonString); List<object> result1 = ((IEnumerable)deSerializedResult).Cast<object> ().ToList (); if (result1 != null && result1.Count > 0) { result = result1; } switch (type) { case ResponseType.Publish: result.Add (multiChannel); break; case ResponseType.History: if (this.cipherKey.Length > 0) { List<object> historyDecrypted = new List<object> (); PubnubCrypto aes = new PubnubCrypto (this.cipherKey); foreach (object message in result) { historyDecrypted.Add (aes.Decrypt (message.ToString ())); } History = historyDecrypted; } else { History = result; } break; case ResponseType.DetailedHistory: result = DecodeDecryptLoop (result, channels, errorCallback); result.Add (multiChannel); break; case ResponseType.Here_Now: Dictionary<string, object> dictionary = _jsonPluggableLibrary.DeserializeToDictionaryOfObject (jsonString); result = new List<object> (); result.Add (dictionary); result.Add (multiChannel); break; case ResponseType.GlobalHere_Now: Dictionary<string, object> globalHereNowDictionary = _jsonPluggableLibrary.DeserializeToDictionaryOfObject (jsonString); result = new List<object> (); result.Add (globalHereNowDictionary); break; case ResponseType.Where_Now: Dictionary<string, object> whereNowDictionary = _jsonPluggableLibrary.DeserializeToDictionaryOfObject (jsonString); result = new List<object> (); result.Add (whereNowDictionary); result.Add (multiChannel); break; case ResponseType.Time: break; case ResponseType.Subscribe: case ResponseType.Presence: result.Add (multiChannel); long receivedTimetoken = (result.Count > 1) ? Convert.ToInt64 (result [1].ToString ()) : 0; long minimumTimetoken = (multiChannelSubscribe.Count > 0) ? multiChannelSubscribe.Min (token => token.Value) : 0; long maximumTimetoken = (multiChannelSubscribe.Count > 0) ? multiChannelSubscribe.Max (token => token.Value) : 0; if (minimumTimetoken == 0 || lastTimetoken == 0) { if (maximumTimetoken == 0) { lastSubscribeTimetoken = receivedTimetoken; } else { if (!_enableResumeOnReconnect) { lastSubscribeTimetoken = receivedTimetoken; } else { //do nothing. keep last subscribe token } } } else { if (reconnect) { if (_enableResumeOnReconnect) { //do nothing. keep last subscribe token } else { lastSubscribeTimetoken = receivedTimetoken; } } else { lastSubscribeTimetoken = receivedTimetoken; } } break; case ResponseType.Leave: result.Add (multiChannel); break; case ResponseType.GrantAccess: case ResponseType.AuditAccess: case ResponseType.RevokeAccess: Dictionary<string, object> grantDictionary = _jsonPluggableLibrary.DeserializeToDictionaryOfObject (jsonString); result = new List<object> (); result.Add (grantDictionary); result.Add (multiChannel); break; case ResponseType.GetUserState: case ResponseType.SetUserState: Dictionary<string, object> userStateDictionary = _jsonPluggableLibrary.DeserializeToDictionaryOfObject (jsonString); result = new List<object> (); result.Add (userStateDictionary); result.Add (multiChannel); break; default: break; } ;//switch stmt end } } } catch (Exception ex) { if (channels != null) { if (type == ResponseType.Subscribe || type == ResponseType.Presence) { for (int index = 0; index < channels.Length; index++) { string activeChannel = channels [index].ToString (); PubnubChannelCallbackKey callbackKey = new PubnubChannelCallbackKey (); callbackKey.Channel = activeChannel; callbackKey.Type = type; if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey (callbackKey)) { PubnubChannelCallback<T> currentPubnubCallback = channelCallbacks [callbackKey] as PubnubChannelCallback<T>; if (currentPubnubCallback != null && currentPubnubCallback.ErrorCallback != null) { CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, activeChannel, currentPubnubCallback.ErrorCallback, ex, null, null); } } } } else { if (errorCallback != null) { CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, string.Join (",", channels), errorCallback, ex, null, null); } } } } return result; } #endregion #region "Build, process and send request" protected abstract void ForceCanonicalPathAndQuery (Uri requestUri); protected abstract PubnubWebRequest SetProxy<T> (PubnubWebRequest request); protected abstract PubnubWebRequest SetTimeout<T> (RequestState<T> pubnubRequestState, PubnubWebRequest request); protected virtual void TimerWhenOverrideTcpKeepAlive<T> (Uri requestUri, RequestState<T> pubnubRequestState) { //Eventhough heart-beat is disabled, run one time to check internet connection by setting dueTime=0 localClientHeartBeatTimer = new System.Threading.Timer ( new TimerCallback (OnPubnubLocalClientHeartBeatTimeoutCallback<T>), pubnubRequestState, 0, (-1 == _pubnubNetworkTcpCheckIntervalInSeconds) ? Timeout.Infinite : _pubnubNetworkTcpCheckIntervalInSeconds * 1000); channelLocalClientHeartbeatTimer.AddOrUpdate (requestUri, localClientHeartBeatTimer, (key, oldState) => localClientHeartBeatTimer); } protected abstract PubnubWebRequest SetServicePointSetTcpKeepAlive (PubnubWebRequest request); protected abstract void SendRequestAndGetResult<T> (Uri requestUri, RequestState<T> pubnubRequestState, PubnubWebRequest request); private bool UrlProcessRequest<T> (Uri requestUri, RequestState<T> pubnubRequestState) { string channel = ""; if (pubnubRequestState != null && pubnubRequestState.Channels != null) { channel = string.Join (",", pubnubRequestState.Channels); } try { if (!_channelRequest.ContainsKey (channel) && (pubnubRequestState.Type == ResponseType.Subscribe || pubnubRequestState.Type == ResponseType.Presence)) { return false; } // Create Request PubnubWebRequestCreator requestCreator = new PubnubWebRequestCreator (_pubnubUnitTest); PubnubWebRequest request = (PubnubWebRequest)requestCreator.Create (requestUri); request = SetProxy<T> (request); request = SetTimeout<T> (pubnubRequestState, request); pubnubRequestState.Request = request; if (pubnubRequestState.Type == ResponseType.Subscribe || pubnubRequestState.Type == ResponseType.Presence) { _channelRequest.AddOrUpdate (channel, pubnubRequestState.Request, (key, oldState) => pubnubRequestState.Request); } if (overrideTcpKeepAlive) { TimerWhenOverrideTcpKeepAlive (requestUri, pubnubRequestState); } else { request = SetServicePointSetTcpKeepAlive (request); } LoggingMethod.WriteToLog (string.Format ("DateTime {0}, Request={1}", DateTime.Now.ToString (), requestUri.ToString ()), LoggingMethod.LevelInfo); SendRequestAndGetResult (requestUri, pubnubRequestState, request); return true; } catch (System.Exception ex) { if (pubnubRequestState != null && pubnubRequestState.ErrorCallback != null) { string multiChannel = (pubnubRequestState.Channels != null) ? string.Join (",", pubnubRequestState.Channels) : ""; CallErrorCallback (PubnubErrorSeverity.Critical, PubnubMessageSource.Client, multiChannel, pubnubRequestState.ErrorCallback, ex, pubnubRequestState.Request, pubnubRequestState.Response); } LoggingMethod.WriteToLog (string.Format ("DateTime {0} Exception={1}", DateTime.Now.ToString (), ex.ToString ()), LoggingMethod.LevelError); UrlRequestCommonExceptionHandler<T> (pubnubRequestState.Type, pubnubRequestState.Channels, false, pubnubRequestState.UserCallback, pubnubRequestState.ConnectCallback, pubnubRequestState.ErrorCallback, false); return false; } } private Uri BuildRestApiRequest<T> (List<string> urlComponents, ResponseType type) { VerifyOrSetSessionUUID (); return BuildRestApiRequest<T> (urlComponents, type, this.sessionUUID); } private Uri BuildRestApiRequest<T> (List<string> urlComponents, ResponseType type, string uuid) { //bool queryParamExist = false; StringBuilder url = new StringBuilder (); if (string.IsNullOrEmpty (uuid)) { VerifyOrSetSessionUUID (); uuid = this.sessionUUID; } // Add http or https based on SSL flag if (this.ssl) { url.Append ("https://"); } else { url.Append ("http://"); } // Add Origin To The Request url.Append (this._origin); // Generate URL with UTF-8 Encoding for (int componentIndex = 0; componentIndex < urlComponents.Count; componentIndex++) { url.Append ("/"); if (type == ResponseType.Publish && componentIndex == urlComponents.Count - 1) { url.Append(EncodeUricomponent(urlComponents[componentIndex].ToString(), type, false)); } else { url.Append(EncodeUricomponent(urlComponents[componentIndex].ToString(), type, true)); } } if (type == ResponseType.Presence || type == ResponseType.Subscribe || type == ResponseType.Leave) { //queryParamExist = true; url.AppendFormat("?uuid={0}", uuid); url.Append(subscribeParameters); if (!string.IsNullOrEmpty(_authenticationKey)) { url.AppendFormat ("&auth={0}", EncodeUricomponent(_authenticationKey, type, false)); } if (_pubnubPresenceHeartbeatInSeconds != 0) { url.AppendFormat("&heartbeat={0}", _pubnubPresenceHeartbeatInSeconds); } } if (type == ResponseType.PresenceHeartbeat) { //queryParamExist = true; url.AppendFormat("?uuid={0}", uuid); url.Append(presenceHeartbeatParameters); if (_pubnubPresenceHeartbeatInSeconds != 0) { url.AppendFormat("&heartbeat={0}", _pubnubPresenceHeartbeatInSeconds); } if (!string.IsNullOrEmpty(_authenticationKey)) { url.AppendFormat("&auth={0}", EncodeUricomponent(_authenticationKey, type, false)); } } if (type == ResponseType.SetUserState) { //queryParamExist = true; url.Append(setUserStateparameters); if (!string.IsNullOrEmpty(_authenticationKey)) { url.AppendFormat("&auth={0}", EncodeUricomponent(_authenticationKey, type, false)); } } if (type == ResponseType.GetUserState) { if (!string.IsNullOrEmpty (_authenticationKey)) { //queryParamExist = true; url.AppendFormat ("?auth={0}", EncodeUricomponent(_authenticationKey, type, false)); } } if (type == ResponseType.Here_Now) { url.Append(hereNowParameters); if (!string.IsNullOrEmpty(_authenticationKey)) { //queryParamExist = true; url.AppendFormat ("&auth={0}", EncodeUricomponent(_authenticationKey, type, false)); } } if (type == ResponseType.GlobalHere_Now) { url.Append(globalHereNowParameters); if (!string.IsNullOrEmpty(_authenticationKey)) { //queryParamExist = true; url.AppendFormat ("&auth={0}", EncodeUricomponent(_authenticationKey, type, false)); } } if (type == ResponseType.Where_Now) { if (!string.IsNullOrEmpty(_authenticationKey)) { //queryParamExist = true; url.AppendFormat ("?auth={0}", EncodeUricomponent(_authenticationKey, type, false)); } } if (type == ResponseType.Publish && !string.IsNullOrEmpty(_authenticationKey)) { //queryParamExist = true; url.AppendFormat("?auth={0}", EncodeUricomponent(_authenticationKey, type, false)); } if (type == ResponseType.DetailedHistory || type == ResponseType.GrantAccess || type == ResponseType.AuditAccess || type == ResponseType.RevokeAccess) { url.Append(parameters); //queryParamExist = true; } Uri requestUri = new Uri (url.ToString()); if ((type == ResponseType.Publish || type == ResponseType.Subscribe || type == ResponseType.Presence)) { ForceCanonicalPathAndQuery(requestUri); } return requestUri; } #endregion } #region "Unit test interface" public interface IPubnubUnitTest { bool EnableStubTest { get; set; } string TestClassName { get; set; } string TestCaseName { get; set; } string GetStubResponse (HttpWebRequest request); } #endregion #region "Webrequest and webresponse" internal abstract class PubnubWebRequestCreatorBase : IWebRequestCreate { protected IPubnubUnitTest pubnubUnitTest = null; public PubnubWebRequestCreatorBase () { } public PubnubWebRequestCreatorBase (IPubnubUnitTest pubnubUnitTest) { this.pubnubUnitTest = pubnubUnitTest; } protected abstract HttpWebRequest SetNoCache(HttpWebRequest req, bool nocache); protected abstract WebRequest CreateRequest(Uri uri, bool keepAliveRequest, bool nocache); public WebRequest Create(Uri uri) { return CreateRequest(uri, true, true); } public WebRequest Create(Uri uri, bool keepAliveRequest) { return CreateRequest(uri, keepAliveRequest, true); } public WebRequest Create(Uri uri, bool keepAliveRequest, bool nocache) { return CreateRequest(uri, keepAliveRequest, nocache); } } public abstract class PubnubWebRequestBase : WebRequest { internal IPubnubUnitTest pubnubUnitTest = null; private static bool simulateNetworkFailForTesting = false; private static bool machineSuspendMode = false; private bool terminated = false; PubnubErrorFilter.Level filterErrorLevel = PubnubErrorFilter.Level.Info; internal HttpWebRequest request; internal static bool SimulateNetworkFailForTesting { get { return simulateNetworkFailForTesting; } set { simulateNetworkFailForTesting = value; } } internal static bool MachineSuspendMode { get { return machineSuspendMode; } set { machineSuspendMode = value; } } public PubnubWebRequestBase (HttpWebRequest request) { this.request = request; } public PubnubWebRequestBase (HttpWebRequest request, IPubnubUnitTest pubnubUnitTest) { this.request = request; this.pubnubUnitTest = pubnubUnitTest; } public override void Abort () { if (request != null) { terminated = true; request.Abort (); } } public void Abort (Action<PubnubClientError> errorCallback, PubnubErrorFilter.Level errorLevel) { if (request != null) { terminated = true; try { request.Abort (); } catch (WebException webEx) { if (errorCallback != null) { HttpStatusCode currentHttpStatusCode; filterErrorLevel = errorLevel; if (webEx.Response.GetType ().ToString () == "System.Net.HttpWebResponse" || webEx.Response.GetType ().ToString () == "System.Net.Browser.ClientHttpWebResponse") { currentHttpStatusCode = ((HttpWebResponse)webEx.Response).StatusCode; } else { currentHttpStatusCode = ((PubnubWebResponse)webEx.Response).HttpStatusCode; } string statusMessage = currentHttpStatusCode.ToString (); PubnubErrorCode pubnubErrorType = PubnubErrorCodeHelper.GetErrorType ((int)currentHttpStatusCode, statusMessage); int pubnubStatusCode = (int)pubnubErrorType; string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (pubnubErrorType); PubnubClientError error = new PubnubClientError (pubnubStatusCode, PubnubErrorSeverity.Critical, true, webEx.Message, webEx, PubnubMessageSource.Client, null, null, errorDescription, ""); GoToCallback (error, errorCallback); } } catch (Exception ex) { if (errorCallback != null) { filterErrorLevel = errorLevel; PubnubErrorCode errorType = PubnubErrorCodeHelper.GetErrorType (ex); int statusCode = (int)errorType; string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (errorType); PubnubClientError error = new PubnubClientError (statusCode, PubnubErrorSeverity.Critical, true, ex.Message, ex, PubnubMessageSource.Client, null, null, errorDescription, ""); GoToCallback (error, errorCallback); } } } } private void GoToCallback (PubnubClientError error, Action<PubnubClientError> Callback) { if (Callback != null && error != null) { if ((int)error.Severity <= (int)filterErrorLevel) { //Checks whether the error serverity falls in the range of error filter level //Do not send 107 = PubnubObjectDisposedException //Do not send 105 = WebRequestCancelled //Do not send 130 = PubnubClientMachineSleep if (error.StatusCode != 107 && error.StatusCode != 105 && error.StatusCode != 130) { //Error Code that should not go out Callback (error); } } } } public override WebHeaderCollection Headers { get { return request.Headers; } set { request.Headers = value; } } public override string Method { get { return request.Method; } set { request.Method = value; } } public override string ContentType { get { return request.ContentType; } set { request.ContentType = value; } } public override ICredentials Credentials { get { return request.Credentials; } set { request.Credentials = value; } } public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) { return request.BeginGetRequestStream (callback, state); } public override Stream EndGetRequestStream (IAsyncResult asyncResult) { return request.EndGetRequestStream (asyncResult); } public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state) { if (pubnubUnitTest is IPubnubUnitTest && pubnubUnitTest.EnableStubTest) { return new PubnubWebAsyncResult (callback, state); } else if (machineSuspendMode) { return new PubnubWebAsyncResult (callback, state); } else { return request.BeginGetResponse (callback, state); } } public override WebResponse EndGetResponse (IAsyncResult asyncResult) { if (pubnubUnitTest is IPubnubUnitTest && pubnubUnitTest.EnableStubTest) { string stubResponse = pubnubUnitTest.GetStubResponse (request); return new PubnubWebResponse (new MemoryStream (Encoding.UTF8.GetBytes (stubResponse))); } else if (machineSuspendMode) { WebException simulateException = new WebException ("Machine suspend mode enabled. No request will be processed.", WebExceptionStatus.Pending); throw simulateException; } else if (simulateNetworkFailForTesting) { WebException simulateException = new WebException ("For simulating network fail, the remote name could not be resolved", WebExceptionStatus.ConnectFailure); throw simulateException; } else { return new PubnubWebResponse (request.EndGetResponse (asyncResult)); } } public override Uri RequestUri { get { return request.RequestUri; } } public override bool UseDefaultCredentials { get { return request.UseDefaultCredentials; } } public bool Terminated { get { return terminated; } } } public abstract class PubnubWebResponseBase : WebResponse { protected WebResponse response; readonly Stream _responseStream; HttpStatusCode httpStatusCode; public PubnubWebResponseBase (WebResponse response) { this.response = response; } public PubnubWebResponseBase (WebResponse response, HttpStatusCode statusCode) { this.response = response; this.httpStatusCode = statusCode; } public PubnubWebResponseBase (Stream responseStream) { _responseStream = responseStream; } public PubnubWebResponseBase(Stream responseStream, HttpStatusCode statusCode) { _responseStream = responseStream; this.httpStatusCode = statusCode; } public override Stream GetResponseStream () { if (response != null) return response.GetResponseStream (); else return _responseStream; } public override WebHeaderCollection Headers { get { return response.Headers; } } public override long ContentLength { get { return response.ContentLength; } } public override string ContentType { get { return response.ContentType; } } public override Uri ResponseUri { get { return response.ResponseUri; } } public HttpStatusCode HttpStatusCode { get { return httpStatusCode; } } } internal class PubnubWebAsyncResult : IAsyncResult { private const int pubnubDefaultLatencyInMilliSeconds = 1; //PubnubDefaultLatencyInMilliSeconds private readonly AsyncCallback _callback; private readonly object _state; private readonly ManualResetEvent _waitHandle; private readonly Timer _timer; public bool IsCompleted { get; private set; } public WaitHandle AsyncWaitHandle { get { return _waitHandle; } } public object AsyncState { get { return _state; } } public bool CompletedSynchronously { get { return IsCompleted; } } public PubnubWebAsyncResult (AsyncCallback callback, object state) : this (callback, state, TimeSpan.FromMilliseconds (pubnubDefaultLatencyInMilliSeconds)) { } public PubnubWebAsyncResult (AsyncCallback callback, object state, TimeSpan latency) { IsCompleted = false; _callback = callback; _state = state; _waitHandle = new ManualResetEvent (false); _timer = new Timer (onTimer => NotifyComplete (), null, latency, TimeSpan.FromMilliseconds (-1)); } public void Abort () { _timer.Dispose (); NotifyComplete (); } private void NotifyComplete () { IsCompleted = true; _waitHandle.Set (); if (_callback != null) _callback (this); } } #endregion #region "Proxy" public class PubnubProxy { string proxyServer; int proxyPort; string proxyUserName; string proxyPassword; public string ProxyServer { get { return proxyServer; } set { proxyServer = value; } } public int ProxyPort { get { return proxyPort; } set { proxyPort = value; } } public string ProxyUserName { get { return proxyUserName; } set { proxyUserName = value; } } public string ProxyPassword { get { return proxyPassword; } set { proxyPassword = value; } } } #endregion #region "Json Pluggable Library" public interface IJsonPluggableLibrary { bool IsArrayCompatible (string jsonString); bool IsDictionaryCompatible (string jsonString); string SerializeToJsonString (object objectToSerialize); List<object> DeserializeToListOfObject (string jsonString); object DeserializeToObject (string jsonString); //T DeserializeToObject<T>(string jsonString); Dictionary<string, object> DeserializeToDictionaryOfObject (string jsonString); } #if (USE_JSONFX)|| (USE_JSONFX_UNITY) public class JsonFXDotNet : IJsonPluggableLibrary { public bool IsArrayCompatible (string jsonString) { return false; } public bool IsDictionaryCompatible (string jsonString) { return true; } public string SerializeToJsonString (object objectToSerialize) { #if(__MonoCS__) var writer = new JsonFx.Json.JsonWriter (); string json = writer.Write (objectToSerialize); return PubnubCryptoBase.ConvertHexToUnicodeChars (json); #else string json = ""; var resolver = new JsonFx.Serialization.Resolvers.CombinedResolverStrategy(new JsonFx.Serialization.Resolvers.DataContractResolverStrategy()); JsonFx.Serialization.DataWriterSettings dataWriterSettings = new JsonFx.Serialization.DataWriterSettings(resolver); var writer = new JsonFx.Json.JsonWriter(dataWriterSettings, new string[] { "PubnubClientError" }); json = writer.Write(objectToSerialize); return json; #endif } public List<object> DeserializeToListOfObject (string jsonString) { jsonString = PubnubCryptoBase.ConvertHexToUnicodeChars(jsonString); var reader = new JsonFx.Json.JsonReader (); var output = reader.Read<List<object>> (jsonString); return output; } public object DeserializeToObject (string jsonString) { jsonString = PubnubCryptoBase.ConvertHexToUnicodeChars(jsonString); var reader = new JsonFx.Json.JsonReader (); var output = reader.Read<object> (jsonString); return output; } public Dictionary<string, object> DeserializeToDictionaryOfObject (string jsonString) { #if USE_JSONFX_UNITY LoggingMethod.WriteToLog ("jsonstring:"+jsonString, LoggingMethod.LevelInfo); object obj = DeserializeToObject(jsonString); Dictionary<string, object> stateDictionary = new Dictionary<string, object> (); Dictionary<string, object> message = (Dictionary<string, object>)obj; if(message != null){ foreach (KeyValuePair<String, object> kvp in message) { stateDictionary.Add (kvp.Key, kvp.Value); } } return stateDictionary; #else jsonString = PubnubCryptoBase.ConvertHexToUnicodeChars (jsonString); var reader = new JsonFx.Json.JsonReader (); var output = reader.Read<object> (jsonString); Type valueType = null; valueType = output.GetType (); var expectedType = typeof(System.Dynamic.ExpandoObject); if (expectedType.IsAssignableFrom (valueType)) { var d = output as IDictionary<string, object>; Dictionary<string, object> stateDictionary = new Dictionary<string, object> (); foreach (KeyValuePair<string, object> kvp in d) { stateDictionary.Add (kvp.Key, kvp.Value); } return stateDictionary; } else { LoggingMethod.WriteToLog ("jsonstring:"+jsonString, LoggingMethod.LevelInfo); object obj = DeserializeToObject(jsonString); Dictionary<string, object> stateDictionary = new Dictionary<string, object> (); Dictionary<string, object> message = (Dictionary<string, object>)obj; if(message != null){ foreach (KeyValuePair<String, object> kvp in message) { stateDictionary.Add (kvp.Key, kvp.Value); } } return stateDictionary; } #endif } } #elif (USE_DOTNET_SERIALIZATION) public class JscriptSerializer : IJsonPluggableLibrary { public bool IsArrayCompatible(string jsonString){ return false; } public bool IsDictionaryCompatible(string jsonString){ return false; } public string SerializeToJsonString(object objectToSerialize) { JavaScriptSerializer jS = new JavaScriptSerializer(); return jS.Serialize(objectToSerialize); } public List<object> DeserializeToListOfObject(string jsonString) { JavaScriptSerializer jS = new JavaScriptSerializer(); return (List<object>)jS.Deserialize<List<object>>(jsonString); } public object DeserializeToObject(string jsonString) { JavaScriptSerializer jS = new JavaScriptSerializer(); return (object)jS.Deserialize<object>(jsonString); } public Dictionary<string, object> DeserializeToDictionaryOfObject(string jsonString) { JavaScriptSerializer jS = new JavaScriptSerializer(); return (Dictionary<string, object>)jS.Deserialize<Dictionary<string, object>>(jsonString); } } #elif (USE_MiniJSON) public class MiniJSONObjectSerializer : IJsonPluggableLibrary { public bool IsArrayCompatible(string jsonString){ return false; } public bool IsDictionaryCompatible(string jsonString){ return true; } public string SerializeToJsonString(object objectToSerialize) { string json = Json.Serialize(objectToSerialize); return PubnubCryptoBase.ConvertHexToUnicodeChars(json); } public List<object> DeserializeToListOfObject(string jsonString) { return Json.Deserialize(jsonString) as List<object>; } public object DeserializeToObject (string jsonString) { return Json.Deserialize (jsonString) as object; } public Dictionary<string, object> DeserializeToDictionaryOfObject(string jsonString) { return Json.Deserialize(jsonString) as Dictionary<string, object>; } } #elif (USE_JSONFX_UNITY_IOS) public class JsonFxUnitySerializer : IJsonPluggableLibrary { public bool IsArrayCompatible (string jsonString) { return false; } public bool IsDictionaryCompatible (string jsonString) { return true; } public string SerializeToJsonString (object objectToSerialize) { string json = JsonWriter.Serialize (objectToSerialize); return PubnubCryptoBase.ConvertHexToUnicodeChars (json); } public List<object> DeserializeToListOfObject (string jsonString) { var output = JsonReader.Deserialize<object[]> (jsonString) as object[]; List<object> messageList = output.Cast<object> ().ToList (); return messageList; } public object DeserializeToObject (string jsonString) { var output = JsonReader.Deserialize<object> (jsonString) as object; return output; } public Dictionary<string, object> DeserializeToDictionaryOfObject (string jsonString) { LoggingMethod.WriteToLog ("jsonstring:"+jsonString, LoggingMethod.LevelInfo); object obj = DeserializeToObject(jsonString); Dictionary<string, object> stateDictionary = new Dictionary<string, object> (); Dictionary<string, object> message = (Dictionary<string, object>)obj; if(message != null){ foreach (KeyValuePair<String, object> kvp in message) { stateDictionary.Add (kvp.Key, kvp.Value); } } return stateDictionary; } } #else public class NewtonsoftJsonDotNet : IJsonPluggableLibrary { #region IJsonPlugableLibrary methods implementation public bool IsArrayCompatible (string jsonString) { bool ret = false; JsonTextReader reader = new JsonTextReader (new StringReader (jsonString)); while (reader.Read ()) { if (reader.LineNumber == 1 && reader.LinePosition == 1 && reader.TokenType == JsonToken.StartArray) { ret = true; break; } else { break; } } return ret; } public bool IsDictionaryCompatible (string jsonString) { bool ret = false; JsonTextReader reader = new JsonTextReader (new StringReader (jsonString)); while (reader.Read ()) { if (reader.LineNumber == 1 && reader.LinePosition == 1 && reader.TokenType == JsonToken.StartObject) { ret = true; break; } else { break; } } return ret; } public string SerializeToJsonString (object objectToSerialize) { return JsonConvert.SerializeObject (objectToSerialize); } public List<object> DeserializeToListOfObject (string jsonString) { List<object> result = JsonConvert.DeserializeObject<List<object>> (jsonString); return result; } public object DeserializeToObject (string jsonString) { object result = JsonConvert.DeserializeObject<object> (jsonString); if (result.GetType ().ToString () == "Newtonsoft.Json.Linq.JArray") { JArray jarrayResult = result as JArray; List<object> objectContainer = jarrayResult.ToObject<List<object>> (); if (objectContainer != null && objectContainer.Count > 0) { for (int index = 0; index < objectContainer.Count; index++) { if (objectContainer [index].GetType ().ToString () == "Newtonsoft.Json.Linq.JArray") { JArray internalItem = objectContainer [index] as JArray; objectContainer [index] = internalItem.Select (item => (object)item).ToArray (); } } result = objectContainer; } } return result; } public Dictionary<string, object> DeserializeToDictionaryOfObject (string jsonString) { return JsonConvert.DeserializeObject<Dictionary<string, object>> (jsonString); } #endregion } #endif #endregion #region "States and ResposeTypes" public enum ResponseType { Publish, History, Time, Subscribe, Presence, Here_Now, DetailedHistory, Leave, Unsubscribe, PresenceUnsubscribe, GrantAccess, AuditAccess, RevokeAccess, PresenceHeartbeat, SetUserState, GetUserState, Where_Now, GlobalHere_Now } internal class InternetState<T> { public Action<bool> Callback; public Action<PubnubClientError> ErrorCallback; public string[] Channels; public InternetState () { Callback = null; ErrorCallback = null; Channels = null; } } public class RequestState<T> { public Action<T> UserCallback; public Action<PubnubClientError> ErrorCallback; public Action<T> ConnectCallback; public PubnubWebRequest Request; public PubnubWebResponse Response; public ResponseType Type; public string[] Channels; public bool Timeout; public bool Reconnect; public long Timetoken; public RequestState () { UserCallback = null; ConnectCallback = null; Request = null; Response = null; Channels = null; } } #endregion #region "Channel callback" internal struct PubnubChannelCallbackKey { public string Channel; public ResponseType Type; } internal class PubnubChannelCallback<T> { public Action<T> Callback; public Action<PubnubClientError> ErrorCallback; public Action<T> ConnectCallback; public Action<T> DisconnectCallback; //public ResponseType Type; public PubnubChannelCallback () { Callback = null; ConnectCallback = null; DisconnectCallback = null; ErrorCallback = null; } } #endregion }
36.284161
257
0.679048
[ "MIT" ]
redarrowlabs/pubnub-c-sharp
demos/ePoll/PubnubCore/PubnubCore.cs
170,211
C#
// Entity Designer Documentation Generator // Copyright 2017 Matthew Hamilton - matthamilton@live.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace DocumentationGenerator { /// <summary> /// Represents a source of entity documentation. /// </summary> public interface IDocumentationSource : IDisposable { /// <summary> /// Retrieves documentation for an entity. /// </summary> /// <param name="entity">An entity.</param> /// <returns>A documentation string</returns> string GetDocumentation(EntityType entity); /// <summary> /// Retrieves documentation for an entity property. /// </summary> /// <param name="entity">The parent entity.</param> /// <param name="property">An entity property.</param> /// <returns>A documentation string.</returns> string GetDocumentation(EntityType entity, EntityProperty property); } }
37.5
76
0.672
[ "Apache-2.0" ]
mthamil/EFDocumentationGenerator
extension/EFDocumentationGenerator/IDocumentationSource.cs
1,502
C#
using ShaderTools.CodeAnalysis.Hlsl.Symbols; namespace ShaderTools.CodeAnalysis.Hlsl.Binding { internal sealed class NamespaceBinder : Binder { public NamespaceSymbol NamespaceSymbol { get; } public NamespaceBinder(SharedBinderState sharedBinderState, Binder parent, NamespaceSymbol namespaceSymbol) : base(sharedBinderState, parent) { NamespaceSymbol = namespaceSymbol; } } }
30.733333
116
0.683297
[ "Apache-2.0" ]
BigHeadGift/HLSL
src/ShaderTools.CodeAnalysis.Hlsl/Binding/NamespaceBinder.cs
449
C#
// This file was generated by a tool; you should avoid making direct changes. // Consider using 'partial classes' to extend these types // Input: planning.proto #pragma warning disable 0612, 1591, 3021 namespace apollo.planning { [global::ProtoBuf.ProtoContract()] public partial class ADCSignals : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public ADCSignals() { signal = new global::System.Collections.Generic.List<SignalType>(); OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] public global::System.Collections.Generic.List<SignalType> signal { get; private set; } [global::ProtoBuf.ProtoContract()] public enum SignalType { [global::ProtoBuf.ProtoEnum(Name = @"LEFT_TURN")] LeftTurn = 1, [global::ProtoBuf.ProtoEnum(Name = @"RIGHT_TURN")] RightTurn = 2, [global::ProtoBuf.ProtoEnum(Name = @"LOW_BEAM_LIGHT")] LowBeamLight = 3, [global::ProtoBuf.ProtoEnum(Name = @"HIGH_BEAM_LIGHT")] HighBeamLight = 4, [global::ProtoBuf.ProtoEnum(Name = @"FOG_LIGHT")] FogLight = 5, [global::ProtoBuf.ProtoEnum(Name = @"EMERGENCY_LIGHT")] EmergencyLight = 6, } } [global::ProtoBuf.ProtoContract()] public partial class EStop : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public EStop() { OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] public bool is_estop { get { return __pbn__is_estop.GetValueOrDefault(); } set { __pbn__is_estop = value; } } public bool ShouldSerializeis_estop() { return __pbn__is_estop != null; } public void Resetis_estop() { __pbn__is_estop = null; } private bool? __pbn__is_estop; [global::ProtoBuf.ProtoMember(2)] [global::System.ComponentModel.DefaultValue("")] public string reason { get { return __pbn__reason ?? ""; } set { __pbn__reason = value; } } public bool ShouldSerializereason() { return __pbn__reason != null; } public void Resetreason() { __pbn__reason = null; } private string __pbn__reason; } [global::ProtoBuf.ProtoContract()] public partial class TaskStats : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public TaskStats() { OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] [global::System.ComponentModel.DefaultValue("")] public string name { get { return __pbn__name ?? ""; } set { __pbn__name = value; } } public bool ShouldSerializename() { return __pbn__name != null; } public void Resetname() { __pbn__name = null; } private string __pbn__name; [global::ProtoBuf.ProtoMember(2)] public double time_ms { get { return __pbn__time_ms.GetValueOrDefault(); } set { __pbn__time_ms = value; } } public bool ShouldSerializetime_ms() { return __pbn__time_ms != null; } public void Resettime_ms() { __pbn__time_ms = null; } private double? __pbn__time_ms; } [global::ProtoBuf.ProtoContract()] public partial class LatencyStats : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public LatencyStats() { task_stats = new global::System.Collections.Generic.List<TaskStats>(); OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] public double total_time_ms { get { return __pbn__total_time_ms.GetValueOrDefault(); } set { __pbn__total_time_ms = value; } } public bool ShouldSerializetotal_time_ms() { return __pbn__total_time_ms != null; } public void Resettotal_time_ms() { __pbn__total_time_ms = null; } private double? __pbn__total_time_ms; [global::ProtoBuf.ProtoMember(2)] public global::System.Collections.Generic.List<TaskStats> task_stats { get; private set; } [global::ProtoBuf.ProtoMember(3)] public double init_frame_time_ms { get { return __pbn__init_frame_time_ms.GetValueOrDefault(); } set { __pbn__init_frame_time_ms = value; } } public bool ShouldSerializeinit_frame_time_ms() { return __pbn__init_frame_time_ms != null; } public void Resetinit_frame_time_ms() { __pbn__init_frame_time_ms = null; } private double? __pbn__init_frame_time_ms; } [global::ProtoBuf.ProtoContract()] public partial class RSSInfo : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public RSSInfo() { OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] public bool is_rss_safe { get { return __pbn__is_rss_safe.GetValueOrDefault(); } set { __pbn__is_rss_safe = value; } } public bool ShouldSerializeis_rss_safe() { return __pbn__is_rss_safe != null; } public void Resetis_rss_safe() { __pbn__is_rss_safe = null; } private bool? __pbn__is_rss_safe; [global::ProtoBuf.ProtoMember(2)] public double cur_dist_lon { get { return __pbn__cur_dist_lon.GetValueOrDefault(); } set { __pbn__cur_dist_lon = value; } } public bool ShouldSerializecur_dist_lon() { return __pbn__cur_dist_lon != null; } public void Resetcur_dist_lon() { __pbn__cur_dist_lon = null; } private double? __pbn__cur_dist_lon; [global::ProtoBuf.ProtoMember(3)] public double rss_safe_dist_lon { get { return __pbn__rss_safe_dist_lon.GetValueOrDefault(); } set { __pbn__rss_safe_dist_lon = value; } } public bool ShouldSerializerss_safe_dist_lon() { return __pbn__rss_safe_dist_lon != null; } public void Resetrss_safe_dist_lon() { __pbn__rss_safe_dist_lon = null; } private double? __pbn__rss_safe_dist_lon; [global::ProtoBuf.ProtoMember(4)] public double acc_lon_range_minimum { get { return __pbn__acc_lon_range_minimum.GetValueOrDefault(); } set { __pbn__acc_lon_range_minimum = value; } } public bool ShouldSerializeacc_lon_range_minimum() { return __pbn__acc_lon_range_minimum != null; } public void Resetacc_lon_range_minimum() { __pbn__acc_lon_range_minimum = null; } private double? __pbn__acc_lon_range_minimum; [global::ProtoBuf.ProtoMember(5)] public double acc_lon_range_maximum { get { return __pbn__acc_lon_range_maximum.GetValueOrDefault(); } set { __pbn__acc_lon_range_maximum = value; } } public bool ShouldSerializeacc_lon_range_maximum() { return __pbn__acc_lon_range_maximum != null; } public void Resetacc_lon_range_maximum() { __pbn__acc_lon_range_maximum = null; } private double? __pbn__acc_lon_range_maximum; [global::ProtoBuf.ProtoMember(6)] public double acc_lat_left_range_minimum { get { return __pbn__acc_lat_left_range_minimum.GetValueOrDefault(); } set { __pbn__acc_lat_left_range_minimum = value; } } public bool ShouldSerializeacc_lat_left_range_minimum() { return __pbn__acc_lat_left_range_minimum != null; } public void Resetacc_lat_left_range_minimum() { __pbn__acc_lat_left_range_minimum = null; } private double? __pbn__acc_lat_left_range_minimum; [global::ProtoBuf.ProtoMember(7)] public double acc_lat_left_range_maximum { get { return __pbn__acc_lat_left_range_maximum.GetValueOrDefault(); } set { __pbn__acc_lat_left_range_maximum = value; } } public bool ShouldSerializeacc_lat_left_range_maximum() { return __pbn__acc_lat_left_range_maximum != null; } public void Resetacc_lat_left_range_maximum() { __pbn__acc_lat_left_range_maximum = null; } private double? __pbn__acc_lat_left_range_maximum; [global::ProtoBuf.ProtoMember(8)] public double acc_lat_right_range_minimum { get { return __pbn__acc_lat_right_range_minimum.GetValueOrDefault(); } set { __pbn__acc_lat_right_range_minimum = value; } } public bool ShouldSerializeacc_lat_right_range_minimum() { return __pbn__acc_lat_right_range_minimum != null; } public void Resetacc_lat_right_range_minimum() { __pbn__acc_lat_right_range_minimum = null; } private double? __pbn__acc_lat_right_range_minimum; [global::ProtoBuf.ProtoMember(9)] public double acc_lat_right_range_maximum { get { return __pbn__acc_lat_right_range_maximum.GetValueOrDefault(); } set { __pbn__acc_lat_right_range_maximum = value; } } public bool ShouldSerializeacc_lat_right_range_maximum() { return __pbn__acc_lat_right_range_maximum != null; } public void Resetacc_lat_right_range_maximum() { __pbn__acc_lat_right_range_maximum = null; } private double? __pbn__acc_lat_right_range_maximum; } [global::ProtoBuf.ProtoContract()] public partial class ADCTrajectory : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public ADCTrajectory() { trajectory_point = new global::System.Collections.Generic.List<global::apollo.common.TrajectoryPoint>(); path_point = new global::System.Collections.Generic.List<global::apollo.common.PathPoint>(); lane_id = new global::System.Collections.Generic.List<global::apollo.hdmap.Id>(); OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] public global::apollo.common.Header header { get; set; } [global::ProtoBuf.ProtoMember(2)] public double total_path_length { get { return __pbn__total_path_length.GetValueOrDefault(); } set { __pbn__total_path_length = value; } } public bool ShouldSerializetotal_path_length() { return __pbn__total_path_length != null; } public void Resettotal_path_length() { __pbn__total_path_length = null; } private double? __pbn__total_path_length; [global::ProtoBuf.ProtoMember(3)] public double total_path_time { get { return __pbn__total_path_time.GetValueOrDefault(); } set { __pbn__total_path_time = value; } } public bool ShouldSerializetotal_path_time() { return __pbn__total_path_time != null; } public void Resettotal_path_time() { __pbn__total_path_time = null; } private double? __pbn__total_path_time; [global::ProtoBuf.ProtoMember(12)] public global::System.Collections.Generic.List<global::apollo.common.TrajectoryPoint> trajectory_point { get; private set; } [global::ProtoBuf.ProtoMember(6)] public EStop estop { get; set; } [global::ProtoBuf.ProtoMember(13)] public global::System.Collections.Generic.List<global::apollo.common.PathPoint> path_point { get; private set; } [global::ProtoBuf.ProtoMember(9)] [global::System.ComponentModel.DefaultValue(false)] public bool is_replan { get { return __pbn__is_replan ?? false; } set { __pbn__is_replan = value; } } public bool ShouldSerializeis_replan() { return __pbn__is_replan != null; } public void Resetis_replan() { __pbn__is_replan = null; } private bool? __pbn__is_replan; [global::ProtoBuf.ProtoMember(22)] [global::System.ComponentModel.DefaultValue("")] public string replan_reason { get { return __pbn__replan_reason ?? ""; } set { __pbn__replan_reason = value; } } public bool ShouldSerializereplan_reason() { return __pbn__replan_reason != null; } public void Resetreplan_reason() { __pbn__replan_reason = null; } private string __pbn__replan_reason; [global::ProtoBuf.ProtoMember(10)] [global::System.ComponentModel.DefaultValue(global::apollo.canbus.Chassis.GearPosition.GearNeutral)] public global::apollo.canbus.Chassis.GearPosition gear { get { return __pbn__gear ?? global::apollo.canbus.Chassis.GearPosition.GearNeutral; } set { __pbn__gear = value; } } public bool ShouldSerializegear() { return __pbn__gear != null; } public void Resetgear() { __pbn__gear = null; } private global::apollo.canbus.Chassis.GearPosition? __pbn__gear; [global::ProtoBuf.ProtoMember(14)] public DecisionResult decision { get; set; } [global::ProtoBuf.ProtoMember(15)] public LatencyStats latency_stats { get; set; } [global::ProtoBuf.ProtoMember(16)] public global::apollo.common.Header routing_header { get; set; } [global::ProtoBuf.ProtoMember(8)] public global::apollo.planning_internal.Debug debug { get; set; } [global::ProtoBuf.ProtoMember(17)] [global::System.ComponentModel.DefaultValue(RightOfWayStatus.Unprotected)] public RightOfWayStatus right_of_way_status { get { return __pbn__right_of_way_status ?? RightOfWayStatus.Unprotected; } set { __pbn__right_of_way_status = value; } } public bool ShouldSerializeright_of_way_status() { return __pbn__right_of_way_status != null; } public void Resetright_of_way_status() { __pbn__right_of_way_status = null; } private RightOfWayStatus? __pbn__right_of_way_status; [global::ProtoBuf.ProtoMember(18)] public global::System.Collections.Generic.List<global::apollo.hdmap.Id> lane_id { get; private set; } [global::ProtoBuf.ProtoMember(19)] public global::apollo.common.EngageAdvice engage_advice { get; set; } [global::ProtoBuf.ProtoMember(20)] public CriticalRegion critical_region { get; set; } [global::ProtoBuf.ProtoMember(21)] [global::System.ComponentModel.DefaultValue(TrajectoryType.Unknown)] public TrajectoryType trajectory_type { get { return __pbn__trajectory_type ?? TrajectoryType.Unknown; } set { __pbn__trajectory_type = value; } } public bool ShouldSerializetrajectory_type() { return __pbn__trajectory_type != null; } public void Resettrajectory_type() { __pbn__trajectory_type = null; } private TrajectoryType? __pbn__trajectory_type; [global::ProtoBuf.ProtoMember(100)] public RSSInfo rss_info { get; set; } [global::ProtoBuf.ProtoContract()] public partial class CriticalRegion : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public CriticalRegion() { region = new global::System.Collections.Generic.List<global::apollo.common.Polygon>(); OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] public global::System.Collections.Generic.List<global::apollo.common.Polygon> region { get; private set; } } [global::ProtoBuf.ProtoContract()] public enum RightOfWayStatus { [global::ProtoBuf.ProtoEnum(Name = @"UNPROTECTED")] Unprotected = 0, [global::ProtoBuf.ProtoEnum(Name = @"PROTECTED")] Protected = 1, } [global::ProtoBuf.ProtoContract()] public enum TrajectoryType { [global::ProtoBuf.ProtoEnum(Name = @"UNKNOWN")] Unknown = 0, [global::ProtoBuf.ProtoEnum(Name = @"NORMAL")] Normal = 1, [global::ProtoBuf.ProtoEnum(Name = @"PATH_FALLBACK")] PathFallback = 2, [global::ProtoBuf.ProtoEnum(Name = @"SPEED_FALLBACK")] SpeedFallback = 3, } } } #pragma warning restore 0612, 1591, 3021
33.889655
132
0.613197
[ "Apache-2.0", "BSD-3-Clause" ]
0x8BADFOOD/simulator
Assets/Scripts/Bridge/Cyber/Protobuf/planning/proto/planning.cs
19,656
C#
using SmartifyBotStudio.Models; using SmartifyBotStudio.RobotDesigner.Interfaces; using SmartifyBotStudio.RobotDesigner.Variable; using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; namespace SmartifyBotStudio.RobotDesigner.TaskModel.File { [Serializable] public class RenameFiles : RobotActionBase, ITask { public SelectedFileInfo FilesToRename { get; set; } public string RenameScheme { get; set; } public string NewFileName { get; set; } public string NewFileName_or_Existing_Sequentioal { get; set; } public string NewFileNameSequential { get; set; } public bool KeepExtension { get; set; } public bool IfFileExists { get; set; } public string New_Extension { get; set; } public string After_Or_Before_Date { get; set; } public string Ater_Or_Before_AddText { get; set; } public string After_or_before_sequential { get; set; } public string Text_to_Add { get; set; } public string Text_to_Remove { get; set; } public string Text_to_Replace { get; set; } public string Text_to_ReplaceWith { get; set; } public string Custom_Date { get; set; } public string Separator_datetime { get; set; } public string Separator_sequential { get; set; } public string Date_Time_Format { get; set; } public string Date_time_to_Add { get; set; } public string Add_number_to { get; set; } public int Start_numbering_at { get; set; } public int Increment_by { get; set; } public int Lenght_of_digit { get; set; } public string Var_StoreRenamedFilesInto { get; set; } public int Execute() { try { string destinationFile=""; //if (System.IO.File.Exists(FilesToRename.FilePath)) //{ if (RenameScheme == "Set New Name") { if (KeepExtension == true) { destinationFile = FilesToRename.FilePath + "\\" + NewFileName + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } else { destinationFile = FilesToRename.FilePath + "\\" + NewFileName; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } } else if (RenameScheme == "Add Text") { if (Ater_Or_Before_AddText == "after name") { destinationFile = FilesToRename.FilePath + "\\" + FilesToRename.FileNameWithoutExtension + Text_to_Add + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } else if (Ater_Or_Before_AddText == "before name") { destinationFile = FilesToRename.FilePath + "\\" + Text_to_Add + FilesToRename.FileNameWithoutExtension + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } } else if (RenameScheme == "Remove Text") { FilesToRename.FileNameWithoutExtension = FilesToRename.FileNameWithoutExtension.Replace(Text_to_Remove, ""); destinationFile = FilesToRename.FilePath + "\\" + FilesToRename.FileNameWithoutExtension + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } else if (RenameScheme == "Replace Text") { FilesToRename.FileNameWithoutExtension = FilesToRename.FileNameWithoutExtension.Replace(Text_to_Replace, Text_to_ReplaceWith); destinationFile = FilesToRename.FilePath + "\\" + FilesToRename.FileNameWithoutExtension + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } else if (RenameScheme == "Change Extension") { destinationFile = FilesToRename.FilePath + "\\" + FilesToRename.FileNameWithoutExtension + "." + New_Extension; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } else if (RenameScheme == "Add Date or Time") { // Time information DateTime last_access_time = System.IO.File.GetLastAccessTime(FilesToRename.FileInfo); DateTime last_modified_time = System.IO.File.GetLastWriteTime(FilesToRename.FileInfo); DateTime creation_time = System.IO.File.GetCreationTime(FilesToRename.FileInfo); DateTime current_date = DateTime.Now; string final_formated_date = ""; if (Date_time_to_Add == "Current DateTime") { string str_current_date_time = current_date.ToString(Date_Time_Format, CultureInfo.InvariantCulture); final_formated_date = str_current_date_time; } else if (Date_time_to_Add == "Creation DateTime") { string str_creation_time = creation_time.ToString(Date_Time_Format, CultureInfo.InvariantCulture); final_formated_date = str_creation_time; } else if (Date_time_to_Add == "Last Accessed DateTime") { string str_last_access_time = last_access_time.ToString(Date_Time_Format, CultureInfo.InvariantCulture); final_formated_date = str_last_access_time; } else if (Date_time_to_Add == "Last Modified DateTime") { string str_last_modified_time = last_modified_time.ToString(Date_Time_Format, CultureInfo.InvariantCulture); final_formated_date = str_last_modified_time; } else if (Date_time_to_Add == "Custom DateTime") { string str_last_modified_time = last_modified_time.ToString(Custom_Date, CultureInfo.InvariantCulture); final_formated_date = str_last_modified_time; } if (After_Or_Before_Date == "after name") { destinationFile = FilesToRename.FilePath + "\\" + FilesToRename.FileNameWithoutExtension + Separator_(Separator_datetime) + final_formated_date + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } else if (After_Or_Before_Date == "before name") { destinationFile = FilesToRename.FilePath + "\\" + final_formated_date + Separator_(Separator_datetime) + FilesToRename.FileNameWithoutExtension + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } } else if (RenameScheme == "Make Sequential") { string digit_string_filled_with_0 = string.Concat(Enumerable.Repeat("0", Lenght_of_digit)); string digit_string = digit_string_filled_with_0.Remove(digit_string_filled_with_0.Length - Start_numbering_at.ToString().Length); ; digit_string = digit_string + Start_numbering_at.ToString(); if (NewFileName_or_Existing_Sequentioal == "existing name") { if (After_or_before_sequential == "after name") { destinationFile = FilesToRename.FilePath + "\\" + FilesToRename.FileNameWithoutExtension + Separator_(Separator_sequential) + digit_string + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } else if (After_or_before_sequential == "before name") { destinationFile = FilesToRename.FilePath + "\\" + digit_string + Separator_(Separator_sequential) + FilesToRename.FileNameWithoutExtension + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } } else if (NewFileName_or_Existing_Sequentioal == "new name") { if (After_or_before_sequential == "after name") { destinationFile = FilesToRename.FilePath + "\\" + NewFileNameSequential + Separator_(Separator_sequential) + digit_string + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } else if (After_or_before_sequential == "before name") { destinationFile = FilesToRename.FilePath + "\\" + digit_string + Separator_(Separator_sequential) + NewFileNameSequential + FilesToRename.FileExtention; System.IO.File.Move(FilesToRename.FileInfo, destinationFile); } } } // } return 1; } catch (Exception ex) { return 0; } } public string Separator_(string separator) { if (separator== "space") { return " "; } else if(separator == "dash") { return "-"; } else if (separator == "period") { return "."; } else if (separator == "underscore") { return "_"; } return ""; } } }
48.716814
202
0.527702
[ "MIT" ]
codertuhin/BotStudio
SmartifyBotStudio/RobotDesigner/TaskModel/File/RenameFiles.cs
11,012
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestCursor : MonoBehaviour { public GameObject Player; // Use this for initialization void Start () { Player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame void Update () { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Debug.DrawRay(ray.origin, ray.direction * 20, Color.yellow); RaycastHit hit; if (Physics.Raycast(ray.origin, ray.direction, out hit, 200)) { if (hit.transform.name == "LookPlane") { Player.GetComponent<PlayerController>().LookPos = new Vector3(hit.point.x, hit.point.y, hit.point.z); } } } }
29.961538
117
0.63543
[ "MIT" ]
DedhamJammers/whitebloodcell
Cell Frontier/Assets/TestCursor.cs
781
C#
// ReSharper disable once CheckNamespace namespace System.Numerics { public static class BigIntegerExtensions { public static BigInteger Factorial(BigInteger n) { BigInteger result = 1; for(BigInteger i = 1; i <= n; i++) result *= i; return result; } } }
24.5
56
0.553936
[ "MIT" ]
Infarh/MathCore
MathCore/Extensions/Numerics/BigIntegerExtensions.cs
345
C#
namespace vsgerrit.Features.ChangeBrowser.Services { public interface IChangeBrowserNavigationService { void ToggleSettingsVisibility(); } }
23
52
0.745342
[ "Apache-2.0" ]
vsgerrit/vsgerrit
src/VSGerrit/Features/ChangeBrowser/Services/IChangeBrowserNavigationService.cs
163
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Input { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class ManipulationUpdatedEventArgs { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.UI.Input.ManipulationDelta Cumulative { get { throw new global::System.NotImplementedException("The member ManipulationDelta ManipulationUpdatedEventArgs.Cumulative is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.UI.Input.ManipulationDelta Delta { get { throw new global::System.NotImplementedException("The member ManipulationDelta ManipulationUpdatedEventArgs.Delta is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Devices.Input.PointerDeviceType PointerDeviceType { get { throw new global::System.NotImplementedException("The member PointerDeviceType ManipulationUpdatedEventArgs.PointerDeviceType is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Foundation.Point Position { get { throw new global::System.NotImplementedException("The member Point ManipulationUpdatedEventArgs.Position is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.UI.Input.ManipulationVelocities Velocities { get { throw new global::System.NotImplementedException("The member ManipulationVelocities ManipulationUpdatedEventArgs.Velocities is not implemented in Uno."); } } #endif // Forced skipping of method Windows.UI.Input.ManipulationUpdatedEventArgs.PointerDeviceType.get // Forced skipping of method Windows.UI.Input.ManipulationUpdatedEventArgs.Position.get // Forced skipping of method Windows.UI.Input.ManipulationUpdatedEventArgs.Delta.get // Forced skipping of method Windows.UI.Input.ManipulationUpdatedEventArgs.Cumulative.get // Forced skipping of method Windows.UI.Input.ManipulationUpdatedEventArgs.Velocities.get } }
36.925373
159
0.756669
[ "Apache-2.0" ]
ATHULBABYKURIAN/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Input/ManipulationUpdatedEventArgs.cs
2,474
C#
using System; using System.IO; using System.Text; using Axiom.Core; using Axiom.MathLib; namespace Axiom.Serialization { /// <summary> /// Summary description for Serializer. /// </summary> public class Serializer { #region Fields /// <summary> /// Version string of this serializer. /// </summary> protected string version; /// <summary> /// Length of the chunk that is currently being processed. /// </summary> protected int currentChunkLength; /// <summary> /// Chunk ID + size (short + long). /// </summary> public const int ChunkOverheadSize = 6; #endregion Fields #region Constructor /// <summary> /// Default constructor. /// </summary> public Serializer() { // default binary file version version = "[Serializer_v1.00]"; } #endregion Constructor #region Methods /// <summary> /// Skips past a particular chunk. /// </summary> /// <remarks> /// Only really used during development, when logic for handling particular chunks is not yet complete. /// </remarks> protected void IgnoreCurrentChunk(BinaryMemoryReader reader) { Seek(reader, currentChunkLength - ChunkOverheadSize); } /// <summary> /// Reads a specified number of floats and copies them into the destination pointer. /// </summary> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> protected void ReadBytes(BinaryMemoryReader reader, int count, IntPtr dest) { // blast the data into the buffer unsafe { byte* pointer = (byte*)dest.ToPointer(); for(int i = 0; i < count; i++) { pointer[i] = reader.ReadByte(); } } } /// <summary> /// Writes a specified number of bytes. /// </summary> /// <param name="count">Number of values to write.</param> /// <param name="src">Pointer that holds the values.</param> protected void WriteBytes(BinaryWriter writer, int count, IntPtr src) { unsafe { byte* pointer = (byte*)src.ToPointer(); for (int i = 0; i < count; i++) { writer.Write(pointer[i]); } } } /// <summary> /// Reads a specified number of floats and copies them into the destination pointer. /// </summary> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> protected void ReadFloats(BinaryMemoryReader reader, int count, IntPtr dest) { // blast the data into the buffer unsafe { float* pointer = (float*)dest.ToPointer(); for(int i = 0; i < count; i++) { pointer[i] = reader.ReadSingle(); } } } /// <summary> /// Writes a specified number of floats. /// </summary> /// <param name="count">Number of values to write.</param> /// <param name="src">Pointer that holds the values.</param> protected void WriteFloats(BinaryWriter writer, int count, IntPtr src) { unsafe { float* pointer = (float*)src.ToPointer(); for (int i = 0; i < count; i++) { writer.Write(pointer[i]); } } } /// <summary> /// Reads a specified number of floats and copies them into the destination pointer. /// </summary> /// <remarks>This overload will also copy the values into the specified destination array.</remarks> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> /// <param name="destArray">A float array that is to have the values copied into it at the same time as 'dest'.</param> protected void ReadFloats(BinaryMemoryReader reader, int count, IntPtr dest, float[] destArray) { // blast the data into the buffer unsafe { float* pointer = (float*)dest.ToPointer(); for(int i = 0; i < count; i++) { float val = reader.ReadSingle(); pointer[i] = val; destArray[i] = val; } } } protected bool ReadBool(BinaryMemoryReader reader) { return reader.ReadBoolean(); } protected void WriteBool(BinaryWriter writer, bool val) { writer.Write(val); } protected float ReadFloat(BinaryMemoryReader reader) { return reader.ReadSingle(); } protected void WriteFloat(BinaryWriter writer, float val) { writer.Write(val); } protected int ReadInt(BinaryMemoryReader reader) { return reader.ReadInt32(); } protected void WriteInt(BinaryWriter writer, int val) { writer.Write(val); } protected uint ReadUInt(BinaryMemoryReader reader) { return reader.ReadUInt32(); } protected void WriteUInt(BinaryWriter writer, uint val) { writer.Write(val); } protected long ReadLong(BinaryMemoryReader reader) { return reader.ReadInt64(); } protected void WriteLong(BinaryWriter writer, long val) { writer.Write(val); } protected ulong ReadULong(BinaryMemoryReader reader) { return reader.ReadUInt64(); } protected void WriteULong(BinaryWriter writer, ulong val) { writer.Write(val); } protected short ReadShort(BinaryMemoryReader reader) { return reader.ReadInt16(); } protected void WriteShort(BinaryWriter writer, short val) { writer.Write(val); } protected ushort ReadUShort(BinaryMemoryReader reader) { return reader.ReadUInt16(); } protected void WriteUShort(BinaryWriter writer, ushort val) { writer.Write(val); } /// <summary> /// Reads a specified number of integers and copies them into the destination pointer. /// </summary> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> protected void ReadInts(BinaryMemoryReader reader, int count, IntPtr dest) { // blast the data into the buffer unsafe { int* pointer = (int*)dest.ToPointer(); for(int i = 0; i < count; i++) { pointer[i] = reader.ReadInt32(); } } } /// <summary> /// Writes a specified number of integers. /// </summary> /// <param name="count">Number of values to write.</param> /// <param name="src">Pointer that holds the values.</param> protected void WriteInts(BinaryWriter writer, int count, IntPtr src) { // blast the data into the buffer unsafe { int* pointer = (int*)src.ToPointer(); for (int i = 0; i < count; i++) { writer.Write(pointer[i]); } } } /// <summary> /// Reads a specified number of shorts and copies them into the destination pointer. /// </summary> /// <param name="count">Number of values to read.</param> /// <param name="dest">Pointer to copy the values into.</param> protected void ReadShorts(BinaryMemoryReader reader, int count, IntPtr dest) { // blast the data into the buffer unsafe { short* pointer = (short*)dest.ToPointer(); for (int i = 0; i < count; i++) { pointer[i] = reader.ReadInt16(); } } } /// <summary> /// Writes a specified number of shorts. /// </summary> /// <param name="count">Number of values to write.</param> /// <param name="src">Pointer that holds the values.</param> protected void WriteShorts(BinaryWriter writer, int count, IntPtr src) { // blast the data into the buffer unsafe { short* pointer = (short*)src.ToPointer(); for (int i = 0; i < count; i++) { writer.Write(pointer[i]); } } } /// <summary> /// Reads from the stream up to the first endline character. /// </summary> /// <returns>A string formed from characters up to the first '\n' character.</returns> protected string ReadString(BinaryMemoryReader reader) { // note: Not using Environment.NewLine here, this character is specifically used in Ogre files. return ReadString(reader, '\n'); } /// <summary> /// Writes the string to the stream including the endline character. /// </summary> protected void WriteString(BinaryWriter writer, string str) { WriteString(writer, str, '\n'); } /// <summary> /// Reads from the stream up to the specified delimiter character. /// </summary> /// <param name="delimiter">The character that signals the end of the string.</param> /// <returns>A string formed from characters up to the first instance of the specified delimeter.</returns> protected string ReadString(BinaryMemoryReader reader, char delimiter) { StringBuilder sb = new StringBuilder(); char c; // sift through each character until we hit the delimiter while((c = reader.ReadChar()) != delimiter) { sb.Append(c); } // return the accumulated string return sb.ToString(); } /// <summary> /// Writes the string to the stream including the specified delimiter character. /// </summary> /// <param name="delimiter">The character that signals the end of the string.</param> protected void WriteString(BinaryWriter writer, string str, char delimiter) { StringBuilder sb = new StringBuilder(str); sb.Append(delimiter); writer.Write(sb.ToString().ToCharArray()); } /// <summary> /// Reads and returns a Quaternion. /// </summary> /// <returns></returns> protected Quaternion ReadQuat(BinaryMemoryReader reader) { Quaternion quat = new Quaternion(); quat.x = reader.ReadSingle(); quat.y = reader.ReadSingle(); quat.z = reader.ReadSingle(); quat.w = reader.ReadSingle(); return quat; } /// <summary> /// Reads and returns a Quaternion. /// </summary> protected void WriteQuat(BinaryWriter writer, Quaternion quat) { writer.Write(quat.x); writer.Write(quat.y); writer.Write(quat.z); writer.Write(quat.w); } /// <summary> /// Reads and returns a Vector3 structure. /// </summary> /// <returns></returns> protected Vector3 ReadVector3(BinaryMemoryReader reader) { Vector3 vector = new Vector3(); vector.x = ReadFloat(reader); vector.y = ReadFloat(reader); vector.z = ReadFloat(reader); return vector; } /// <summary> /// Writes a Vector3 structure. /// </summary> protected void WriteVector3(BinaryWriter writer, Vector3 vector) { WriteFloat(writer, vector.x); WriteFloat(writer, vector.y); WriteFloat(writer, vector.z); } /// <summary> /// Reads and returns a Vector4 structure. /// </summary> /// <returns></returns> protected Vector4 ReadVector4(BinaryMemoryReader reader) { Vector4 vector = new Vector4(); vector.x = ReadFloat(reader); vector.y = ReadFloat(reader); vector.z = ReadFloat(reader); vector.w = ReadFloat(reader); return vector; } /// <summary> /// Writes a Vector4 structure. /// </summary> protected void WriteVector4(BinaryWriter writer, Vector4 vector) { WriteFloat(writer, vector.x); WriteFloat(writer, vector.y); WriteFloat(writer, vector.z); WriteFloat(writer, vector.w); } /// <summary> /// Reads a chunk ID and chunk size. /// </summary> /// <returns>The chunk ID at the current location.</returns> protected short ReadFileChunk(BinaryMemoryReader reader) { // get the chunk id short id = reader.ReadInt16(); // read the length for this chunk currentChunkLength = reader.ReadInt32(); return id; } /// <summary> /// Writes a chunk ID and chunk size. This would be more accurately named /// WriteChunkHeader, but this name is the counter of ReadChunk. /// </summary> protected void WriteChunk(BinaryWriter writer, MeshChunkID id, int chunkLength) { writer.Write((short)id); writer.Write(chunkLength); } /// <summary> /// Writes a chunk ID and chunk size. This would be more accurately named /// WriteChunkHeader, but this name is the counter of ReadChunk. /// </summary> protected void WriteChunk(BinaryWriter writer, SkeletonChunkID id, int chunkLength) { writer.Write((short)id); writer.Write(chunkLength); } /// <summary> /// Reads a file header and checks the version string. /// </summary> protected void ReadFileHeader(BinaryMemoryReader reader) { short headerID = 0; // read the header ID headerID = reader.ReadInt16(); // better hope this is the header if(headerID == (short)MeshChunkID.Header) { string fileVersion = ReadString(reader); // read the version string if(version != fileVersion) { throw new AxiomException("Invalid file: version incompatible, file reports {0}, Serializer is version {1}", fileVersion, version); } } else { throw new AxiomException("Invalid file: no header found."); } } /// <summary> /// Writes a file header and version string. /// </summary> protected void WriteFileHeader(BinaryWriter writer, string fileVersion) { writer.Write((short)MeshChunkID.Header); WriteString(writer, fileVersion); } protected void Seek(BinaryMemoryReader reader, long length) { Seek(reader, length, SeekOrigin.Current); } /// <summary> /// Skips to a particular part of the binary stream. /// </summary> /// <param name="length">Number of bytes to skip.</param> protected void Seek(BinaryMemoryReader reader, long length, SeekOrigin origin) { reader.Seek(length, origin); } protected bool IsEOF(BinaryMemoryReader reader) { return reader.PeekChar() == -1; } #endregion Methods } }
31.218415
135
0.595857
[ "MIT" ]
AustralianDisabilityLimited/MultiversePlatform
axiom/Engine/Serialization/Serializer.cs
14,579
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Reservations.Models { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; [Rest.Serialization.JsonTransformation] public partial class ReservationOrderResponse : IResource { /// <summary> /// Initializes a new instance of the ReservationOrderResponse class. /// </summary> public ReservationOrderResponse() { CustomInit(); } /// <summary> /// Initializes a new instance of the ReservationOrderResponse class. /// </summary> /// <param name="id">Identifier of the reservation</param> /// <param name="name">Name of the reservation</param> /// <param name="displayName">Friendly name for user to easily /// identified the reservation.</param> /// <param name="requestDateTime">This is the DateTime when the /// reservation was initially requested for purchase.</param> /// <param name="createdDateTime">This is the DateTime when the /// reservation was created.</param> /// <param name="expiryDate">This is the date when the Reservation will /// expire.</param> /// <param name="term">Possible values include: 'P1Y', 'P3Y'</param> /// <param name="provisioningState">Current state of the /// reservation.</param> /// <param name="type">Type of resource. /// "Microsoft.Capacity/reservations"</param> public ReservationOrderResponse(int? etag = default(int?), string id = default(string), string name = default(string), string displayName = default(string), System.DateTime? requestDateTime = default(System.DateTime?), System.DateTime? createdDateTime = default(System.DateTime?), System.DateTime? expiryDate = default(System.DateTime?), int? originalQuantity = default(int?), string term = default(string), string provisioningState = default(string), IList<ReservationResponse> reservationsProperty = default(IList<ReservationResponse>), string type = default(string)) { Etag = etag; Id = id; Name = name; DisplayName = displayName; RequestDateTime = requestDateTime; CreatedDateTime = createdDateTime; ExpiryDate = expiryDate; OriginalQuantity = originalQuantity; Term = term; ProvisioningState = provisioningState; ReservationsProperty = reservationsProperty; Type = type; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "etag")] public int? Etag { get; set; } /// <summary> /// Gets identifier of the reservation /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; private set; } /// <summary> /// Gets name of the reservation /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; private set; } /// <summary> /// Gets or sets friendly name for user to easily identified the /// reservation. /// </summary> [JsonProperty(PropertyName = "properties.displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets this is the DateTime when the reservation was /// initially requested for purchase. /// </summary> [JsonProperty(PropertyName = "properties.requestDateTime")] public System.DateTime? RequestDateTime { get; set; } /// <summary> /// Gets or sets this is the DateTime when the reservation was created. /// </summary> [JsonProperty(PropertyName = "properties.createdDateTime")] public System.DateTime? CreatedDateTime { get; set; } /// <summary> /// Gets or sets this is the date when the Reservation will expire. /// </summary> [JsonConverter(typeof(DateJsonConverter))] [JsonProperty(PropertyName = "properties.expiryDate")] public System.DateTime? ExpiryDate { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "properties.originalQuantity")] public int? OriginalQuantity { get; set; } /// <summary> /// Gets or sets possible values include: 'P1Y', 'P3Y' /// </summary> [JsonProperty(PropertyName = "properties.term")] public string Term { get; set; } /// <summary> /// Gets or sets current state of the reservation. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "properties.reservations")] public IList<ReservationResponse> ReservationsProperty { get; set; } /// <summary> /// Gets type of resource. "Microsoft.Capacity/reservations" /// </summary> [JsonProperty(PropertyName = "type")] public string Type { get; private set; } } }
39.849315
577
0.619629
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/Reservations/Management.Reservations/Generated/Models/ReservationOrderResponse.cs
5,818
C#
using System; using TLDAG.Core.Algorithms; using static TLDAG.Core.Exceptions.Errors; namespace TLDAG.Core.Collections { public partial class IntSet : IEquatable<IntSet>, IComparable<IntSet> { public int CompareTo(IntSet? other) => other is null ? 1 : Comparing.Compare(values, other.values); public bool Equals(IntSet? other) => CompareTo(other) == 0; } public partial class UIntSet : IEquatable<UIntSet>, IComparable<UIntSet> { public int CompareTo(UIntSet? other) => other is null ? 1 : Comparing.Compare(values, other.values); public bool Equals(UIntSet? other) => CompareTo(other) == 0; } public partial class CharSet : IEquatable<CharSet>, IComparable<CharSet> { public int CompareTo(CharSet? other) { throw NotYetImplemented(); } public bool Equals(CharSet? other) { throw NotYetImplemented(); } } public partial class ValueSet<T> : IEquatable<ValueSet<T>>, IComparable<ValueSet<T>> where T : notnull { public int CompareTo(ValueSet<T>? other) { throw NotYetImplemented(); } public bool Equals(ValueSet<T>? other) { throw NotYetImplemented(); } } public partial class StringSet : IEquatable<StringSet>, IComparable<StringSet> { public int CompareTo(StringSet? other) { throw NotYetImplemented(); } public bool Equals(StringSet? other) { throw NotYetImplemented(); } } }
25.415385
88
0.587167
[ "MIT" ]
tldag/tldag-dotnet
TLDAG.Core/Collections/Set.Compare.cs
1,654
C#
// <copyright file="MklFourierTransformProvider.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://mathnet.opensourcedotnet.info // // Copyright (c) 2009-2016 Math.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. // </copyright> #if NATIVE using System; using System.Numerics; using System.Threading; using MathNet.Numerics.Providers.Common.Mkl; namespace MathNet.Numerics.Providers.FourierTransform.Mkl { public class MklFourierTransformProvider : IFourierTransformProvider, IDisposable { class Kernel { public IntPtr Handle; public int Length; public FourierTransformScaling Scaling; } Kernel _kernel; /// <summary> /// Try to find out whether the provider is available, at least in principle. /// Verification may still fail if available, but it will certainly fail if unavailable. /// </summary> public bool IsAvailable() { return MklProvider.IsAvailable(minRevision: 11); } /// <summary> /// Initialize and verify that the provided is indeed available. If not, fall back to alternatives like the managed provider /// </summary> public void InitializeVerify() { MklProvider.Load(minRevision: 11); // we only support exactly one major version, since major version changes imply a breaking change. int fftMajor = SafeNativeMethods.query_capability((int)ProviderCapability.FourierTransformMajor); int fftMinor = SafeNativeMethods.query_capability((int)ProviderCapability.FourierTransformMinor); if (!(fftMajor == 1 && fftMinor >= 0)) { throw new NotSupportedException(string.Format("MKL Native Provider not compatible. Expecting fourier transform v1 but provider implements v{0}.", fftMajor)); } } /// <summary> /// Frees the memory allocated to the MKL memory pool. /// </summary> public void FreeBuffers() { Kernel kernel = Interlocked.Exchange(ref _kernel, null); if (kernel != null) { SafeNativeMethods.x_fft_free(ref kernel.Handle); } MklProvider.FreeBuffers(); } /// <summary> /// Frees the memory allocated to the MKL memory pool on the current thread. /// </summary> public void ThreadFreeBuffers() { MklProvider.ThreadFreeBuffers(); } /// <summary> /// Disable the MKL memory pool. May impact performance. /// </summary> public void DisableMemoryPool() { MklProvider.DisableMemoryPool(); } /// <summary> /// Retrieves information about the MKL memory pool. /// </summary> /// <param name="allocatedBuffers">On output, returns the number of memory buffers allocated.</param> /// <returns>Returns the number of bytes allocated to all memory buffers.</returns> public long MemoryStatistics(out int allocatedBuffers) { return MklProvider.MemoryStatistics(out allocatedBuffers); } /// <summary> /// Enable gathering of peak memory statistics of the MKL memory pool. /// </summary> public void EnablePeakMemoryStatistics() { MklProvider.EnablePeakMemoryStatistics(); } /// <summary> /// Disable gathering of peak memory statistics of the MKL memory pool. /// </summary> public void DisablePeakMemoryStatistics() { MklProvider.DisablePeakMemoryStatistics(); } /// <summary> /// Measures peak memory usage of the MKL memory pool. /// </summary> /// <param name="reset">Whether the usage counter should be reset.</param> /// <returns>The peak number of bytes allocated to all memory buffers.</returns> public long PeakMemoryStatistics(bool reset = true) { return MklProvider.PeakMemoryStatistics(reset); } public override string ToString() { return MklProvider.Describe(); } Kernel Configure(int length, FourierTransformScaling scaling) { Kernel kernel = Interlocked.Exchange(ref _kernel, null); if (kernel == null) { kernel = new Kernel { Length = length, Scaling = scaling }; SafeNativeMethods.z_fft_create(out kernel.Handle, length, ForwardScaling(scaling, length), BackwardScaling(scaling, length)); return kernel; } if (kernel.Length != length || kernel.Scaling != scaling) { SafeNativeMethods.x_fft_free(ref kernel.Handle); SafeNativeMethods.z_fft_create(out kernel.Handle, length, ForwardScaling(scaling, length), BackwardScaling(scaling, length)); kernel.Length = length; kernel.Scaling = scaling; return kernel; } return kernel; } void Release(Kernel kernel) { Kernel existing = Interlocked.Exchange(ref _kernel, kernel); if (existing != null) { SafeNativeMethods.x_fft_free(ref existing.Handle); } } public void ForwardInplace(Complex[] complex, FourierTransformScaling scaling) { Kernel kernel = Configure(complex.Length, scaling); SafeNativeMethods.z_fft_forward_inplace(kernel.Handle, complex); Release(kernel); } public void BackwardInplace(Complex[] complex, FourierTransformScaling scaling) { Kernel kernel = Configure(complex.Length, scaling); SafeNativeMethods.z_fft_backward_inplace(kernel.Handle, complex); Release(kernel); } public Complex[] Forward(Complex[] complexTimeSpace, FourierTransformScaling scaling) { Complex[] work = new Complex[complexTimeSpace.Length]; complexTimeSpace.Copy(work); ForwardInplace(work, scaling); return work; } public Complex[] Backward(Complex[] complexFrequenceSpace, FourierTransformScaling scaling) { Complex[] work = new Complex[complexFrequenceSpace.Length]; complexFrequenceSpace.Copy(work); BackwardInplace(work, scaling); return work; } static double ForwardScaling(FourierTransformScaling scaling, int length) { switch (scaling) { case FourierTransformScaling.SymmetricScaling: return Math.Sqrt(1.0/length); case FourierTransformScaling.ForwardScaling: return 1.0/length; default: return 1.0; } } static double BackwardScaling(FourierTransformScaling scaling, int length) { switch (scaling) { case FourierTransformScaling.SymmetricScaling: return Math.Sqrt(1.0/length); case FourierTransformScaling.BackwardScaling: return 1.0/length; default: return 1.0; } } public void Dispose() { FreeBuffers(); } } } #endif
35.391837
173
0.604083
[ "MIT" ]
XionWin/Mac-Dock-Bar
MathNet.Numerics/Providers/FourierTransform/Mkl/MklFourierTransformProvider.cs
8,673
C#
using System; using System.Windows.Forms; namespace Controls { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
21.2
65
0.566038
[ "BSD-3-Clause" ]
Krypton-Suite/Extended-Toolk
Source/Krypton Toolkit/Examples/Controls/Program.cs
424
C#
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Distributed; using Xunit; using Piranha.AttributeBuilder; using Piranha.Extend; using Piranha.Extend.Fields; using Piranha.Models; namespace Piranha.Tests.Services { [Collection("Integration tests")] public class SiteTestsMemoryCache : SiteTests { public override async Task InitializeAsync() { _cache = new Cache.MemoryCache((IMemoryCache)_services.GetService(typeof(IMemoryCache))); await base.InitializeAsync(); } } [Collection("Integration tests")] public class SiteTestsDistributedCache : SiteTests { public override async Task InitializeAsync() { _cache = new Cache.DistributedCache((IDistributedCache)_services.GetService(typeof(IDistributedCache))); await base.InitializeAsync(); } } [Collection("Integration tests")] public class SiteTests : BaseTestsAsync { private const string SITE_1 = "MyFirstSite"; private const string SITE_2 = "MySecondSite"; private const string SITE_4 = "MyFourthSite"; private const string SITE_5 = "MyFifthSite"; private const string SITE_6 = "MySixthSite"; private const string SITE_1_HOSTS = "mysite.com"; private readonly Guid SITE_1_ID = Guid.NewGuid(); [PageType(Title = "PageType")] public class MyPage : Models.Page<MyPage> { [Region] public TextField Text { get; set; } } [SiteType(Title = "SiteType")] public class MySiteContent : Models.SiteContent<MySiteContent> { [Region] public HtmlField Header { get; set; } [Region] public HtmlField Footer { get; set; } } public override async Task InitializeAsync() { using (var api = CreateApi()) { Piranha.App.Init(api); new ContentTypeBuilder(api) .AddType(typeof(MyPage)) .AddType(typeof(MySiteContent)) .Build(); await api.Sites.SaveAsync(new Site { Id = SITE_1_ID, SiteTypeId = "MySiteContent", InternalId = SITE_1, Title = SITE_1, Hostnames = SITE_1_HOSTS, IsDefault = true }); await api.Sites.SaveAsync(new Site { InternalId = SITE_4, Title = SITE_4 }); await api.Sites.SaveAsync(new Site { InternalId = SITE_5, Title = SITE_5 }); await api.Sites.SaveAsync(new Site { InternalId = SITE_6, Title = SITE_6 }); // Sites for testing hostname routing await api.Sites.SaveAsync(new Site { InternalId = "RoutingTest1", Title = "RoutingTest1", Hostnames = "mydomain.com,localhost" }); await api.Sites.SaveAsync(new Site { InternalId = "RoutingTest2", Title = "RoutingTest2", Hostnames = " mydomain.com/en" }); await api.Sites.SaveAsync(new Site { InternalId = "RoutingTest3", Title = "RoutingTest3", Hostnames = "sub.mydomain.com , sub2.localhost" }); var content = await MySiteContent.CreateAsync(api); content.Header = "<p>Lorem ipsum</p>"; content.Footer = "<p>Tellus Ligula</p>"; await api.Sites.SaveContentAsync(SITE_1_ID, content); var page1 = await MyPage.CreateAsync(api); page1.SiteId = SITE_1_ID; page1.Title = "Startpage"; page1.Text = "Welcome"; page1.IsHidden = true; page1.Published = DateTime.Now; await api.Pages.SaveAsync(page1); var page2 = await MyPage.CreateAsync(api); page2.SiteId = SITE_1_ID; page2.SortOrder = 1; page2.Title = "Second page"; page2.Text = "The second page"; await api.Pages.SaveAsync(page2); var page3 = await MyPage.CreateAsync(api); page3.SiteId = SITE_1_ID; page3.ParentId = page2.Id; page3.Title = "Subpage"; page3.Text = "The subpage"; page3.Published = DateTime.Now; await api.Pages.SaveAsync(page3); } } public override async Task DisposeAsync() { using (var api = CreateApi()) { var pages = await api.Pages.GetAllAsync(SITE_1_ID); foreach (var page in pages.Where(p => p.ParentId.HasValue)) { await api.Pages.DeleteAsync(page); } foreach (var page in pages.Where(p => !p.ParentId.HasValue)) { await api.Pages.DeleteAsync(page); } var types = await api.PageTypes.GetAllAsync(); foreach (var t in types) { await api.PageTypes.DeleteAsync(t); } var sites = await api.Sites.GetAllAsync(); foreach (var site in sites) { await api.Sites.DeleteAsync(site); } var siteTypes = await api.SiteTypes.GetAllAsync(); foreach (var t in siteTypes) { await api.SiteTypes.DeleteAsync(t); } } } [Fact] public void IsCached() { using (var api = CreateApi()) { Assert.Equal(((Api)api).IsCached, this.GetType() == typeof(SiteTestsMemoryCache) || this.GetType() == typeof(SiteTestsDistributedCache)); } } [Fact] public async Task Add() { using (var api = CreateApi()) { await api.Sites.SaveAsync(new Site { InternalId = SITE_2, Title = SITE_2 }); } } [Fact] public async Task AddDuplicateKey() { using (var api = CreateApi()) { await Assert.ThrowsAnyAsync<ValidationException>(async () => await api.Sites.SaveAsync(new Site { InternalId = SITE_1, Title = SITE_1 })); } } [Fact] public async Task AddEmptyFailure() { using (var api = CreateApi()) { await Assert.ThrowsAnyAsync<ValidationException>(async () => await api.Sites.SaveAsync(new Site())); } } [Fact] public async Task AddAndGenerateInternalId() { var id = Guid.NewGuid(); using (var api = CreateApi()) { await api.Sites.SaveAsync(new Site { Id = id, Title = "Generate internal id" }); var site = await api.Sites.GetByIdAsync(id); Assert.NotNull(site); Assert.Equal("GenerateInternalId", site.InternalId); } } [Fact] public async Task GetAll() { using (var api = CreateApi()) { var models = await api.Sites.GetAllAsync(); Assert.NotNull(models); Assert.NotEmpty(models); } } [Fact] public async Task GetNoneById() { using (var api = CreateApi()) { var none = await api.Sites.GetByIdAsync(Guid.NewGuid()); Assert.Null(none); } } [Fact] public async Task GetNoneByInternalId() { using (var api = CreateApi()) { var none = await api.Sites.GetByInternalIdAsync("none-existing-id"); Assert.Null(none); } } [Fact] public async Task GetById() { using (var api = CreateApi()) { var model = await api.Sites.GetByIdAsync(SITE_1_ID); Assert.NotNull(model); Assert.Equal(SITE_1, model.InternalId); } } [Fact] public async Task GetByInternalId() { using (var api = CreateApi()) { var model = await api.Sites.GetByInternalIdAsync(SITE_1); Assert.NotNull(model); Assert.Equal(SITE_1, model.InternalId); } } [Fact] public async Task GetDefault() { using (var api = CreateApi()) { var model = await api.Sites.GetDefaultAsync(); Assert.NotNull(model); Assert.Equal(SITE_1, model.InternalId); } } [Fact] public async Task GetSitemap() { using (var api = CreateApi()) { var sitemap = await api.Sites.GetSitemapAsync(); Assert.NotNull(sitemap); Assert.NotEmpty(sitemap); Assert.Equal("Startpage", sitemap[0].Title); } } [Fact] public async Task GetSitemapById() { using (var api = CreateApi()) { var sitemap = await api.Sites.GetSitemapAsync(SITE_1_ID); Assert.NotNull(sitemap); Assert.NotEmpty(sitemap); Assert.Equal("Startpage", sitemap[0].Title); } } [Fact] public async Task CheckPermlinkSyntax() { using (var api = CreateApi()) { var sitemap = await api.Sites.GetSitemapAsync(); foreach (var item in sitemap) { Assert.NotNull(item.Permalink); Assert.StartsWith("/", item.Permalink); } } } [Fact] public async Task GetUnpublishedSitemap() { using (var api = CreateApi()) { var sitemap = await api.Sites.GetSitemapAsync(onlyPublished: false); Assert.NotNull(sitemap); Assert.Equal(2, sitemap.Count); Assert.Equal("Startpage", sitemap[0].Title); Assert.Single(sitemap[1].Items); Assert.Equal("Subpage", sitemap[1].Items[0].Title); } } [Fact] public async Task CheckHiddenSitemapItems() { using (var api = CreateApi()) { var sitemap = await api.Sites.GetSitemapAsync(); Assert.Equal(1, sitemap.Count(s => s.IsHidden)); } } [Fact] public async Task ChangeDefaultSite() { using (var api = CreateApi()) { var site6 = await api.Sites.GetByInternalIdAsync(SITE_6); Assert.False(site6.IsDefault); site6.IsDefault = true; await api.Sites.SaveAsync(site6); var site1 = await api.Sites.GetByIdAsync(SITE_1_ID); Assert.False(site1.IsDefault); site1.IsDefault = true; await api.Sites.SaveAsync(site1); } } [Fact] public async Task CantRemoveDefault() { using (var api = CreateApi()) { var site1 = await api.Sites.GetByIdAsync(SITE_1_ID); Assert.True(site1.IsDefault); site1.IsDefault = false; await api.Sites.SaveAsync(site1); site1 = await api.Sites.GetByIdAsync(SITE_1_ID); Assert.True(site1.IsDefault); } } [Fact] public async Task GetUnpublishedSitemapById() { using (var api = CreateApi()) { var sitemap = await api.Sites.GetSitemapAsync(SITE_1_ID, onlyPublished: false); Assert.NotNull(sitemap); Assert.Equal(2, sitemap.Count); Assert.Equal("Startpage", sitemap[0].Title); Assert.Single(sitemap[1].Items); Assert.Equal("Subpage", sitemap[1].Items[0].Title); } } [Fact] public async Task Update() { using (var api = CreateApi()) { var model = await api.Sites.GetByIdAsync(SITE_1_ID); Assert.Equal(SITE_1_HOSTS, model.Hostnames); model.Hostnames = "Updated"; await api.Sites.SaveAsync(model); } } [Fact] public async Task Delete() { using (var api = CreateApi()) { var model = await api.Sites.GetByInternalIdAsync(SITE_4); Assert.NotNull(model); await api.Sites.DeleteAsync(model); } } [Fact] public async Task DeleteById() { using (var api = CreateApi()) { var model = await api.Sites.GetByInternalIdAsync(SITE_5); Assert.NotNull(model); await api.Sites.DeleteAsync(model.Id); } } [Fact] public async Task GetSiteContent() { using (var api = CreateApi()) { var model = await api.Sites.GetContentByIdAsync<MySiteContent>(SITE_1_ID); Assert.NotNull(model); Assert.Equal("<p>Lorem ipsum</p>", model.Header.Value); } } [Fact] public async Task UpdateSiteContent() { using (var api = CreateApi()) { var model = await api.Sites.GetContentByIdAsync<MySiteContent>(SITE_1_ID); Assert.NotNull(model); model.Footer = "<p>Fusce Parturient</p>"; await api.Sites.SaveContentAsync(SITE_1_ID, model); model = await api.Sites.GetContentByIdAsync<MySiteContent>(SITE_1_ID); Assert.NotNull(model); Assert.Equal("<p>Fusce Parturient</p>", model.Footer.Value); } } [Fact] public async Task GetDynamicSiteContent() { using (var api = CreateApi()) { var model = await api.Sites.GetContentByIdAsync(SITE_1_ID); Assert.NotNull(model); Assert.Equal("<p>Lorem ipsum</p>", model.Regions.Header.Value); } } [Fact] public async Task UpdateDynamicSiteContent() { using (var api = CreateApi()) { var model = await api.Sites.GetContentByIdAsync(SITE_1_ID); Assert.NotNull(model); model.Regions.Footer.Value = "<p>Purus Sit</p>"; await api.Sites.SaveContentAsync(SITE_1_ID, model); model = await api.Sites.GetContentByIdAsync(SITE_1_ID); Assert.NotNull(model); Assert.Equal("<p>Purus Sit</p>", model.Regions.Footer.Value); } } [Fact] public async Task GetByHostname() { using (var api = CreateApi()) { var model = await api.Sites.GetByHostnameAsync("mydomain.com"); Assert.NotNull(model); Assert.Equal("RoutingTest1", model.InternalId); } } [Fact] public async Task GetByHostnameSecond() { using (var api = CreateApi()) { var model = await api.Sites.GetByHostnameAsync("localhost"); Assert.NotNull(model); Assert.Equal("RoutingTest1", model.InternalId); } } [Fact] public async Task GetByHostnameSuffix() { using (var api = CreateApi()) { var model = await api.Sites.GetByHostnameAsync("mydomain.com/en"); Assert.NotNull(model); Assert.Equal("RoutingTest2", model.InternalId); } } [Fact] public async Task GetByHostnameSubdomain() { using (var api = CreateApi()) { var model = await api.Sites.GetByHostnameAsync("sub.mydomain.com"); Assert.NotNull(model); Assert.Equal("RoutingTest3", model.InternalId); } } [Fact] public async Task GetByHostnameSubdomainSecond() { using (var api = CreateApi()) { var model = await api.Sites.GetByHostnameAsync("sub2.localhost"); Assert.NotNull(model); Assert.Equal("RoutingTest3", model.InternalId); } } [Fact] public async Task GetByHostnameMissing() { using (var api = CreateApi()) { var model = await api.Sites.GetByHostnameAsync("nosite.com"); Assert.Null(model); } } } }
30.710145
117
0.466467
[ "MIT" ]
JarLob/piranha.core
test/Piranha.Tests/Services/SiteTests.cs
19,073
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Selector.UWP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Selector.UWP")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
35.896552
84
0.739673
[ "Apache-2.0" ]
15217711253/xamarin-forms-samples
Templates/DataTemplateSelector/UWP/Properties/AssemblyInfo.cs
1,044
C#
#if XAMARIN_APPLETLS // // AsyncProtocolRequest.cs // // Author: // Martin Baulig <martin.baulig@xamarin.com> // // Copyright (c) 2015 Xamarin, Inc. // using System; using System.IO; using System.Net; using System.Net.Security; using SD = System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace XamCore.Security.Tls { delegate AsyncOperationStatus AsyncOperation (AsyncProtocolRequest asyncRequest, AsyncOperationStatus status); class BufferOffsetSize { public byte[] Buffer; public int Offset; public int Size; public int TotalBytes; public bool Complete; public int EndOffset { get { return Offset + Size; } } public int Remaining { get { return Buffer.Length - Offset - Size; } } public BufferOffsetSize (byte[] buffer, int offset, int size) { Buffer = buffer; Offset = offset; Size = size; Complete = false; } public void Reset () { Offset = Size = 0; TotalBytes = 0; Complete = false; } public override string ToString () { return string.Format ("[BufferOffsetSize: {0} {1}]", Offset, Size); } } enum AsyncOperationStatus { NotStarted, Initialize, Continue, Running, Complete, WantRead, WantWrite, ReadDone } class AsyncProtocolRequest { public readonly MobileAuthenticatedStream Parent; public readonly BufferOffsetSize UserBuffer; int RequestedSize; public int CurrentSize; public int UserResult; AsyncOperation Operation; int Status; public readonly LazyAsyncResult UserAsyncResult; public AsyncProtocolRequest (MobileAuthenticatedStream parent, LazyAsyncResult lazyResult, BufferOffsetSize userBuffer = null) { Parent = parent; UserAsyncResult = lazyResult; UserBuffer = userBuffer; } public bool CompleteWithError (Exception ex) { Status = (int)AsyncOperationStatus.Complete; if (UserAsyncResult == null) return true; if (!UserAsyncResult.InternalPeekCompleted) UserAsyncResult.InvokeCallback (ex); return false; } internal void RequestRead (int size) { var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.WantRead, (int)AsyncOperationStatus.Running); Parent.Debug ("RequestRead: {0} {1}", oldStatus, size); if (oldStatus == AsyncOperationStatus.Running) RequestedSize = size; else if (oldStatus == AsyncOperationStatus.WantRead) RequestedSize += size; else if (oldStatus != AsyncOperationStatus.WantWrite) throw new InvalidOperationException (); } internal void RequestWrite () { var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.WantWrite, (int)AsyncOperationStatus.Running); if (oldStatus == AsyncOperationStatus.Running) return; else if (oldStatus != AsyncOperationStatus.WantRead && oldStatus != AsyncOperationStatus.WantWrite) throw new InvalidOperationException (); } internal void StartOperation (AsyncOperation operation) { if (Interlocked.CompareExchange (ref Status, (int)AsyncOperationStatus.Initialize, (int)AsyncOperationStatus.NotStarted) != (int)AsyncOperationStatus.NotStarted) throw new InvalidOperationException (); Operation = operation; if (UserAsyncResult == null) { StartOperation (); return; } ThreadPool.QueueUserWorkItem (_ => StartOperation ()); } void StartOperation () { try { ProcessOperation (); if (UserAsyncResult != null && !UserAsyncResult.InternalPeekCompleted) UserAsyncResult.InvokeCallback (UserResult); } catch (Exception ex) { if (UserAsyncResult == null) throw; if (!UserAsyncResult.InternalPeekCompleted) UserAsyncResult.InvokeCallback (ex); } } void ProcessOperation () { AsyncOperationStatus status; do { status = (AsyncOperationStatus)Interlocked.Exchange (ref Status, (int)AsyncOperationStatus.Running); Parent.Debug ("ProcessOperation: {0}", status); status = ProcessOperation (status); var oldStatus = (AsyncOperationStatus)Interlocked.CompareExchange (ref Status, (int)status, (int)AsyncOperationStatus.Running); Parent.Debug ("ProcessOperation done: {0} -> {1}", oldStatus, status); if (oldStatus != AsyncOperationStatus.Running) { if (status == oldStatus || status == AsyncOperationStatus.Continue || status == AsyncOperationStatus.Complete) status = oldStatus; else throw new InvalidOperationException (); } } while (status != AsyncOperationStatus.Complete); } AsyncOperationStatus ProcessOperation (AsyncOperationStatus status) { if (status == AsyncOperationStatus.WantRead) { if (RequestedSize < 0) throw new InvalidOperationException (); else if (RequestedSize == 0) return AsyncOperationStatus.Continue; Parent.Debug ("ProcessOperation - read inner: {0}", RequestedSize); var ret = Parent.InnerRead (RequestedSize); Parent.Debug ("ProcessOperation - read inner done: {0} - {1}", RequestedSize, ret); if (ret < 0) return AsyncOperationStatus.ReadDone; RequestedSize -= ret; if (ret == 0 || RequestedSize == 0) return AsyncOperationStatus.Continue; else return AsyncOperationStatus.WantRead; } else if (status == AsyncOperationStatus.WantWrite) { Parent.InnerWrite (); return AsyncOperationStatus.Continue; } else if (status == AsyncOperationStatus.Initialize || status == AsyncOperationStatus.Continue) { Parent.Debug ("ProcessOperation - continue"); status = Operation (this, status); Parent.Debug ("ProcessOperation - continue done: {0}", status); return status; } else if (status == AsyncOperationStatus.ReadDone) { Parent.Debug ("ProcessOperation - read done"); status = Operation (this, status); Parent.Debug ("ProcessOperation - read done: {0}", status); return status; } throw new InvalidOperationException (); } } } #endif
27.651163
164
0.713877
[ "BSD-3-Clause" ]
chamons/xamarin-macios
src/Security/Tls/AsyncProtocolRequest.cs
5,945
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WCMS.WebSystem.WebParts.Central.Security { public partial class UserProfile { /// <summary> /// hNewUserId control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HiddenField hNewUserId; /// <summary> /// hGroupFilter control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HiddenField hGroupFilter; /// <summary> /// hDataEntry control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HiddenField hDataEntry; /// <summary> /// divGeneral control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl divGeneral; /// <summary> /// panelGeneralHeading control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl panelGeneralHeading; /// <summary> /// linkHeader control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl linkHeader; /// <summary> /// FormProfile control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WCMS.WebSystem.WebParts.Central._CMS_Controls_UserProfileForm FormProfile; /// <summary> /// panelSecurity control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl panelSecurity; /// <summary> /// ChangePasswordForm1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WCMS.WebSystem.WebParts.Central.Controls.ChangePasswordForm ChangePasswordForm1; /// <summary> /// cmdUpdate control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlButton cmdUpdate; /// <summary> /// cmdUpdateAddNew control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton cmdUpdateAddNew; /// <summary> /// cmdCancel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button cmdCancel; /// <summary> /// ValidationSummary1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ValidationSummary ValidationSummary1; /// <summary> /// lblStatus control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblStatus; } }
36.43662
106
0.556049
[ "MIT" ]
dsalunga/mPortal
Portal/WebSystem/WebSystem-MVC/Content/Parts/Central/Security/UserProfile.ascx.designer.cs
5,176
C#
using Cron.Network.P2P; using Cron.Network.P2P.Payloads; namespace Cron.Plugins { public interface IP2PPlugin { bool OnP2PMessage(Message message); bool OnConsensusMessage(ConsensusPayload payload); } }
19.416667
58
0.712446
[ "MIT" ]
cronfoundation/cronium-core
Cron/Plugins/IP2PPlugin.cs
235
C#
using Microsoft.AspNetCore.Components.WebAssembly.Authentication; using Microsoft.Graph; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace ApiDemo.Library.Graph { public class MsalWrappedTokenProvider : IAuthenticationProvider { private readonly IAccessTokenProvider _accessTokenProvider; /// <summary> /// Default constructor /// </summary> /// <param name="accessTokenProvider">WebAssembly access token provider instance</param> public MsalWrappedTokenProvider(IAccessTokenProvider accessTokenProvider) { _accessTokenProvider = accessTokenProvider; } private const string MicrosoftGraphScope = "Sites.Read.All"; private string[] GetRelevantScopes(Uri resourceUri) { return new[] { $"{resourceUri}/{MicrosoftGraphScope}" }; } /// <summary> /// Authenticate the web request /// </summary> /// <param name="resource">Resource to get an access token for</param> /// <param name="request">Request to add the access token on</param> /// <returns></returns> public async Task AuthenticateRequestAsync(Uri resource, HttpRequestMessage request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (resource == null) { throw new ArgumentNullException(nameof(resource)); } request.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetAccessTokenAsync(resource).ConfigureAwait(false)); } /// <summary> /// Gets an access token for the requested resource and scopes /// </summary> /// <param name="resource">Resource to get access token for</param> /// <param name="scopes">Scopes to use when getting the access token</param> /// <returns>Obtained access token</returns> public async Task<string> GetAccessTokenAsync(Uri resource, string[] scopes) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } if (scopes == null) { throw new ArgumentNullException(nameof(scopes)); } var tokenResult = await _accessTokenProvider.RequestAccessToken(new AccessTokenRequestOptions() { // The scopes must specify the needed permissions for the app to work Scopes = scopes, }).ConfigureAwait(false); if (!tokenResult.TryGetToken(out AccessToken accessToken)) { throw new Exception("An error occured while trying to acquire the access token..."); } return accessToken.Value; } /// <summary> /// Gets an access token for the requested resource /// </summary> /// <param name="resource">Resource to get access token for</param> /// <returns>Obtained access token</returns> public async Task<string> GetAccessTokenAsync(Uri resource) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } return await GetAccessTokenAsync(resource, GetRelevantScopes(resource)); } public async Task AuthenticateRequestAsync(HttpRequestMessage request) { request.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetAccessTokenAsync(new("https://graph.microsoft.com/" + MicrosoftGraphScope)).ConfigureAwait(false)); } } }
35.127273
124
0.604037
[ "MIT" ]
dotnet-devops/Examples
ApiDemo/ApiDemo.Library/Graph/MsalWrappedTokenProvider.cs
3,866
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("GetQuote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GetQuote")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("51d7204a-f7b7-405e-a826-4c86f0e59281")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.216216
103
0.749328
[ "MIT" ]
fredatgithub/GetQuote
GetQuote/Properties/AssemblyInfo.cs
1,513
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.ElasticFileSystem; using Amazon.ElasticFileSystem.Model; namespace Amazon.PowerShell.Cmdlets.EFS { /// <summary> /// Deletes the specified access point. After deletion is complete, new clients can no /// longer connect to the access points. Clients connected to the access point at the /// time of deletion will continue to function until they terminate their connection. /// /// /// <para> /// This operation requires permissions for the <code>elasticfilesystem:DeleteAccessPoint</code> /// action. /// </para> /// </summary> [Cmdlet("Remove", "EFSAccessPoint", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)] [OutputType("None")] [AWSCmdlet("Calls the Amazon Elastic File System DeleteAccessPoint API operation.", Operation = new[] {"DeleteAccessPoint"}, SelectReturnType = typeof(Amazon.ElasticFileSystem.Model.DeleteAccessPointResponse))] [AWSCmdletOutput("None or Amazon.ElasticFileSystem.Model.DeleteAccessPointResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.ElasticFileSystem.Model.DeleteAccessPointResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class RemoveEFSAccessPointCmdlet : AmazonElasticFileSystemClientCmdlet, IExecutor { #region Parameter AccessPointId /// <summary> /// <para> /// <para>The ID of the access point that you want to delete.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String AccessPointId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.ElasticFileSystem.Model.DeleteAccessPointResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the AccessPointId parameter. /// The -PassThru parameter is deprecated, use -Select '^AccessPointId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^AccessPointId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.AccessPointId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-EFSAccessPoint (DeleteAccessPoint)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.ElasticFileSystem.Model.DeleteAccessPointResponse, RemoveEFSAccessPointCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.AccessPointId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.AccessPointId = this.AccessPointId; #if MODULAR if (this.AccessPointId == null && ParameterWasBound(nameof(this.AccessPointId))) { WriteWarning("You are passing $null as a value for parameter AccessPointId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.ElasticFileSystem.Model.DeleteAccessPointRequest(); if (cmdletContext.AccessPointId != null) { request.AccessPointId = cmdletContext.AccessPointId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.ElasticFileSystem.Model.DeleteAccessPointResponse CallAWSServiceOperation(IAmazonElasticFileSystem client, Amazon.ElasticFileSystem.Model.DeleteAccessPointRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic File System", "DeleteAccessPoint"); try { #if DESKTOP return client.DeleteAccessPoint(request); #elif CORECLR return client.DeleteAccessPointAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String AccessPointId { get; set; } public System.Func<Amazon.ElasticFileSystem.Model.DeleteAccessPointResponse, RemoveEFSAccessPointCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
45.219731
284
0.618604
[ "Apache-2.0" ]
JekzVadaria/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/ElasticFileSystem/Basic/Remove-EFSAccessPoint-Cmdlet.cs
10,084
C#
using System; using System.Linq; using System.Threading.Tasks; using GoalTracker.Entities; using GoalTracker.Services; using Microsoft.AppCenter.Crashes; namespace GoalTracker.ViewModels { public class GoalTaskViewModel : BaseViewModel, IGoalTaskViewModel { private readonly IGoalTaskRepository goalTaskRepository; private GoalTask goalTask; private GoalTask[] goalTasks; public GoalTaskViewModel(Goal parent, IGoalTaskRepository goalTaskRepository) { this.goalTaskRepository = goalTaskRepository; Parent = parent; } public GoalTask SelectedGoalTask { get => goalTask; set { goalTask = value; OnPropertyChanged(); } } public Goal Parent { get; set; } public string ParentTitle => Parent == null ? "N/A" : Parent.Title; public GoalTask[] GoalTasks { get => goalTasks; set { goalTasks = value; OnPropertyChanged(); } } public async Task LoadTasks() { try { var goalTaskCollection = await goalTaskRepository.GetAllByParentAsync(Parent); GoalTasks = goalTaskCollection.ToArray(); } catch (Exception ex) { Crashes.TrackError(ex); } } } }
25.288136
94
0.546247
[ "MIT" ]
Zasam/GoalTracker
GoalTracker/GoalTracker/ViewModels/GoalTaskViewModel.cs
1,494
C#
using System.Collections.Generic; using Horizon.Payment.Alipay.Response; namespace Horizon.Payment.Alipay.Request { /// <summary> /// alipay.marketing.campaign.discount.budget.query /// </summary> public class AlipayMarketingCampaignDiscountBudgetQueryRequest : IAlipayRequest<AlipayMarketingCampaignDiscountBudgetQueryResponse> { /// <summary> /// 营销立减活动预算查询 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.marketing.campaign.discount.budget.query"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.967742
135
0.55302
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Request/AlipayMarketingCampaignDiscountBudgetQueryRequest.cs
2,870
C#
namespace Tailspin.Web.Survey.Shared.Stores { using Models; using System.Threading.Tasks; public interface ISurveyAnswersSummaryStore { Task InitializeAsync(); Task<SurveyAnswersSummary> GetSurveyAnswersSummaryAsync(string tenant, string slugName); Task DeleteSurveyAnswersSummaryAsync(string tenant, string slugName); Task SaveSurveyAnswersSummaryAsync(SurveyAnswersSummary surveyAnswersSummary); Task MergeSurveyAnswersSummaryAsync(SurveyAnswersSummary partialSurveyAnswersSummary); } }
37.266667
104
0.763864
[ "MIT" ]
msajidirfan/cloud-services-to-service-fabric
servicefabric/Tailspin/Tailspin.Web.Survey.Shared/Stores/ISurveyAnswersSummaryStore.cs
561
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("YouTubeManagerWpf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("YouTubeManagerWpf")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.535714
98
0.710747
[ "MIT" ]
congdinh2008/YouTubeManager
YouTubeManager/YouTubeManagerWpf/Properties/AssemblyInfo.cs
2,385
C#
using ExtendedDatabase; using NUnit.Framework; using System; namespace Tests { public class ExtendedDatabaseTests { private const int DatabaseCapacity = 16; private Person[] people; private ExtendedDatabase.ExtendedDatabase extendedDB; [SetUp] public void Setup() { this.extendedDB = new ExtendedDatabase.ExtendedDatabase(); this.people = new Person[] { new Person(2636, "Hihi"), new Person(2635, "Lili"), new Person(2634, "Kiki"), new Person(2633, "Didi"), new Person(2632, "Vivi"), new Person(2631, "Bibi"), new Person(2630, "Titi"), new Person(2629, "Jiji"), new Person(2628, "Gigi"), new Person(2627, "Sisi"), new Person(2626, "Pipi"), new Person(2625, "Zizi"), new Person(2624, "Fifi"), new Person(2623, "Tedi"), new Person(2622, "Simi"), new Person(2621, "Mimi"), }; } [Test] public void ConstructorInitializeThePeopleInDataWithExactly16People() { //Arrange this.extendedDB = new ExtendedDatabase.ExtendedDatabase(people); //Assert Assert.AreEqual(DatabaseCapacity, extendedDB.Count); } [Test] public void CheckIfArrayIsOverCapacity() { this.people = new Person[17]; //Assert Assert.Throws<ArgumentException>(() => new ExtendedDatabase.ExtendedDatabase(people)); } [Test] public void ThrowExeptionIfTryToAddMoreThanDatabaseCapacity() { this.extendedDB = new ExtendedDatabase.ExtendedDatabase(this.people); //Assert Assert.Throws<InvalidOperationException>(() => this.extendedDB.Add(new Person(3698, "Jizi"))); } [Test] public void ThrowExeptionIfTryToAddSamePerosnWithAlredyExistingName() { this.extendedDB.Add(new Person(2621, "Mimi")); Assert.Throws<InvalidOperationException>(() => this.extendedDB.Add(new Person(7979, "Mimi"))); ; } [Test] public void ThrowExeptionIfTryToAddSamePerosnWithAlredyExistingId() { this.extendedDB.Add(new Person(2621, "Mimi")); Assert.Throws<InvalidOperationException>(() => this.extendedDB.Add(new Person(2621, "Jana"))); ; } [Test] public void RemoveOperationShouldReturExeption() { //Arrange this.extendedDB = new ExtendedDatabase.ExtendedDatabase(); //Assert Assert.Throws<InvalidOperationException>(() => this.extendedDB.Remove()); } [Test] public void RemoveShouldRemoveAtLastIndex() { this.extendedDB = new ExtendedDatabase.ExtendedDatabase(new Person(26231, "Jino")); this.extendedDB.Remove(); int expectedCount = 0; int actualCount = this.extendedDB.Count; Assert.AreEqual(expectedCount, actualCount); } [Test] public void FindByUserNameShouldReturnMatchingName() { this.extendedDB = new ExtendedDatabase.ExtendedDatabase(this.people); Person actualPerson = people[15]; Person expectedPerson = this.extendedDB.FindByUsername("Mimi"); Assert.AreEqual(expectedPerson, actualPerson); } [Test] public void FindByUserNameShouldReturnMatchingNameIsFalse() { this.extendedDB = new ExtendedDatabase.ExtendedDatabase(this.people); Person actualPerson = people[15]; Assert.Throws<InvalidOperationException>(() => this.extendedDB.FindByUsername("Desi")); } [Test] [TestCase("")] [TestCase(null)] public void FindByUserNameShouldThrowArgumentNullExceptionWhenTheNameIsNullOrEmpty(string name) { Assert.Throws<ArgumentNullException>(() => this.extendedDB.FindByUsername(name)); } [TestCase(-1)] public void FindByUserIDShouldThrowArgumentOutOfRangeExceptionWhenTheIdIsLEssThanZero(int Id) { Assert.Throws<ArgumentOutOfRangeException>(() => this.extendedDB.FindById(Id)); } [TestCase(2646)] [TestCase(000000)] [TestCase(123313540)] public void FindByUserIDShouldThrowInvalidOperationExceptionTheIdDoesntExist(int Id) { Assert.Throws<InvalidOperationException>(() => this.extendedDB.FindById(Id)); } [Test] public void FindByIdShouldReturnMatchingId() { this.extendedDB = new ExtendedDatabase.ExtendedDatabase(this.people); Person actualPerson = people[15]; Person expectedPerson = this.extendedDB.FindById(2621); Assert.AreEqual(expectedPerson, actualPerson); } } }
32.384615
108
0.590657
[ "MIT" ]
Anzzhhela98/CSharp-Advanced
C# OOP/07.Unit Testing/Unit Testing - Exercises/DatabaseExtended.Tests/ExtendedDatabase.Tests.cs
5,052
C#
using Medic.Entities.Bases; using Medic.Entities.Contracts; using Medic.Mappers.Contracts; using System; namespace Medic.Entities { /// <summary> /// CP -> Implant /// </summary> [Serializable] public partial class Implant : BaseEntity, IModelBuilder, IModelTransformer { public int Id { get; set; } public int? ProductTypeId { get; set; } public ImplantProductType ProductType { get; set; } public string TradeName { get; set; } public string ReferenceNumber { get; set; } public string Manufacturer { get; set; } public int? ProviderId { get; set; } public Provider Provider { get; set; } public string Code { get; set; } public DateTime Date { get; set; } public string SerialNumber { get; set; } public int Stickers { get; set; } public string DistributorInvoiceNumber { get; set; } public DateTime DistributorInvoiceDate { get; set; } public decimal NhifAmount { get; set; } public decimal PatientAmount { get; set; } public decimal TotalAmount { get; set; } public Procedure Procedure { get; set; } public int? ClinicProcedureId { get; set; } public ClinicProcedure ClinicProcedure { get; set; } } }
24.481481
79
0.617247
[ "MIT" ]
eeevgeniev/ITSPMedic
src/Medic.Entities/Implant.cs
1,324
C#
 namespace BigRogue.CharacterAvatar { /// <summary> /// 换装的孔位 /// </summary> public enum AvatarSlot { MainBody = 0, Beard = 1, Ears = 2, Hair = 3, Face = 4, Horns = 5, Wing = 6, Bag = 7, MainHand = 101, OffHand = 102 } /// <summary> /// Avatar的部件类型,除了武器,部件类型的孔位是固定的 /// </summary> public enum AvatarPartType { MainBody = 0, Beard = 1, Ears = 2, Hair = 3, Face = 4, Horns = 5, Wing = 6, Bag = 7, Weapon = 100 } /// <summary> /// Avatar部件的挂载类型 /// </summary> public enum MountingType { None = -1, Root = 0, Base = 1, Head = 2, Back = 3, LeftHand = 4, RightHand = 5, BothHand = 6, } /// <summary> /// 挂点位置枚举 /// </summary> public enum MountingPoint { Root, Base, Head, Back, Left, Right } /// <summary> /// 性别类型 /// </summary> public enum SexType { None = 0, Female = 1, Male = 2, Other = 3, } }
17.753846
43
0.418544
[ "MIT" ]
BigWan/BigRogue
BigRouge/Assets/Scripts/Avatar/AvatarDefine.cs.cs
1,240
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.ContainerApps.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// The configuration settings of the Azure Active Directory app /// registration. /// </summary> public partial class AzureActiveDirectoryRegistration { /// <summary> /// Initializes a new instance of the AzureActiveDirectoryRegistration /// class. /// </summary> public AzureActiveDirectoryRegistration() { CustomInit(); } /// <summary> /// Initializes a new instance of the AzureActiveDirectoryRegistration /// class. /// </summary> /// <param name="openIdIssuer">The OpenID Connect Issuer URI that /// represents the entity which issues access tokens for this /// application. /// When using Azure Active Directory, this value is the URI of the /// directory tenant, e.g. /// https://login.microsoftonline.com/v2.0/{tenant-guid}/. /// This URI is a case-sensitive identifier for the token issuer. /// More information on OpenID Connect Discovery: /// http://openid.net/specs/openid-connect-discovery-1_0.html</param> /// <param name="clientId">The Client ID of this relying party /// application, known as the client_id. /// This setting is required for enabling OpenID Connection /// authentication with Azure Active Directory or /// other 3rd party OpenID Connect providers. /// More information on OpenID Connect: /// http://openid.net/specs/openid-connect-core-1_0.html</param> /// <param name="clientSecretRefName">The app secret ref name that /// contains the client secret of the relying party /// application.</param> /// <param name="clientSecretCertificateThumbprint">An alternative to /// the client secret, that is the thumbprint of a certificate used for /// signing purposes. This property acts as /// a replacement for the Client Secret. It is also optional.</param> /// <param name="clientSecretCertificateSubjectAlternativeName">An /// alternative to the client secret thumbprint, that is the subject /// alternative name of a certificate used for signing purposes. This /// property acts as /// a replacement for the Client Secret Certificate Thumbprint. It is /// also optional.</param> /// <param name="clientSecretCertificateIssuer">An alternative to the /// client secret thumbprint, that is the issuer of a certificate used /// for signing purposes. This property acts as /// a replacement for the Client Secret Certificate Thumbprint. It is /// also optional.</param> public AzureActiveDirectoryRegistration(string openIdIssuer = default(string), string clientId = default(string), string clientSecretRefName = default(string), string clientSecretCertificateThumbprint = default(string), string clientSecretCertificateSubjectAlternativeName = default(string), string clientSecretCertificateIssuer = default(string)) { OpenIdIssuer = openIdIssuer; ClientId = clientId; ClientSecretRefName = clientSecretRefName; ClientSecretCertificateThumbprint = clientSecretCertificateThumbprint; ClientSecretCertificateSubjectAlternativeName = clientSecretCertificateSubjectAlternativeName; ClientSecretCertificateIssuer = clientSecretCertificateIssuer; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the OpenID Connect Issuer URI that represents the /// entity which issues access tokens for this application. /// When using Azure Active Directory, this value is the URI of the /// directory tenant, e.g. /// https://login.microsoftonline.com/v2.0/{tenant-guid}/. /// This URI is a case-sensitive identifier for the token issuer. /// More information on OpenID Connect Discovery: /// http://openid.net/specs/openid-connect-discovery-1_0.html /// </summary> [JsonProperty(PropertyName = "openIdIssuer")] public string OpenIdIssuer { get; set; } /// <summary> /// Gets or sets the Client ID of this relying party application, known /// as the client_id. /// This setting is required for enabling OpenID Connection /// authentication with Azure Active Directory or /// other 3rd party OpenID Connect providers. /// More information on OpenID Connect: /// http://openid.net/specs/openid-connect-core-1_0.html /// </summary> [JsonProperty(PropertyName = "clientId")] public string ClientId { get; set; } /// <summary> /// Gets or sets the app secret ref name that contains the client /// secret of the relying party application. /// </summary> [JsonProperty(PropertyName = "clientSecretRefName")] public string ClientSecretRefName { get; set; } /// <summary> /// Gets or sets an alternative to the client secret, that is the /// thumbprint of a certificate used for signing purposes. This /// property acts as /// a replacement for the Client Secret. It is also optional. /// </summary> [JsonProperty(PropertyName = "clientSecretCertificateThumbprint")] public string ClientSecretCertificateThumbprint { get; set; } /// <summary> /// Gets or sets an alternative to the client secret thumbprint, that /// is the subject alternative name of a certificate used for signing /// purposes. This property acts as /// a replacement for the Client Secret Certificate Thumbprint. It is /// also optional. /// </summary> [JsonProperty(PropertyName = "clientSecretCertificateSubjectAlternativeName")] public string ClientSecretCertificateSubjectAlternativeName { get; set; } /// <summary> /// Gets or sets an alternative to the client secret thumbprint, that /// is the issuer of a certificate used for signing purposes. This /// property acts as /// a replacement for the Client Secret Certificate Thumbprint. It is /// also optional. /// </summary> [JsonProperty(PropertyName = "clientSecretCertificateIssuer")] public string ClientSecretCertificateIssuer { get; set; } } }
47.837838
355
0.658475
[ "MIT" ]
ElleTojaroon/azure-sdk-for-net
sdk/app/Microsoft.Azure.Management.ContainerApps/src/Generated/Models/AzureActiveDirectoryRegistration.cs
7,080
C#
#define SQLITE_ASCII #define SQLITE_DISABLE_LFS #define SQLITE_ENABLE_OVERSIZE_CELL_CHECK #define SQLITE_MUTEX_OMIT #define SQLITE_OMIT_AUTHORIZATION #define SQLITE_OMIT_DEPRECATED #define SQLITE_OMIT_GET_TABLE #define SQLITE_OMIT_INCRBLOB #define SQLITE_OMIT_LOOKASIDE #define SQLITE_OMIT_SHARED_CACHE #define SQLITE_OMIT_UTF16 #define SQLITE_OMIT_WAL #define SQLITE_OS_WIN #define SQLITE_SYSTEM_MALLOC #define VDBE_PROFILE_OFF #define WINDOWS_MOBILE #define NDEBUG #define _MSC_VER #define YYFALLBACK using Pgno = System.UInt32; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2001 September 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 header file defines the interface that the sqlite page cache ** subsystem. The page cache subsystem reads and writes a file a page ** at a time and provides a journal for rollback. ************************************************************************* ** 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-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#if !_PAGER_H_ //#define _PAGER_H_ /* ** Default maximum size for persistent journal files. A negative ** value means no limit. This value may be overridden using the ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". */ #if !SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT const int SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT = -1;//#define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 #endif /* ** The type used to represent a page number. The first page in a file ** is called page 1. 0 is used to represent "not a page". */ //typedef u32 Pgno; /* ** Each open file is managed by a separate instance of the "Pager" structure. */ //typedef struct Pager Pager; /* ** Handle type for pages. */ //typedef struct PgHdr DbPage; /* ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is ** reserved for working around a windows/posix incompatibility). It is ** used in the journal to signify that the remainder of the journal file ** is devoted to storing a master journal name - there are no more pages to ** roll back. See comments for function writeMasterJournal() in pager.c ** for details. */ //#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) static Pgno PAGER_MJ_PGNO( Pager x ) { return ( (Pgno)( ( PENDING_BYTE / ( ( x ).pageSize ) ) + 1 ) ); } /* ** Allowed values for the flags parameter to sqlite3PagerOpen(). ** ** NOTE: These values must match the corresponding BTREE_ values in btree.h. */ //#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ //#define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */ //#define PAGER_MEMORY 0x0004 /* In-memory database */ const int PAGER_OMIT_JOURNAL = 0x0001; const int PAGER_NO_READLOCK = 0x0002; const int PAGER_MEMORY = 0x0004; /* ** Valid values for the second argument to sqlite3PagerLockingMode(). */ //#define PAGER_LOCKINGMODE_QUERY -1 //#define PAGER_LOCKINGMODE_NORMAL 0 //#define PAGER_LOCKINGMODE_EXCLUSIVE 1 static int PAGER_LOCKINGMODE_QUERY = -1; static int PAGER_LOCKINGMODE_NORMAL = 0; static int PAGER_LOCKINGMODE_EXCLUSIVE = 1; /* ** Numeric constants that encode the journalmode. */ //#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ //#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ //#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ //#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ //#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ //#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ //#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ const int PAGER_JOURNALMODE_QUERY = -1; const int PAGER_JOURNALMODE_DELETE = 0; const int PAGER_JOURNALMODE_PERSIST = 1; const int PAGER_JOURNALMODE_OFF = 2; const int PAGER_JOURNALMODE_TRUNCATE = 3; const int PAGER_JOURNALMODE_MEMORY = 4; const int PAGER_JOURNALMODE_WAL = 5; /* ** The remainder of this file contains the declarations of the functions ** that make up the Pager sub-system API. See source code comments for ** a detailed description of each routine. */ /* Open and close a Pager connection. */ //int sqlite3PagerOpen( // sqlite3_vfs*, // Pager **ppPager, // const char*, // int, // int, // int, //// void()(DbPage) //); //int sqlite3PagerClose(Pager *pPager); //int sqlite3PagerReadFileheader(Pager*, int, unsigned char); /* Functions used to configure a Pager object. */ //void sqlite3PagerSetBusyhandler(Pager*, int()(void ), object ); //int sqlite3PagerSetPagesize(Pager*, u32*, int); //int sqlite3PagerMaxPageCount(Pager*, int); //void sqlite3PagerSetCachesize(Pager*, int); //void sqlite3PagerSetSafetyLevel(Pager*,int,int,int); //int sqlite3PagerLockingMode(Pager *, int); //int sqlite3PagerSetJournalMode(Pager *, int); //int sqlite3PagerGetJournalMode(Pager); //int sqlite3PagerOkToChangeJournalMode(Pager); //i64 sqlite3PagerJournalSizeLimit(Pager *, i64); //sqlite3_backup **sqlite3PagerBackupPtr(Pager); /* Functions used to obtain and release page references. */ //int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); //#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) //DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); //void sqlite3PagerRef(DbPage); //void sqlite3PagerUnref(DbPage); /* Operations on page references. */ //int sqlite3PagerWrite(DbPage); //void sqlite3PagerDontWrite(DbPage); //int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); //int sqlite3PagerPageRefcount(DbPage); //void *sqlite3PagerGetData(DbPage ); //void *sqlite3PagerGetExtra(DbPage ); /* Functions used to manage pager transactions and savepoints. */ //void sqlite3PagerPagecount(Pager*, int); //int sqlite3PagerBegin(Pager*, int exFlag, int); //int sqlite3PagerCommitPhaseOne(Pager*,string zMaster, int); //int sqlite3PagerExclusiveLock(Pager); //int sqlite3PagerSync(Pager *pPager); //int sqlite3PagerCommitPhaseTwo(Pager); //int sqlite3PagerRollback(Pager); //int sqlite3PagerOpenSavepoint(Pager *pPager, int n); //int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); //int sqlite3PagerSharedLock(Pager *pPager); //int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int); //int sqlite3PagerWalSupported(Pager* pPager); //int sqlite3PagerWalCallback(Pager* pPager); //int sqlite3PagerOpenWal(Pager* pPager, int* pisOpen); //int sqlite3PagerCloseWal(Pager* pPager); /* Functions used to query pager state and configuration. */ //u8 sqlite3PagerIsreadonly(Pager); //int sqlite3PagerRefcount(Pager); //int sqlite3PagerMemUsed(Pager); //string sqlite3PagerFilename(Pager); //const sqlite3_vfs *sqlite3PagerVfs(Pager); //sqlite3_file *sqlite3PagerFile(Pager); //string sqlite3PagerJournalname(Pager); //int sqlite3PagerNosync(Pager); //void *sqlite3PagerTempSpace(Pager); //int sqlite3PagerIsMemdb(Pager); /* Functions used to truncate the database file. */ //void sqlite3PagerTruncateImage(Pager*,Pgno); //#if (SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) //void *sqlite3PagerCodec(DbPage ); //#endif /* Functions to support testing and debugging. */ //#if !NDEBUG || SQLITE_TEST // Pgno sqlite3PagerPagenumber(DbPage); // int sqlite3PagerIswriteable(DbPage); //#endif //#if SQLITE_TEST // int *sqlite3PagerStats(Pager); // void sqlite3PagerRefdump(Pager); // void disable_simulated_io_errors(void); // void enable_simulated_io_errors(void); //#else //# define disable_simulated_io_errors() //# define enable_simulated_io_errors() //#endif } }
37.939655
99
0.67496
[ "MIT" ]
BOBO41/CasinosClient
Assets/Plugins/Sqlite/Impl/pager_h.cs
8,802
C#
using System; using System.Runtime.Serialization; using UnityEngine; namespace UE.Serialization { /// <summary> /// Serialization wrapper for unity vector3. /// </summary> [Serializable] public class SerializedVector3 : ISerializable { public Vector3 vector; public SerializedVector3() { vector = new Vector3(); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("X", vector.x); info.AddValue("Y", vector.y); info.AddValue("Z", vector.z); } protected SerializedVector3(SerializationInfo info, StreamingContext context) { vector = new Vector3 { x = (float) info.GetValue("X", typeof(float)), y = (float) info.GetValue("Y", typeof(float)), z = (float) info.GetValue("Z", typeof(float)) }; } } }
26.026316
91
0.55814
[ "MIT" ]
hendrik-schulte/unity-binary-serialization
SerializedVector3.cs
991
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml.Serialization; namespace ProductShop.XMLHelper { public static class XMLConverter { public static string Serialize<T>( T dataTransferObjects, string xmlRootAttributeName) { XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootAttributeName)); var builder = new StringBuilder(); using (var write = new StringWriter(builder)) { serializer.Serialize(write, dataTransferObjects, GetXmlNamespaces()); return builder.ToString(); }; } public static string Serialize<T>( T[] dataTransferObjects, string xmlRootAttributeName) { XmlSerializer serializer = new XmlSerializer(typeof(T[]), new XmlRootAttribute(xmlRootAttributeName)); var builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { serializer.Serialize(writer, dataTransferObjects, GetXmlNamespaces()); return builder.ToString(); } } public static T[] Deserializer<T>( string xmlObjectsAsString, string xmlRootAttributeName) { XmlSerializer serializer = new XmlSerializer(typeof(T[]), new XmlRootAttribute(xmlRootAttributeName)); var dataTransferObjects = serializer.Deserialize(new StringReader(xmlObjectsAsString)) as T[]; return dataTransferObjects; } public static T Deserializer<T>( string xmlObjectsAsString, string xmlRootAttributeName, bool isSampleObject) where T : class { XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootAttributeName)); var dataTransferObjects = serializer.Deserialize(new StringReader(xmlObjectsAsString)) as T; return dataTransferObjects; } private static XmlSerializerNamespaces GetXmlNamespaces() { XmlSerializerNamespaces xmlNamespaces = new XmlSerializerNamespaces(); xmlNamespaces.Add(string.Empty, string.Empty); return xmlNamespaces; } } }
31.730769
115
0.6
[ "MIT" ]
q2kPetrov/SoftUni
Entity Framework Core/Exercises/09. XML Processing/ProductShop/ProductShop/XMLHelper/XMLConverter.cs
2,477
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CognitiveInsta.Core.WebInfographic.Aliases { public class ASpirit : Alias { public override string GetResult(ProfileInfo info) { return info.NameOfMaxWeightEmo; } } }
20.176471
58
0.693878
[ "Unlicense" ]
Nox7atra/Cognitive-Instagram-Infographics
CognitiveInsta/Core/WebInfographic/Aliases/ASpirit.cs
345
C#
using System.Reflection; using Core.Commands; using Core.Events; using Core.Events.External; using Core.Ids; using Core.Projections; using Core.Queries; using Core.Requests; using Core.Tracing; using Core.Tracing.Causation; using Core.Tracing.Correlation; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Core; public static class Config { public static IServiceCollection AddCoreServices(this IServiceCollection services) { services.AddMediatR() .AddScoped<ICommandBus, CommandBus>() .AddScoped<IQueryBus, QueryBus>() .AddTracing() .AddEventBus(); services.TryAddScoped<IExternalEventProducer, NulloExternalEventProducer>(); services.TryAddScoped<IExternalCommandBus, ExternalCommandBus>(); services.TryAddScoped<IIdGenerator, NulloIdGenerator>(); return services; } public static IServiceCollection AddTracing(this IServiceCollection services) { services.TryAddScoped<ICorrelationIdFactory, GuidCorrelationIdFactory>(); services.TryAddScoped<ICausationIdFactory, GuidCausationIdFactory>(); services.TryAddScoped<ICorrelationIdProvider, CorrelationIdProvider>(); services.TryAddScoped<ICausationIdProvider, CausationIdProvider>(); services.TryAddScoped<ITraceMetadataProvider, TraceMetadataProvider>(); services.TryAddScoped<ITracingScopeFactory, TracingScopeFactory>(); services.TryAddScoped<Func<IServiceProvider, TraceMetadata?, TracingScope>>(sp => (scopedServiceProvider, traceMetadata) => sp.GetRequiredService<ITracingScopeFactory>().CreateTraceScope(scopedServiceProvider, traceMetadata) ); services.TryAddScoped<Func<IServiceProvider, EventEnvelope?, TracingScope>>(sp => (scopedServiceProvider, eventEnvelope) => sp.GetRequiredService<ITracingScopeFactory>() .CreateTraceScope(scopedServiceProvider, eventEnvelope) ); return services; } private static IServiceCollection AddMediatR(this IServiceCollection services) { return services .AddScoped<IMediator, Mediator>() .AddTransient<ServiceFactory>(sp => sp.GetRequiredService!); } public static IServiceCollection AddProjections(this IServiceCollection services, params Assembly[] assemblies) { services.AddSingleton<IProjectionPublisher, ProjectionPublisher>(); var assembliesToScan = assemblies.Any() ? assemblies : new[] { Assembly.GetEntryAssembly() }; RegisterProjections(services, assembliesToScan!); return services; } private static void RegisterProjections(IServiceCollection services, Assembly[] assembliesToScan) { services.Scan(scan => scan .FromAssemblies(assembliesToScan) .AddClasses(classes => classes.AssignableTo<IHaveAggregateStateProjection>()) // Filter classes .AsImplementedInterfaces() .WithTransientLifetime()); } }
36.611765
116
0.721722
[ "MIT" ]
mehdihadeli/EventSourcing.NetCore
Core/Config.cs
3,112
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AvoidBalls { public class BlueBall { public Point Location { get; set; } public Color Color { get; set; } public int Radius { get; set; } public bool IsHit { get; set; } public BlueBall(Point Location) { this.Location = Location; this.Color = Color.Blue; } public BlueBall() { this.Color = Color.Blue; } public void Draw(Graphics g) { Brush brush = new SolidBrush(this.Color); g.FillEllipse(brush, Location.X - Radius / 2, Location.Y - Radius / 2, Radius, Radius); brush.Dispose(); } public bool IsItHit(RedBall redBall) { return ((Location.X - redBall.Location.X) * (Location.X - redBall.Location.X) + (Location.Y - redBall.Location.Y) * (Location.Y - redBall.Location.Y)) < 2*2*Radius*Radius; } public void Move(Point Location) { this.Location = Location; } } }
26.130435
107
0.551581
[ "MIT" ]
Konstantin-Bogdanoski/VP
Exams/AvoidBalls/AvoidBalls/AvoidBalls/BlueBall.cs
1,204
C#
/*---------------------------------------------------------------- Copyright (C) 2019 Senparc 文件名:WeixinController.cs 文件功能描述:用于处理微信回调的信息 创建标识:Senparc - 20150312 ----------------------------------------------------------------*/ /* 重要提示 1. 当前 Controller 中的 2 个 Get() 和 Post() 方法展示了有特殊自定义需求的 MessageHandler 处理方案, 可以高度控制消息处理过程的每一个细节, 如果仅常规项目使用,可以直接使用中间件方式,参考 startup.cs: app.UseMessageHandlerForMp("/WeixinAsync", CustomMessageHandler.GenerateMessageHandler, options => ...); 2. 目前 Senparc.Weixin SDK 已经全面转向异步方法驱动, 因此建议使用异步方法(如:messageHandler.ExecuteAsync()),不再推荐同步方法。 */ //DPBMARK_FILE MP using System; using System.IO; using Microsoft.AspNetCore.Mvc; using Senparc.Weixin.MP.Entities.Request; namespace Senparc.Weixin.Sample.NetCore3.Controllers { using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Senparc.CO2NET.Cache; using Senparc.CO2NET.HttpUtility; using Senparc.CO2NET.Utilities; using Senparc.NeuChar.MessageHandlers; using Senparc.Weixin.Entities; using Senparc.Weixin.HttpUtility; using Senparc.Weixin.MP; using Senparc.Weixin.MP.MvcExtension; using Senparc.Weixin.MP.Sample.CommonService.CustomMessageHandler; using Senparc.Weixin.MP.Sample.CommonService.Utilities; using System.Text; using System.Threading; using System.Threading.Tasks; public partial class WeixinController : Controller { public static readonly string Token = Config.SenparcWeixinSetting.MpSetting.Token;//与微信公众账号后台的Token设置保持一致,区分大小写。 public static readonly string EncodingAESKey = Config.SenparcWeixinSetting.MpSetting.EncodingAESKey;//与微信公众账号后台的EncodingAESKey设置保持一致,区分大小写。 public static readonly string AppId = Config.SenparcWeixinSetting.MpSetting.WeixinAppId;//与微信公众账号后台的AppId设置保持一致,区分大小写。 readonly Func<string> _getRandomFileName = () => SystemTime.Now.ToString("yyyyMMdd-HHmmss") + Guid.NewGuid().ToString("n").Substring(0, 6); SenparcWeixinSetting _senparcWeixinSetting; public WeixinController(IOptions<SenparcWeixinSetting> senparcWeixinSetting) { _senparcWeixinSetting = senparcWeixinSetting.Value; } /// <summary> /// 微信后台验证地址(使用Get),微信后台的“接口配置信息”的Url填写如:http://sdk.weixin.senparc.com/weixin /// </summary> [HttpGet] [ActionName("Index")] public ActionResult Get(PostModel postModel, string echostr) { if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return Content(echostr); //返回随机字符串则表示验证通过 } else { return Content("failed:" + postModel.Signature + "," + MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" + "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); } } /// <summary> /// 【异步方法】用户发送消息后,微信平台自动Post一个请求到这里,并等待响应XML。 /// PS:此方法为简化方法,效果与OldPost一致。 /// v0.8之后的版本可以结合Senparc.Weixin.MP.MvcExtension扩展包,使用WeixinResult,见MiniPost方法。 /// </summary> [HttpPost] [ActionName("Index")] public ActionResult Post(PostModel postModel) { /* 异步请求请见 WeixinAsyncController(推荐) */ if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return Content("参数错误!"); } #region 打包 PostModel 信息 postModel.Token = Token;//根据自己后台的设置保持一致 postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致 postModel.AppId = AppId;//根据自己后台的设置保持一致(必须提供) #endregion //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制(实际最大限制 99999) //注意:如果使用分布式缓存,不建议此值设置过大,如果需要储存历史信息,请使用数据库储存 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount); #region 设置消息去重设置 /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的 RequestMessage */ messageHandler.OmitRepeatedMessage = true;//默认已经是开启状态,此处仅作为演示,也可以设置为 false 在本次请求中停用此功能 #endregion try { messageHandler.SaveRequestMessageLog();//记录 Request 日志(可选) messageHandler.Execute();//执行微信处理过程(关键) messageHandler.SaveResponseMessageLog();//记录 Response 日志(可选) //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return new FixWeixinBugWeixinResult(messageHandler);//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 } catch (Exception ex) { #region 异常处理 WeixinTrace.Log("MessageHandler错误:{0}", ex.Message); using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt"))) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); } return Content(""); #endregion } } /// <summary> /// 最简化的处理流程(不加密) /// </summary> [HttpPost] [ActionName("MiniPost")] public ActionResult MiniPost(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { //return Content("参数错误!");//v0.7- return new WeixinResult("参数错误!");//v0.8+ } postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致 postModel.AppId = AppId;//根据自己后台的设置保持一致 var messageHandler = new CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, 10); messageHandler.Execute();//执行微信处理过程 //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return new FixWeixinBugWeixinResult(messageHandler);//v0.8+ } /* * v0.3.0之前的原始Post方法见:WeixinController_OldPost.cs * * 注意:虽然这里提倡使用CustomerMessageHandler的方法,但是MessageHandler基类最终还是基于OldPost的判断逻辑, * 因此如果需要深入了解Senparc.Weixin.MP内部处理消息的机制,可以查看WeixinController_OldPost.cs中的OldPost方法。 * 目前为止OldPost依然有效,依然可用于生产。 */ /// <summary> /// 为测试并发性能而建 /// </summary> /// <returns></returns> public ActionResult ForTest() { //异步并发测试(提供给单元测试使用) var begin = SystemTime.Now; int t1, t2, t3; System.Threading.ThreadPool.GetAvailableThreads(out t1, out t3); System.Threading.ThreadPool.GetMaxThreads(out t2, out t3); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(0.5)); var end = SystemTime.Now; var thread = System.Threading.Thread.CurrentThread; var result = string.Format("TId:{0}\tApp:{1}\tBegin:{2:mm:ss,ffff}\tEnd:{3:mm:ss,ffff}\tTPool:{4}", thread.ManagedThreadId, HttpContext.GetHashCode(), begin, end, t2 - t1 ); return Content(result); } /// <summary> /// 多账号注册测试 /// </summary> /// <returns></returns> public async Task<ActionResult> MultiAccountTest() { //说明:这里的多账号通过 appsettings.json 直接注入,如果您在自己的服务上进行测试,请使用自己对应的 appId、secret 等信息 //对本接口调用设置限制(如果此站点部署至公网,务必对刷新AccessToken接口做限制! var cache = CacheStrategyFactory.GetObjectCacheStrategyInstance(); var cacheKey = "LastMultiAccountTestTime"; if (!Request.IsLocal() && await cache.CheckExistedAsync(cacheKey)) { var lastMultiAccountTest = await cache.GetAsync<DateTimeOffset>("LastMultiAccountTestTime"); if ((SystemTime.Now - lastMultiAccountTest).TotalSeconds < 30) { return Content("访问频次过快,请稍后再试!"); } } //储存当前访问时间,用于限制刷新频次 await cache.SetAsync(cacheKey, SystemTime.Now); //演示通过 key 来获取 SenparcWeixinSetting 储存信息,如果有明确的WeixinAppId,这一步也可以省略 var setting1 = Weixin.Config.SenparcWeixinSetting.Items["Default"]; var setting2 = Weixin.Config.SenparcWeixinSetting.Items["第二个公众号"]; var sb = new StringBuilder(); //获取一轮AccessToken var token1_1 = await MP.Containers.AccessTokenContainer.GetAccessTokenResultAsync(setting1.WeixinAppId, true); var token2_1 = await MP.Containers.AccessTokenContainer.GetAccessTokenResultAsync(setting2.WeixinAppId, true); sb.Append($"AccessToken 1-1:{token1_1.access_token.Substring(1, 20)}...<br>"); sb.Append($"AccessToken 2-1:{token2_1.access_token.Substring(1, 20)}...<br><br>"); //重新获取一轮 var token1_2 = await MP.Containers.AccessTokenContainer.GetAccessTokenResultAsync(setting1.WeixinAppId, true); var token2_2 = await MP.Containers.AccessTokenContainer.GetAccessTokenResultAsync(setting2.WeixinAppId, true); sb.Append($"AccessToken 1-1:{token1_2.access_token.Substring(1, 20)}...<br>"); sb.Append($"AccessToken 2-1:{token2_2.access_token.Substring(1, 20)}...<br><br>"); //使用高级接口返回消息 var result1 = await MP.AdvancedAPIs.UrlApi.ShortUrlAsync(setting1.WeixinAppId, "long2short", "https://sdk.weixin.senparc.com"); var result2 = await MP.AdvancedAPIs.UrlApi.ShortUrlAsync(setting2.WeixinAppId, "long2short", "https://weixin.senparc.com"); sb.Append($"Result 1:{result1.short_url}<br>"); sb.Append($"Result 2:{result2.short_url}<br><br>"); return Content(sb.ToString(), "text/html", Encoding.UTF8); } } }
40.229091
154
0.603543
[ "Apache-2.0" ]
CoolJie2001/WeiXinMPSDK
Samples/netcore3.0-mvc/Senparc.Weixin.Sample.NetCore3/Controllers/WeixinController.cs
13,187
C#
using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using Vanara.InteropServices; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Vanara.PInvoke { public static partial class Ole32 { /// <summary>Specifies options for the RoGetAgileReference function.</summary> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/ne-combaseapi-agilereferenceoptions typedef enum // AgileReferenceOptions { AGILEREFERENCE_DEFAULT, AGILEREFERENCE_DELAYEDMARSHAL } ; [PInvokeData("combaseapi.h", MSDNShortId = "F46FD597-F278-4DA8-BC94-26836684AD7E")] public enum AgileReferenceOptions { /// <summary> /// Use the default marshaling behavior, which is to marshal interfaces when an agile reference to the interface is obtained. /// </summary> AGILEREFERENCE_DEFAULT, /// <summary> /// Marshaling happens on demand. Use this option only in situations where it's known that an object is only resolved from the /// same apartment in which it was registered. /// </summary> AGILEREFERENCE_DELAYEDMARSHAL } /// <summary> /// <para>Specifies the behavior of the CoWaitForMultipleHandles function.</para> /// </summary> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/ne-combaseapi-tagcowait_flags typedef enum tagCOWAIT_FLAGS { // COWAIT_DEFAULT, COWAIT_WAITALL, COWAIT_ALERTABLE, COWAIT_INPUTAVAILABLE, COWAIT_DISPATCH_CALLS, COWAIT_DISPATCH_WINDOW_MESSAGES } COWAIT_FLAGS; [PInvokeData("combaseapi.h", MSDNShortId = "e6f8300c-f74b-4383-8ee5-519a0ed0b358")] [Flags] public enum COWAIT_FLAGS { /// <summary>Dispatch calls needed for marshaling without dispatching arbitrary calls.</summary> COWAIT_DEFAULT = 0, /// <summary> /// If set, the call to CoWaitForMultipleHandles will return S_OK only when all handles associated with the synchronization /// object have been signaled and an input event has been received, all at the same time. In this case, the behavior of /// CoWaitForMultipleHandles corresponds to the behavior of the MsgWaitForMultipleObjectsEx function with the dwFlags parameter /// set to MWMO_WAITALL. If COWAIT_WAITALL is not set, the call to CoWaitForMultipleHandles will return S_OK as soon as any /// handle associated with the synchronization object has been signaled, regardless of whether an input event is received. /// </summary> COWAIT_WAITALL = 1, /// <summary> /// If set, the call to CoWaitForMultipleHandles will return S_OK if an asynchronous procedure call (APC) has been queued to the /// calling thread with a call to the QueueUserAPC function, even if no handle has been signaled. /// </summary> COWAIT_ALERTABLE = 2, /// <summary> /// If set, the call to CoWaitForMultipleHandles will return S_OK if input exists for the queue, even if the input has been seen /// (but not removed) using a call to another function, such as PeekMessage. /// </summary> COWAIT_INPUTAVAILABLE = 4, /// <summary> /// Dispatch calls from CoWaitForMultipleHandles in an ASTA. Default is no call dispatch. This value has no meaning in other /// apartment types and is ignored. /// </summary> COWAIT_DISPATCH_CALLS = 8, /// <summary> /// Enables dispatch of window messages from CoWaitForMultipleHandles in an ASTA or STA. Default in ASTA is no window messages /// dispatched, default in STA is only a small set of special-cased messages dispatched. The value has no meaning in MTA and is ignored. /// </summary> COWAIT_DISPATCH_WINDOW_MESSAGES = 0x10, } /// <summary>Provides flags for the CoWaitForMultipleObjects function.</summary> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/ne-combaseapi-cwmo_flags typedef enum CWMO_FLAGS { CWMO_DEFAULT, // CWMO_DISPATCH_CALLS, CWMO_DISPATCH_WINDOW_MESSAGES } ; [PInvokeData("combaseapi.h", MSDNShortId = "5FE605A9-DE92-4CD9-9390-6C9F5189A7CB")] [Flags] public enum CWMO_FLAGS { /// <summary>No call dispatch.</summary> CWMO_DEFAULT = 0, /// <summary>Dispatch calls from CoWaitForMultipleObjects (default is no call dispatch).</summary> CWMO_DISPATCH_CALLS = 1, /// <summary/> CWMO_DISPATCH_WINDOW_MESSAGES = 2, } /// <summary> /// <para>Controls the type of connections to a class object.</para> /// </summary> /// <remarks> /// <para> /// In CoRegisterClassObject, members of both the <c>REGCLS</c> and the CLSCTX enumerations, taken together, determine how the class /// object is registered. /// </para> /// <para> /// An EXE surrogate (in which DLL servers are run) calls CoRegisterClassObject to register a class factory using a new <c>REGCLS</c> /// value, REGCLS_SURROGATE. /// </para> /// <para> /// All class factories for DLL surrogates should be registered with REGCLS_SURROGATE set. Do not set REGCLS_SINGLUSE or /// REGCLS_MULTIPLEUSE when you register a surrogate for DLL servers. /// </para> /// <para> /// The following table summarizes the allowable <c>REGCLS</c> value combinations and the object registrations affected by the combinations. /// </para> /// <list type="table"> /// <listheader> /// <term/> /// <term>REGCLS_SINGLEUSE</term> /// <term>REGCLS_MULTIPLEUSE</term> /// <term>REGCLS_MULTI_SEPARATE</term> /// <term>Other</term> /// </listheader> /// <item> /// <term>CLSCTX_INPROC_SERVER</term> /// <term>Error</term> /// <term>In-process</term> /// <term>In-process</term> /// <term>Error</term> /// </item> /// <item> /// <term>CLSCTX_LOCAL_SERVER</term> /// <term>Local</term> /// <term>In-process/local</term> /// <term>Local</term> /// <term>Error</term> /// </item> /// <item> /// <term>Both of the above</term> /// <term>Error</term> /// <term>In-process/local</term> /// <term>In-process/local</term> /// <term>Error</term> /// </item> /// <item> /// <term>Other</term> /// <term>Error</term> /// <term>Error</term> /// <term>Error</term> /// <term>Error</term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/ne-combaseapi-tagregcls typedef enum tagREGCLS { REGCLS_SINGLEUSE, // REGCLS_MULTIPLEUSE, REGCLS_MULTI_SEPARATE, REGCLS_SUSPENDED, REGCLS_SURROGATE, REGCLS_AGILE } REGCLS; [PInvokeData("combaseapi.h", MSDNShortId = "16bca8e0-9999-4d51-b7f0-87deb7619d89")] [Flags] public enum REGCLS { /// <summary> /// After an application is connected to a class object with CoGetClassObject, the class object is removed from public view so /// that no other applications can connect to it. This value is commonly used for single document interface (SDI) applications. /// Specifying this value does not affect the responsibility of the object application to call CoRevokeClassObject; it must /// always call CoRevokeClassObject when it is finished with an object class. /// </summary> REGCLS_SINGLEUSE = 0, /// <summary> /// Multiple applications can connect to the class object through calls to CoGetClassObject. If both the REGCLS_MULTIPLEUSE and /// CLSCTX_LOCAL_SERVER are set in a call to CoRegisterClassObject, the class object is also automatically registered as an /// in-process server, whether CLSCTX_INPROC_SERVER is explicitly set. /// </summary> REGCLS_MULTIPLEUSE = 1, /// <summary> /// Useful for registering separate CLSCTX_LOCAL_SERVER and CLSCTX_INPROC_SERVER class factories through calls to /// CoGetClassObject. If REGCLS_MULTI_SEPARATE is set, each execution context must be set separately; CoRegisterClassObject does /// not automatically register an out-of-process server (for which CLSCTX_LOCAL_SERVER is set) as an in-process server. This /// allows the EXE to create multiple instances of the object for in-process needs, such as self embeddings, without disturbing /// its CLSCTX_LOCAL_SERVER registration. If an EXE registers a REGCLS_MULTI_SEPARATE class factory and a CLSCTX_INPROC_SERVER /// class factory, instance creation calls that specify CLSCTX_INPROC_SERVER in the CLSCTX parameter executed by the EXE would be /// satisfied locally without approaching the SCM. This mechanism is useful when the EXE uses functions such as OleCreate and /// OleLoad to create embeddings, but at the same does not wish to launch a new instance of itself for the self-embedding case. /// The distinction is important for embeddings because the default handler aggregates the proxy manager by default and the /// application should override this default behavior by calling OleCreateEmbeddingHelper for the self-embedding case. If your /// application need not distinguish between the local and inproc case, you need not register your class factory using /// REGCLS_MULTI_SEPARATE. In fact, the application incurs an extra network round trip to the SCM when it registers its /// MULTIPLEUSE class factory as MULTI_SEPARATE and does not register another class factory as INPROC_SERVER. /// </summary> REGCLS_MULTI_SEPARATE = 2, /// <summary> /// Suspends registration and activation requests for the specified CLSID until there is a call to CoResumeClassObjects. This is /// used typically to register the CLSIDs for servers that can register multiple class objects to reduce the overall registration /// time, and thus the server application startup time, by making a single call to the SCM, no matter how many CLSIDs are /// registered for the server. /// </summary> REGCLS_SUSPENDED = 4, /// <summary> /// The class object is a surrogate process used to run DLL servers. The class factory registered by the surrogate process is not /// the actual class factory implemented by the DLL server, but a generic class factory implemented by the surrogate. This /// generic class factory delegates instance creation and marshaling to the class factory of the DLL server running in the /// surrogate. For further information on DLL surrogates, see the DllSurrogate registry value. /// </summary> REGCLS_SURROGATE = 8, /// <summary> /// The class object aggregates the free-threaded marshaler and will be made visible to all inproc apartments. Can be used /// together with other flags. For example, REGCLS_AGILE | REGCLS_MULTIPLEUSE to register a class object that can be used /// multiple times from different apartments. Without other flags, behavior will retain REGCLS_SINGLEUSE semantics in that only /// one instance can be generated. /// </summary> REGCLS_AGILE = 0x10, } /// <summary>Flags used by CoGetStdMarshalEx.</summary> [PInvokeData("combaseapi.h", MSDNShortId = "405c5ff3-8702-48b3-9be9-df4a9461696e")] public enum STDMSHLFLAGS { /// <summary>Indicates a client-side (handler) aggregated standard marshaler.</summary> SMEXF_HANDLER = 0x0, /// <summary>Indicates a server-side aggregated standard marshaler.</summary> SMEXF_SERVER = 0x01, } /// <summary>Looks up a CLSID in the registry, given a ProgID.</summary> /// <param name="lpszProgID">A pointer to the ProgID whose CLSID is requested.</param> /// <param name="lpclsid">Receives a pointer to the retrieved CLSID on return.</param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The CLSID was retrieved successfully.</term> /// </item> /// <item> /// <term>CO_E_CLASSSTRING</term> /// <term>The registered CLSID for the ProgID is invalid.</term> /// </item> /// <item> /// <term>REGDB_E_WRITEREGDB</term> /// <term>An error occurred writing the CLSID to the registry. See Remarks below.</term> /// </item> /// </list> /// </returns> /// <remarks> /// Given a ProgID, <c>CLSIDFromProgID</c> looks up its associated CLSID in the registry. If the ProgID cannot be found in the /// registry, <c>CLSIDFromProgID</c> creates an OLE 1 CLSID for the ProgID and a CLSID entry in the registry. Because of the /// restrictions placed on OLE 1 CLSID values, <c>CLSIDFromProgID</c> and CLSIDFromString are the only two functions that can be used /// to generate a CLSID for an OLE 1 object. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-clsidfromprogid HRESULT CLSIDFromProgID( LPCOLESTR // lpszProgID, LPCLSID lpclsid ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "89fb20af-65bf-4ed4-9f71-eb707ee8eb09")] public static extern HRESULT CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid lpclsid); /// <summary> /// <para>Triggers automatic installation if the COMClassStore policy is enabled.</para> /// <para> /// This is analogous to the behavior of CoCreateInstance when neither CLSCTX_ENABLE_CODE_DOWNLOAD nor CLSCTX_NO_CODE_DOWNLOAD are specified. /// </para> /// </summary> /// <param name="lpszProgID">A pointer to the ProgID whose CLSID is requested.</param> /// <param name="lpclsid">Receives a pointer to the retrieved CLSID on return.</param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The CLSID was retrieved successfully.</term> /// </item> /// <item> /// <term>CO_E_CLASSSTRING</term> /// <term>The registered CLSID for the ProgID is invalid.</term> /// </item> /// <item> /// <term>REGDB_E_WRITEREGDB</term> /// <term>An error occurred writing the CLSID to the registry. See Remarks below.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// CLSCTX_ENABLE_CODE_DOWNLOAD enables automatic installation of missing classes through IntelliMirror/Application Management from /// the Active Directory. If this flag is not specified, the COMClassStore Policy ("Download missing COM components") determines the /// behavior (default: no download). /// </para> /// <para> /// If the COMClassStore Policy enables automatic installation, CLSCTX_NO_CODE_DOWNLOAD can be used to explicitly disallow download /// for an activation. /// </para> /// <para>If either of the following registry values are enabled (meaning set to 1), automatic download of missing classes is enabled:</para> /// <list type="bullet"> /// <item> /// <term><c>HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\App Management</c>\ <c>COMClassStore</c></term> /// </item> /// <item> /// <term><c>HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\App Management</c>\ <c>COMClassStore</c></term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-clsidfromprogidex HRESULT CLSIDFromProgIDEx( // LPCOLESTR lpszProgID, LPCLSID lpclsid ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "2f937ac1-b214-482a-af4b-8cc8c0c585c3")] public static extern HRESULT CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid lpclsid); /// <summary>Increments a global per-process reference count.</summary> /// <returns>The current reference count.</returns> /// <remarks> /// <para> /// Servers can call <c>CoAddRefServerProcess</c> to increment a global per-process reference count. This function is particularly /// helpful to servers that are implemented with multiple threads, either multi-apartmented or free-threaded. Servers of these types /// must coordinate the decision to shut down with activation requests across multiple threads. Calling <c>CoAddRefServerProcess</c> /// increments a global per-process reference count, and calling CoReleaseServerProcess decrements that count. /// </para> /// <para> /// When that count reaches zero, OLE automatically calls CoSuspendClassObjects, which prevents new activation requests from coming /// in. This permits the server to deregister its class objects from its various threads without worry that another activation /// request may come in. New activation requests result in launching a new instance of the local server process. /// </para> /// <para> /// The simplest way for a local server application to make use of these functions is to call <c>CoAddRefServerProcess</c> in the /// constructor for each of its instance objects, and in each of its IClassFactory::LockServer methods when the fLock parameter is /// <c>TRUE</c>. The server application should also call CoReleaseServerProcess in the destruction of each of its instance objects, /// and in each of its <c>LockServer</c> methods when the fLock parameter is <c>FALSE</c>. Finally, the server application should pay /// attention to the return code from <c>CoReleaseServerProcess</c> and if it returns 0, the server application should initiate its /// cleanup, which, for a server with multiple threads, typically means that it should signal its various threads to exit their /// message loops and call CoRevokeClassObject and CoUninitialize. /// </para> /// <para> /// If these functions are used at all, they must be called in both the object instances and the LockServer method, otherwise the /// server application may be shut down prematurely. In-process servers typically should not call <c>CoAddRefServerProcess</c> or CoReleaseServerProcess. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coaddrefserverprocess ULONG CoAddRefServerProcess( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "79887f9d-cad1-492a-b406-d1753ffaf82b")] public static extern uint CoAddRefServerProcess(); /// <summary>Adds an unmarshaler CLSID to the allowed list for the calling process only.</summary> /// <param name="clsid">The CLSID of the unmarshaler to be added to the per-process allowed list.</param> /// <returns>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</returns> /// <remarks> /// <para> /// Don't call the <c>CoAllowUnmarshalerCLSID</c> function until after CoInitializeSecurity has been called in the current process. /// </para> /// <para> /// The <c>CoAllowUnmarshalerCLSID</c> function provides more granular control over unmarshaling policy than is provided by the /// policy options. If the process applies any unmarshaling policy, the effect of the <c>CoAllowUnmarshalerCLSID</c> function is to /// make the policy comparatively weaker. For this reason, only call <c>CoAllowUnmarshalerCLSID</c> when the security impact is well /// understood. Usually, this is used to facilitate applying a stronger unmarshaling policy option for the broad attack surface /// reduction this provides, when a specific unmarshaler CLSID not allowed by that option is needed due to other constraints. /// </para> /// <para> /// For example, it's appropriate to call the <c>CoAllowUnmarshalerCLSID</c> function when an unmarshaler is known or believed to /// have a vulnerability but is required by an app. Also, it's appropriate to call <c>CoAllowUnmarshalerCLSID</c> if the unmarshaler /// is used in multiple processes, but only as part of an uncommon feature. Don't use the <c>CoAllowUnmarshalerCLSID</c> function as /// a replacement for hardening the unmarshaler. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coallowunmarshalerclsid HRESULT // CoAllowUnmarshalerCLSID( REFCLSID clsid ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "4655C6B6-02CE-42B2-A157-0C0325D1BE52")] public static extern HRESULT CoAllowUnmarshalerCLSID(in Guid clsid); /// <summary>Requests cancellation of an outbound DCOM method call pending on a specified thread.</summary> /// <param name="dwThreadId"> /// The identifier of the thread on which the pending DCOM call is to be canceled. If this parameter is 0, the call is on the current thread. /// </param> /// <param name="ulTimeout"> /// The number of seconds <c>CoCancelCall</c> waits for the server to complete the outbound call after the client requests cancellation. /// </param> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The cancellation request was made.</term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>There is no cancel object corresponding to the specified thread.</term> /// </item> /// <item> /// <term>CO_E_CANCEL_DISABLED</term> /// <term>Call cancellation is not enabled on the specified thread.</term> /// </item> /// <item> /// <term>RPC_E_CALL_COMPLETE</term> /// <term>The call was completed during the timeout interval.</term> /// </item> /// <item> /// <term>RPC_E_CALL_CANCELED</term> /// <term>The call was already canceled.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// <c>CoCancelCall</c> calls CoGetCancelObject and then ICancelMethodCalls::Cancel on the cancel object for the call being executed. /// </para> /// <para>This function does not locate cancel objects for asynchronous calls.</para> /// <para> /// The object server can determine if the call has been canceled by periodically calling CoTestCancel. If the call has been /// canceled, the object server should clean up and return control to the client. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cocancelcall HRESULT CoCancelCall( DWORD dwThreadId, // ULONG ulTimeout ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "1707261c-2d8d-4f35-865d-61c8870c0624")] public static extern HRESULT CoCancelCall(uint dwThreadId, uint ulTimeout); /// <summary>Makes a private copy of the specified proxy.</summary> /// <param name="pProxy">A pointer to the IUnknown interface on the proxy to be copied. This parameter cannot be <c>NULL</c>.</param> /// <param name="ppCopy"> /// Address of the pointer variable that receives the interface pointer to the copy of the proxy. This parameter cannot be <c>NULL</c>. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Indicates success.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>One or more arguments are invalid.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// <c>CoCopyProxy</c> makes a private copy of the specified proxy. Typically, this function is called when a client needs to change /// the authentication information of its proxy through a call to either CoSetProxyBlanket or IClientSecurity::SetBlanket without /// changing this information for other clients. <c>CoSetProxyBlanket</c> affects all the users of an instance of a proxy, so /// creating a private copy of the proxy through a call to <c>CoCopyProxy</c> and then calling <c>CoSetProxyBlanket</c> (or /// <c>IClientSecurity::SetBlanket</c>) using the copy eliminates the problem. /// </para> /// <para>This helper function encapsulates the following sequence of common calls (error handling excluded):</para> /// <para>Local interfaces may not be copied. IUnknown and IClientSecurity are examples of existing local interfaces.</para> /// <para> /// Copies of the same proxy have a special relationship with respect to QueryInterface. Given a proxy, a, of the IA interface of a /// remote object, suppose a copy of a is created, called b. In this case, calling <c>QueryInterface</c> from the b proxy for IID_IA /// will not retrieve the IA interface on b, but the one on a, the original proxy with the "default" security settings for the IA interface. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cocopyproxy HRESULT CoCopyProxy( IUnknown *pProxy, // IUnknown **ppCopy ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "26de7bac-8745-40c0-be0a-dcec88a3ecaf")] public static extern HRESULT CoCopyProxy([MarshalAs(UnmanagedType.IUnknown)] object pProxy, [MarshalAs(UnmanagedType.IUnknown)] out object ppCopy); /// <summary>Creates an aggregatable object capable of context-dependent marshaling.</summary> /// <param name="punkOuter">A pointer to the aggregating object's controlling IUnknown.</param> /// <param name="ppunkMarshal">Address of the pointer variable that receives the interface pointer to the aggregatable marshaler.</param> /// <returns> /// <para>This function can return the standard return value E_OUTOFMEMORY, as well as the following value.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The marshaler was created.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// The <c>CoCreateFreeThreadedMarshaler</c> function enables an object to efficiently marshal interface pointers between threads in /// the same process. If your objects do not support interthread marshaling, you have no need to call this function. It is intended /// for use by free-threaded DLL servers that must be accessed directly by all threads in a process, even those threads associated /// with single-threaded apartments. It custom-marshals the real memory pointer over into other apartments as a bogus "proxy" and /// thereby gives direct access to all callers, even if they are not free-threaded. /// </para> /// <para>The <c>CoCreateFreeThreadedMarshaler</c> function performs the following tasks:</para> /// <list type="number"> /// <item> /// <term>Creates a free-threaded marshaler object.</term> /// </item> /// <item> /// <term> /// Aggregates this marshaler to the object specified by the punkOuter parameter. This object is normally the one whose interface /// pointers are to be marshaled. /// </term> /// </item> /// </list> /// <para> /// The aggregating object's implementation of IMarshal should delegate QueryInterface calls for IID_IMarshal to the IUnknown of the /// free-threaded marshaler. Upon receiving a call, the free-threaded marshaler performs the following tasks: /// </para> /// <list type="number"> /// <item> /// <term>Checks the destination context specified by the CoMarshalInterface function's dwDestContext parameter.</term> /// </item> /// <item> /// <term>If the destination context is MSHCTX_INPROC, copies the interface pointer into the marshaling stream.</term> /// </item> /// <item> /// <term> /// If the destination context is any other value, finds or creates an instance of COM's default (standard) marshaler and delegates /// marshaling to it. /// </term> /// </item> /// </list> /// <para> /// Values for dwDestContext come from the MSHCTX enumeration. MSHCTX_INPROC indicates that the interface pointer is to be marshaled /// between different threads in the same process. Because both threads have access to the same address space, the client thread can /// dereference the pointer directly rather than having to direct calls to a proxy. In all other cases, a proxy is required, so /// <c>CoCreateFreeThreadedMarshaler</c> delegates the marshaling job to COM's default implementation. /// </para> /// <para> /// Great care should be exercised in using the <c>CoCreateFreeThreadedMarshaler</c> function. This is because the performance of /// objects which aggregate the free-threaded marshaler is obtained through a calculated violation of the rules of COM, with the /// ever-present risk of undefined behavior unless the object operates within certain restrictions. The most important restrictions are: /// </para> /// <list type="bullet"> /// <item> /// <term> /// A free-threaded marshaler object cannot hold direct pointers to interfaces on an object that does not aggregate the free-threaded /// marshaler as part of its state. If the object were to use direct references to ordinary single-threaded aggregate objects, it may /// break their single threaded property. If the object were to use direct references to ordinary multithreaded aggregate objects, /// these objects can behave in ways that show no sensitivity to the needs of direct single-threaded aggregate clients. For example, /// these objects can spin new threads and pass parameters to the threads that are references to ordinary single-threaded aggregate objects. /// </term> /// </item> /// <item> /// <term> /// A free-threaded marshaler object cannot hold references to proxies to objects in other apartments. Proxies are sensitive to the /// threading model and can return RPC_E_WRONG_THREAD if called by the wrong client. /// </term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cocreatefreethreadedmarshaler HRESULT // CoCreateFreeThreadedMarshaler( LPUNKNOWN punkOuter, LPUNKNOWN *ppunkMarshal ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "f97a2a39-7291-4a1d-b770-0a34f7f5b60f")] public static extern HRESULT CoCreateFreeThreadedMarshaler([MarshalAs(UnmanagedType.IUnknown)] object punkOuter, [MarshalAs(UnmanagedType.IUnknown)] out object ppunkMarshal); /// <summary> /// <para>Creates a single uninitialized object of the class associated with a specified CLSID.</para> /// <para> /// Call <c>CoCreateInstance</c> when you want to create only one object on the local system. To create a single object on a remote /// system, call the CoCreateInstanceEx function. To create multiple objects based on a single CLSID, call the CoGetClassObject function. /// </para> /// </summary> /// <param name="rclsid">The CLSID associated with the data and code that will be used to create the object.</param> /// <param name="pUnkOuter"> /// If <c>NULL</c>, indicates that the object is not being created as part of an aggregate. If non- <c>NULL</c>, pointer to the /// aggregate object's IUnknown interface (the controlling <c>IUnknown</c>). /// </param> /// <param name="dwClsContext"> /// Context in which the code that manages the newly created object will run. The values are taken from the enumeration CLSCTX. /// </param> /// <param name="riid">A reference to the identifier of the interface to be used to communicate with the object.</param> /// <param name="ppv"> /// Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, *ppv contains the /// requested interface pointer. Upon failure, *ppv contains <c>NULL</c>. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>An instance of the specified object class was successfully created.</term> /// </item> /// <item> /// <term>REGDB_E_CLASSNOTREG</term> /// <term> /// A specified class is not registered in the registration database. Also can indicate that the type of server you requested in the /// CLSCTX enumeration is not registered or the values for the server types in the registry are corrupt. /// </term> /// </item> /// <item> /// <term>CLASS_E_NOAGGREGATION</term> /// <term>This class cannot be created as part of an aggregate.</term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term> /// The specified class does not implement the requested interface, or the controlling IUnknown does not expose the requested interface. /// </term> /// </item> /// <item> /// <term>E_POINTER</term> /// <term>The ppv parameter is NULL.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// The <c>CoCreateInstance</c> function provides a convenient shortcut by connecting to the class object associated with the /// specified CLSID, creating an uninitialized instance, and releasing the class object. As such, it encapsulates the following functionality: /// </para> /// <para> /// It is convenient to use <c>CoCreateInstance</c> when you need to create only a single instance of an object on the local machine. /// If you are creating an instance on remote computer, call CoCreateInstanceEx. When you are creating multiple instances, it is more /// efficient to obtain a pointer to the class object's IClassFactory interface and use its methods as needed. In the latter case, /// you should use the CoGetClassObject function. /// </para> /// <para> /// In the CLSCTX enumeration, you can specify the type of server used to manage the object. The constants can be /// CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER or any combination of these values. The /// constant CLSCTX_ALL is defined as the combination of all four. For more information about the use of one or a combination of /// these constants, see CLSCTX. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cocreateinstance HRESULT CoCreateInstance( REFCLSID // rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "7295a55b-12c7-4ed0-a7a4-9ecee16afdec")] public static extern HRESULT CoCreateInstance(in Guid rclsid, [MarshalAs(UnmanagedType.IUnknown), Optional] object pUnkOuter, CLSCTX dwClsContext, in Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 3)] out object ppv); /// <summary> /// <para>Creates an instance of a specific class on a specific computer.</para> /// </summary> /// <param name="Clsid"> /// <para>The CLSID of the object to be created.</para> /// </param> /// <param name="punkOuter"> /// <para> /// If this parameter non- <c>NULL</c>, indicates the instance is being created as part of an aggregate, and punkOuter is to be used /// as the new instance's controlling IUnknown. Aggregation is currently not supported cross-process or cross-computer. When /// instantiating an object out of process, CLASS_E_NOAGGREGATION will be returned if punkOuter is non- <c>NULL</c>. /// </para> /// </param> /// <param name="dwClsCtx"> /// <para>A value from the CLSCTX enumeration.</para> /// </param> /// <param name="pServerInfo"> /// <para> /// Information about the computer on which to instantiate the object. See COSERVERINFO. This parameter can be <c>NULL</c>, in which /// case the object is instantiated on the local computer or at the computer specified in the registry under the class's /// RemoteServerName value, according to the interpretation of the dwClsCtx parameter. /// </para> /// </param> /// <param name="dwCount"> /// <para>The number of structures in pResults. This value must be greater than 0.</para> /// </param> /// <param name="pResults"> /// <para> /// An array of MULTI_QI structures. Each structure has three members: the identifier for a requested interface ( <c>pIID</c>), the /// location to return the interface pointer ( <c>pItf</c>) and the return value of the call to QueryInterface ( <c>hr</c>). /// </para> /// </param> /// <returns> /// <para>This function can return the standard return value E_INVALIDARG, as well as the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Indicates success.</term> /// </item> /// <item> /// <term>REGDB_E_CLASSNOTREG</term> /// <term> /// A specified class is not registered in the registration database. Also can indicate that the type of server you requested in the /// CLSCTX enumeration is not registered or the values for the server types in the registry are corrupt. /// </term> /// </item> /// <item> /// <term>CLASS_E_NOAGGREGATION</term> /// <term>This class cannot be created as part of an aggregate.</term> /// </item> /// <item> /// <term>CO_S_NOTALLINTERFACES</term> /// <term> /// At least one, but not all of the interfaces requested in the pResults array were successfully retrieved. The hr member of each of /// the MULTI_QI structures in pResults indicates with S_OK or E_NOINTERFACE whether the specific interface was returned. /// </term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>None of the interfaces requested in the pResults array were successfully retrieved.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// <c>CoCreateInstanceEx</c> creates a single uninitialized object associated with the given CLSID on a specified remote computer. /// This is an extension of the function CoCreateInstance, which creates an object on the local computer only. In addition, rather /// than requesting a single interface and obtaining a single pointer to that interface, <c>CoCreateInstanceEx</c> makes it possible /// to specify an array of structures, each pointing to an interface identifier (IID) on input, and, on return, containing (if /// available) a pointer to the requested interface and the return value of the QueryInterface call for that interface. This permits /// fewer round trips between computers. /// </para> /// <para> /// This function encapsulates three calls: first, to CoGetClassObject to connect to the class object associated with the specified /// CLSID, specifying the location of the class; second, to IClassFactory::CreateInstance to create an uninitialized instance, and /// finally, to IClassFactory::Release, to release the class object. /// </para> /// <para> /// The object so created must still be initialized through a call to one of the initialization interfaces (such as /// IPersistStorage::Load). Two functions, CoGetInstanceFromFile and CoGetInstanceFromIStorage encapsulate both the instance creation /// and initialization from the obvious sources. /// </para> /// <para> /// The COSERVERINFO structure passed as the pServerInfo parameter contains the security settings that COM will use when creating a /// new instance of the specified object. Note that this parameter does not influence the security settings used when making method /// calls on the instantiated object. Those security settings are configurable, on a per-interface basis, with the CoSetProxyBlanket /// function. Also see, IClientSecurity::SetBlanket. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cocreateinstanceex HRESULT CoCreateInstanceEx( // REFCLSID Clsid, IUnknown *punkOuter, DWORD dwClsCtx, COSERVERINFO *pServerInfo, DWORD dwCount, MULTI_QI *pResults ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "3b414b95-e8d2-42e8-b4f2-5cc5189a3d08")] public static extern HRESULT CoCreateInstanceEx(in Guid Clsid, [MarshalAs(UnmanagedType.IUnknown), Optional] object punkOuter, CLSCTX dwClsCtx, [Optional] COSERVERINFO pServerInfo, uint dwCount, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] MULTI_QI[] pResults); /// <summary>Creates an instance of a specific class on a specific computer from within an app container.</summary> /// <param name="Clsid">The CLSID of the object to be created.</param> /// <param name="punkOuter"> /// If this parameter non- <c>NULL</c>, indicates the instance is being created as part of an aggregate, and punkOuter is to be used /// as the new instance's controlling IUnknown. Aggregation is currently not supported cross-process or cross-computer. When /// instantiating an object out of process, CLASS_E_NOAGGREGATION will be returned if punkOuter is non- <c>NULL</c>. /// </param> /// <param name="dwClsCtx">A value from the CLSCTX enumeration.</param> /// <param name="reserved">Reserved for future use.</param> /// <param name="dwCount">The number of structures in pResults. This value must be greater than 0.</param> /// <param name="pResults"> /// An array of MULTI_QI structures. Each structure has three members: the identifier for a requested interface ( <c>pIID</c>), the /// location to return the interface pointer ( <c>pItf</c>) and the return value of the call to QueryInterface ( <c>hr</c>). /// </param> /// <returns> /// <para>This function can return the standard return value E_INVALIDARG, as well as the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Indicates success.</term> /// </item> /// <item> /// <term>REGDB_E_CLASSNOTREG</term> /// <term> /// A specified class is not registered in the registration database, or the class is not supported in the app container. Also can /// indicate that the type of server you requested in the CLSCTX enumeration is not registered or the values for the server types in /// the registry are corrupt. /// </term> /// </item> /// <item> /// <term>CLASS_E_NOAGGREGATION</term> /// <term>This class cannot be created as part of an aggregate.</term> /// </item> /// <item> /// <term>CO_S_NOTALLINTERFACES</term> /// <term> /// At least one, but not all of the interfaces requested in the pResults array were successfully retrieved. The hr member of each of /// the MULTI_QI structures in pResults indicates with S_OK or E_NOINTERFACE whether the specific interface was returned. /// </term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>None of the interfaces requested in the pResults array were successfully retrieved.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>The <c>CoCreateInstanceFromApp</c> function is the same as the CoCreateInstanceEx function, with the following differences.</para> /// <list type="bullet"> /// <item> /// <term> /// The <c>CoCreateInstanceFromApp</c> function reads class registrations only from application contexts, and from the /// HKLM\SOFTWARE\Classes\CLSID registry hive. /// </term> /// </item> /// <item> /// <term> /// Only built-in classes that are supported in the app container are supplied. Attempts to activate unsupported classes, including /// all classes installed by 3rd-party code as well as many Windows classes, result in error code <c>REGDB_E_CLASSNOTREG</c>. /// </term> /// </item> /// <item> /// <term> /// The <c>CoCreateInstanceFromApp</c> function is available to Windows Store apps. Desktop applications can call this function, but /// they have the same restrictions as Windows Store apps. /// </term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cocreateinstancefromapp HRESULT // CoCreateInstanceFromApp( REFCLSID Clsid, IUnknown *punkOuter, DWORD dwClsCtx, PVOID reserved, DWORD dwCount, MULTI_QI *pResults ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "1C773D78-5B33-44FE-A09B-AB8087F678A1")] public static extern HRESULT CoCreateInstanceFromApp(in Guid Clsid, [MarshalAs(UnmanagedType.IUnknown)] object punkOuter, uint dwClsCtx, IntPtr reserved, uint dwCount, ref MULTI_QI pResults); /// <summary> /// Locates the implementation of a Component Object Model (COM) interface in a server process given an interface to a proxied object. /// </summary> /// <param name="dwClientPid">The process ID of the process that contains the proxy.</param> /// <param name="ui64ProxyAddress"> /// The address of an interface on a proxy to the object. ui64ProxyAddress is considered a 64-bit value type, rather than a pointer /// to a 64-bit value, and isn't a pointer to an object in the debugger process. Instead, this address is passed to the /// ReadProcessMemory function. /// </param> /// <param name="pServerInformation">A structure that contains the process ID, the thread ID, and the address of the server.</param> /// <returns> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The server information was successfully retrieved.</term> /// </item> /// <item> /// <term>E_ACCESSDENIED</term> /// <term>The caller is an app container, or the developer license is not installed.</term> /// </item> /// <item> /// <term>RPC_E_INVALID_IPID</term> /// <term>ui64ProxyAddress does not point to a proxy.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// The <c>CoDecodeProxy</c> function is a COM API that enables native debuggers to locate the implementation of a COM interface in a /// server process given an interface on a proxy to the object. /// </para> /// <para> /// Also, the <c>CoDecodeProxy</c> function enables the debugger to monitor cross-apartment function calls and fail such calls when appropriate. /// </para> /// <para> /// You can call the <c>CoDecodeProxy</c> function from a 32-bit or 64-bit process. ui64ProxyAddress can be a 32-bit or 64-bit /// address. The <c>CoDecodeProxy</c> function returns a 32-bit or 64-bit address in the pServerInformation field. If it returns a /// 64-bit address, you should pass the address to the ReadProcessMemory function only from a 64-bit process. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-codecodeproxy HRESULT CoDecodeProxy( DWORD // dwClientPid, UINT64 ui64ProxyAddress, PServerInformation pServerInformation ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "C61C68B1-78CA-4052-9E24-629AB4083B86")] public static extern HRESULT CoDecodeProxy(uint dwClientPid, ulong ui64ProxyAddress, IntPtr pServerInformation); /// <summary>Releases the increment made by a previous call to the CoIncrementMTAUsage function.</summary> /// <param name="Cookie">A <c>PVOID</c> variable that was set by a previous call to the CoIncrementMTAUsage function.</param> /// <returns>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</returns> /// <remarks> /// <para> /// Cookie must be a valid value returned by a successful previous call to the CoIncrementMTAUsage function. If the overall count of /// MTA usage reaches 0, including both through this API and through the CoInitializeEx and CoUninitialize functions, the system /// frees resources related to MTA support. /// </para> /// <para> /// You can call CoIncrementMTAUsage from one thread and <c>CoDecrementMTAUsage</c> from another as long as a cookie previously /// returned by <c>CoIncrementMTAUsage</c> is passed to <c>CoDecrementMTAUsage</c>. /// </para> /// <para> /// Don't call <c>CoDecrementMTAUsage</c> during process shutdown or inside dllmain. You can call <c>CoDecrementMTAUsage</c> before /// the call to start the shutdown process. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-codecrementmtausage HRESULT CoDecrementMTAUsage( // CO_MTA_USAGE_COOKIE Cookie ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "66AA2783-7F24-41BB-911B-D452DF54C003")] public static extern HRESULT CoDecrementMTAUsage(CO_MTA_USAGE_COOKIE Cookie); /// <summary> /// Undoes the action of a call to CoEnableCallCancellation. Disables cancellation of synchronous calls on the calling thread when /// all calls to <c>CoEnableCallCancellation</c> are balanced by calls to <c>CoDisableCallCancellation</c>. /// </summary> /// <param name="pReserved">This parameter is reserved and must be <c>NULL</c>.</param> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_INVALIDARG, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the /// following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Call cancellation was successfully disabled on the thread.</term> /// </item> /// <item> /// <term>CO_E_CANCEL_DISABLED</term> /// <term> /// There have been more successful calls to CoEnableCallCancellation on the thread than there have been calls to /// CoDisableCallCancellation. Cancellation is still enabled on the thread. /// </term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// When call cancellation is enabled on a thread, marshaled synchronous calls from that thread to objects on the same computer can /// suffer serious performance degradation. By default, then, synchronous calls cannot be canceled, even if a cancel object is /// available. To enable call cancellation, you must call CoEnableCallCancellation first. /// </para> /// <para> /// When call cancellation is disabled, attempts to gain a pointer to a call object will fail. If the calling thread already has a /// pointer to a call object, calls on that object will fail. /// </para> /// <para> /// Unless you want to enable call cancellation on a thread at all times, you should pair calls to CoEnableCallCancellation with /// calls to <c>CoDisableCallCancellation</c>. Call cancellation is disabled only if each successful call to /// <c>CoEnableCallCancellation</c> is balanced by a successful call to <c>CoDisableCallCancellation</c>. /// </para> /// <para> /// A call will be cancelable or not depending on the state of the thread at the time the call was made. Subsequently enabling or /// disabling call cancellation has no effect on any calls that are pending on the thread. /// </para> /// <para> /// If a thread is uninitialized and then reinitialized by calls to CoUninitialize and CoInitialize, call cancellation is disabled on /// the thread, even if it was enabled when the thread was uninitialized. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-codisablecallcancellation HRESULT // CoDisableCallCancellation( LPVOID pReserved ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "33d99eab-a0bf-4e4d-93a4-5c03c41cebbb")] public static extern HRESULT CoDisableCallCancellation([Optional] IntPtr pReserved); /// <summary> /// <para> /// Disconnects all proxy connections that are being maintained on behalf of all interface pointers that point to objects in the /// current context. /// </para> /// <para> /// This function blocks connections until all objects are successfully disconnected or the time-out expires. Only the context that /// actually manages the objects should call <c>CoDisconnectContext</c>. /// </para> /// </summary> /// <param name="dwTimeout"> /// The time in milliseconds after which <c>CoDisconnectContext</c> returns even if the proxy connections for all objects have not /// been disconnected. INFINITE is an acceptable value for this parameter. /// </param> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_INVALIDARG, and E_OUTOFMEMORY, as well as the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The proxy connections for all objects were successfully disconnected.</term> /// </item> /// <item> /// <term>RPC_E_TIMEOUT</term> /// <term>Not all proxy connections were successfully deleted in the time specified in dwTimeout.</term> /// </item> /// <item> /// <term>CO_E_NOTSUPPORTED</term> /// <term>The current context cannot be disconnected.</term> /// </item> /// <item> /// <term>CONTEXT_E_WOULD_DEADLOCK</term> /// <term> /// An object tried to call CoDisconnectContext on the context it is residing in. This would cause the function to time-out and /// deadlock if dwTimeout were set to INFINITE. /// </term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// The <c>CoDisconnectContext</c> function is used to support unloading services in shared service hosts where you must unload your /// service's binaries without affecting other COM servers that are running in the same process. If you control the process lifetime /// and you do not unload until the process exits, the COM infrastructure will perform the necessary cleanup automatically and you do /// not have to call this function. /// </para> /// <para> /// The <c>CoDisconnectContext</c> function enables a server to correctly disconnect all external clients of all objects in the /// current context. Default contexts cannot be disconnected. To use <c>CoDisconnectContext</c>, you must first create a context that /// can be disconnected and register your class factories for objects from which you want to disconnect within that context. You can /// do this with the IContextCallback interface. /// </para> /// <para> /// If <c>CoDisconnectContext</c> returns RPC_E_TIMEOUT, this does not indicate that the function did not disconnect the objects, but /// that not all disconnections could be completed in the time specified by dwTimeout because of outstanding calls on the objects. /// All objects will be disconnected after all calls on them have been completed. /// </para> /// <para> /// It is not safe to unload the DLL that hosts the service until <c>CoDisconnectContext</c> returns S_OK. If the function returns /// RPC_E_TIMEOUT, the service may perform other clean-up. The service must call the function until it returns S_OK, and then it can /// safely unload its DLL. /// </para> /// <para>The <c>CoDisconnectContext</c> function performs the following tasks:</para> /// <list type="bullet"> /// <item> /// <term>Calls CoDisconnectObject on all objects in the current context.</term> /// </item> /// <item> /// <term>Blocks until all objects have been disconnected or the time-out has expired.</term> /// </item> /// </list> /// <para>The <c>CoDisconnectContext</c> function has the following limitations:</para> /// <list type="bullet"> /// <item> /// <term>Asynchronous COM calls are not supported.</term> /// </item> /// <item> /// <term>In-process objects must be registered and enabled using the CLSCTX_LOCAL_SERVER flag, or they will not be disconnected.</term> /// </item> /// <item> /// <term>COM+ is not supported.</term> /// </item> /// <item> /// <term> /// COM interface pointers are context-sensitive. Therefore, any interface pointer created in the context to be disconnected can only /// be used within that context. /// </term> /// </item> /// </list> /// <para>Examples</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-codisconnectcontext HRESULT CoDisconnectContext( // DWORD dwTimeout ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "faacb583-285a-4ec6-9700-22320e87de6e")] public static extern HRESULT CoDisconnectContext(uint dwTimeout); /// <summary> /// <para> /// Disconnects all remote process connections being maintained on behalf of all the interface pointers that point to a specified object. /// </para> /// <para>Only the process that actually manages the object should call <c>CoDisconnectObject</c>.</para> /// </summary> /// <param name="pUnk">A pointer to any interface derived from IUnknown on the object to be disconnected.</param> /// <param name="dwReserved">This parameter is reserved and must be 0.</param> /// <returns>This function returns S_OK to indicate that all connections to remote processes were successfully deleted.</returns> /// <remarks> /// <para> /// The <c>CoDisconnectObject</c> function enables a server to correctly disconnect all external clients to the object specified by pUnk. /// </para> /// <para>It performs the following tasks:</para> /// <list type="number"> /// <item> /// <term> /// Checks to see whether the object to be disconnected implements the IMarshal interface. If so, it gets the pointer to that /// interface; if not, it gets a pointer to the standard marshaler's (i.e., COM's) <c>IMarshal</c> implementation. /// </term> /// </item> /// <item> /// <term> /// Using whichever IMarshal interface pointer it has acquired, the function then calls IMarshal::DisconnectObject to disconnect all /// out-of-process clients. /// </term> /// </item> /// </list> /// <para> /// An object's client does not call <c>CoDisconnectObject</c> to disconnect itself from the server (clients should use /// IUnknown::Release for this purpose). Rather, an OLE server calls <c>CoDisconnectObject</c> to forcibly disconnect an object's /// clients, usually in response to a user closing the server application. /// </para> /// <para> /// Similarly, an OLE container that supports external links to its embedded objects can call <c>CoDisconnectObject</c> to destroy /// those links. Again, this call is normally made in response to a user closing the application. The container should first call /// IOleObject::Close for all its OLE objects, each of which should send IAdviseSink::OnClose notifications to their various clients. /// Then the container can call <c>CoDisconnectObject</c> to close any existing connections. /// </para> /// <para> /// <c>CoDisconnectObject</c> does not necessarily disconnect out-of-process clients immediately. If any marshaled calls are pending /// on the server object, <c>CoDisconnectObject</c> disconnects the object only when those calls have returned. In the meantime, /// <c>CoDisconnectObject</c> sets a flag that causes any new marshaled calls to return CO_E_OBJNOTCONNECTED. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-codisconnectobject HRESULT CoDisconnectObject( // LPUNKNOWN pUnk, DWORD dwReserved ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "4293316a-bafe-4fca-ad6a-68d8e99c8fba")] public static extern HRESULT CoDisconnectObject([MarshalAs(UnmanagedType.IUnknown)] object pUnk, uint dwReserved = 0); /// <summary>Enables cancellation of synchronous calls on the calling thread.</summary> /// <param name="pReserved">This parameter is reserved and must be <c>NULL</c>.</param> /// <returns>This function can return the standard return values S_OK, E_FAIL, E_INVALIDARG, and E_OUTOFMEMORY.</returns> /// <remarks> /// <para> /// When call cancellation is enabled on a thread, marshaled synchronous calls from that thread to objects on the same computer can /// suffer serious performance degradation. By default, synchronous calls cannot be canceled, even if a cancel object is available. /// To enable call cancellation, you must call <c>CoEnableCallCancellation</c> first. /// </para> /// <para> /// Unless you want to enable call cancellation on a thread at all times, you should pair calls to <c>CoEnableCallCancellation</c> /// with calls to CoDisableCallCancellation. Call cancellation is disabled only if <c>CoDisableCallCancellation</c> has been called /// once for each time <c>CoEnableCallCancellation</c> was called successfully. /// </para> /// <para> /// A call will be cancelable or not depending on the state of the thread at the time the call was made. Subsequently enabling or /// disabling call cancellation has no effect on any calls that are pending on the thread. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coenablecallcancellation HRESULT // CoEnableCallCancellation( LPVOID pReserved ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "59b66f33-486e-49c3-9fb8-0eab93146ed9")] public static extern HRESULT CoEnableCallCancellation(IntPtr pReserved = default); /// <summary> /// <para>Returns the current time as a FILETIME structure.</para> /// <para><c>Note</c> This function is provided for compatibility with 16-bit Windows.</para> /// </summary> /// <param name="lpFileTime">A pointer to the FILETIME structure that receives the current time.</param> /// <returns>This function returns S_OK to indicate success.</returns> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cofiletimenow HRESULT CoFileTimeNow( FILETIME // *lpFileTime ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "00083429-1d61-4a0b-bb73-82158869466d")] public static extern HRESULT CoFileTimeNow(out FILETIME lpFileTime); /// <summary> /// <para>Unloads any DLLs that are no longer in use, probably because the DLL no longer has any instantiated COM objects outstanding.</para> /// <para><c>Note</c> This function is provided for compatibility with 16-bit Windows.</para> /// </summary> /// <remarks> /// Applications can call <c>CoFreeUnusedLibraries</c> periodically to free resources. It is most efficient to call it either at the /// top of a message loop or in some idle-time task. <c>CoFreeUnusedLibraries</c> internally calls DllCanUnloadNow for DLLs that /// implement and export that function. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cofreeunusedlibraries void CoFreeUnusedLibraries( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "188e9a3b-39cc-454e-af65-4ac797e275d4")] public static extern void CoFreeUnusedLibraries(); /// <summary>Unloads any DLLs that are no longer in use and whose unload delay has expired.</summary> /// <param name="dwUnloadDelay"> /// The delay in milliseconds between the time that the DLL has stated it can be unloaded until it becomes a candidate to unload. /// Setting this parameter to INFINITE uses the system default delay (10 minutes). Setting this parameter to 0 forces the unloading /// of any DLLs without any delay. /// </param> /// <param name="dwReserved">This parameter is reserved and must be 0.</param> /// <remarks> /// <para> /// COM supplies functions to reclaim memory held by DLLs containing components. The most commonly used function is /// CoFreeUnusedLibraries. <c>CoFreeUnusedLibraries</c> does not immediately release DLLs that have no active object. There is a /// 10-minute delay for multithreaded apartments (MTAs) and neutral apartments (NAs). For single-threaded apartments (STAs), there is /// no delay. /// </para> /// <para> /// The 10-minute delay for CoFreeUnusedLibraries is to avoid multithread race conditions caused by unloading a component DLL. This /// default delay may be too long for many applications. /// </para> /// <para> /// COM maintains a list of active DLLs that have had components loaded for the apartments that can be hosted on the thread where /// this function is called. When <c>CoFreeUnusedLibrariesEx</c> is called, each DLL on that list has its DllCanUnloadNow function /// called. If <c>DllCanUnloadNow</c> returns S_FALSE (or is not exported), this DLL is not ready to be unloaded. If /// <c>DllCanUnloadNow</c> returns S_OK, this DLL is moved off the active list to a "candidate-for-unloading" list. /// </para> /// <para> /// Adding the DLL to the candidate-for-unloading list time-stamps the DLL dwUnloadDelay milliseconds from when this move occurs. /// When <c>CoFreeUnusedLibrariesEx</c> (or CoFreeUnusedLibraries) is called again, at least dwUnloadDelay milliseconds from the call /// that moved the DLL to the candidate-for-unloading list, the DLL is actually freed from memory. If COM uses the component DLL /// while the DLL is on the candidate-for-unloading list, it is moved back to the active list. /// </para> /// <para> /// Setting dwUnloadDelay to 0 may have unexpected consequences. The component DLL may need some time for cleanup after it returns /// from the DllCanUnloadNow function. For example, if the DLL had its own worker threads, using a value of 0 would most likely lead /// to a problem because the code executing on these threads would be unmapped, caused by the unloading of the DLL before the worker /// threads have a chance to exit. Also, using too brief of a value for dwUnloadDelay can lead to performance issues because there is /// more overhead in reloading a DLL than letting it page out. /// </para> /// <para> /// This behavior is triggered by the DLL supplying components with threading models set to Free, Neutral, or Both. For a threading /// model set to Apartment (or if no threading model is specified), dwUnloadDelay is treated as 0 because these components are tied /// to the single thread hosting the apartment. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cofreeunusedlibrariesex void // CoFreeUnusedLibrariesEx( DWORD dwUnloadDelay, DWORD dwReserved ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "01660e9d-d8f2-40ef-a6d6-b80f0140ab5f")] public static extern void CoFreeUnusedLibrariesEx(uint dwUnloadDelay, uint dwReserved = 0); /// <summary>Returns the current apartment type and type qualifier.</summary> /// <param name="pAptType">APTTYPE enumeration value that specifies the type of the current apartment.</param> /// <param name="pAptQualifier">APTTYPEQUALIFIER enumeration value that specifies the type qualifier of the current apartment.</param> /// <returns> /// <para>Returns S_OK if the call succeeded. Otherwise, one of the following error codes is returned.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>E_FAIL</term> /// <term>The call could not successfully query the current apartment type and type qualifier.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term> /// An invalid parameter value was supplied to the function. Specifically, one or both of the parameters were set to NULL by the caller. /// </term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>CoInitialize or CoInitializeEx was not called on this thread prior to calling CoGetApartmentType.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>On Windows platforms prior to Windows 7, the following actions must be taken on a thread to query the apartment type:</para> /// <list type="bullet"> /// <item> /// <term>Call CoGetContextToken to obtain the current context token.</term> /// </item> /// <item> /// <term>Cast the context token to an IUnknown* pointer.</term> /// </item> /// <item> /// <term>Call the QueryInterface method on that pointer to obtain the IComThreadingInfo interface.</term> /// </item> /// <item> /// <term>Call the GetCurrentApartmentType method of the IComThreadingInfo interface to obtain the current apartment type.</term> /// </item> /// </list> /// <para> /// In multithreaded scenarios, there is a race condition which can potentially cause an Access Violation within the process when /// executing the above sequence of operations. The <c>CoGetApartmentType</c> function is recommended as it does not potentially /// incur the Access Violation. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetapartmenttype HRESULT CoGetApartmentType( // APTTYPE *pAptType, APTTYPEQUALIFIER *pAptQualifier ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "ab0b6008-397f-4210-ba26-1a041b709722")] public static extern HRESULT CoGetApartmentType(out APTTYPE pAptType, out APTTYPEQUALIFIER pAptQualifier); /// <summary>Retrieves the context of the current call on the current thread.</summary> /// <param name="riid"> /// Interface identifier (IID) of the call context that is being requested. If you are using the default call context supported by /// standard marshaling, IID_IServerSecurity is available. For COM+ applications using role-based security, IID_ISecurityCallContext /// is available. /// </param> /// <param name="ppInterface"> /// Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, *ppInterface contains /// the requested interface pointer. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The context was retrieved successfully.</term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>The call context does not support the interface specified by riid.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <c>CoGetCallContext</c> retrieves the context of the current call on the current thread. The riid parameter specifies the /// interface on the context to be retrieved. This is one of the functions provided to give the server access to any contextual /// information of the caller. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetcallcontext HRESULT CoGetCallContext( REFIID // riid, void **ppInterface ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "b82e32c0-840d-402e-90d5-ff678c51faf1")] public static extern HRESULT CoGetCallContext(in Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 0)] out object ppInterface); /// <summary>Returns a pointer to a <c>DWORD</c> that contains the apartment ID of the caller's thread.</summary> /// <param name="lpdwTID"> /// Receives the apartment ID of the caller's thread. For a single threaded apartment (STA), this is the current thread ID. For a /// multithreaded apartment (MTA), the value is 0. For a neutral apartment (NA), the value is -1. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_TRUE</term> /// <term>The caller's thread ID is set and the caller is in the same process.</term> /// </item> /// <item> /// <term>S_FALSE</term> /// <term>The caller's thread ID is set and the caller is in a different process.</term> /// </item> /// <item> /// <term>E_OUTOFMEMORY</term> /// <term>The caller's thread ID was not set.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// If the caller is not running on the same computer, this function does not return the apartment ID and the return value is S_FALSE. /// </para> /// <para> /// There is no guarantee that the information returned from this API is not tampered with, so do not use the ID that is returned to /// make security decisions. The ID can only be used for logging and diagnostic purposes. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetcallertid HRESULT CoGetCallerTID( LPDWORD // lpdwTID ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "3a34001b-6286-4103-ae9f-700ea101dc17")] public static extern HRESULT CoGetCallerTID(out uint lpdwTID); /// <summary> /// Obtains a pointer to a call control interface, normally ICancelMethodCalls, on the cancel object corresponding to an outbound COM /// method call pending on the same or another client thread. /// </summary> /// <param name="dwThreadId"> /// The identifier of the thread on which the pending COM call is to be canceled. If this parameter is 0, the call is on the current thread. /// </param> /// <param name="iid"> /// The globally unique identifier of an interface on the cancel object for the call to be canceled. This argument is usually IID_ICancelMethodCalls. /// </param> /// <param name="ppUnk">Receives the address of a pointer to the interface specified by riid.</param> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_INVALIDARG, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the /// following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The call control object was retrieved successfully.</term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>The object on which the call is executing does not support the interface specified by riid.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// If two or more calls are pending on the same thread through nested calls, the thread ID may not be sufficient to identify the /// call to be canceled. In this case, <c>CoGetCancelObject</c> returns a cancel interface corresponding to the innermost call that /// is pending on the thread and has registered a cancel object. /// </para> /// <para>This function does not locate cancel objects for asynchronous calls.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetcancelobject HRESULT CoGetCancelObject( DWORD // dwThreadId, REFIID iid, void **ppUnk ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "d38161af-d662-4430-99b7-6563efda6f4e")] public static extern HRESULT CoGetCancelObject(uint dwThreadId, in Guid iid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 1)] out object ppUnk); /// <summary> /// <para> /// Provides a pointer to an interface on a class object associated with a specified CLSID. <c>CoGetClassObject</c> locates, and if /// necessary, dynamically loads the executable code required to do this. /// </para> /// <para> /// Call <c>CoGetClassObject</c> directly to create multiple objects through a class object for which there is a CLSID in the system /// registry. You can also retrieve a class object from a specific remote computer. Most class objects implement the IClassFactory /// interface. You would then call CreateInstance to create an uninitialized object. It is not always necessary to go through this /// process however. To create a single object, call the CoCreateInstanceEx function, which allows you to create an instance on a /// remote machine. This replaces the CoCreateInstance function, which can still be used to create an instance on a local computer. /// Both functions encapsulate connecting to the class object, creating the instance, and releasing the class object. Two other /// functions, CoGetInstanceFromFile and CoGetInstanceFromIStorage, provide both instance creation on a remote system and object /// activation. There are numerous functions and interface methods whose purpose is to create objects of a single type and provide a /// pointer to an interface on that object. /// </para> /// </summary> /// <param name="rclsid">The CLSID associated with the data and code that you will use to create the objects.</param> /// <param name="dwClsContext"> /// The context in which the executable code is to be run. To enable a remote activation, include CLSCTX_REMOTE_SERVER. For more /// information on the context values and their use, see the CLSCTX enumeration. /// </param> /// <param name="pvReserved"> /// A pointer to computer on which to instantiate the class object. If this parameter is <c>NULL</c>, the class object is /// instantiated on the current computer or at the computer specified under the class's RemoteServerName key, according to the /// interpretation of the dwClsCtx parameter. See COSERVERINFO. /// </param> /// <param name="riid"> /// Reference to the identifier of the interface, which will be supplied in ppv on successful return. This interface will be used to /// communicate with the class object. Typically this value is IID_IClassFactory, although other values – such as /// IID_IClassFactory2 which supports a form of licensing – are allowed. All OLE-defined interface IIDs are defined in the OLE /// header files as IID_interfacename, where interfacename is the name of the interface. /// </param> /// <param name="ppv"> /// The address of pointer variable that receives the interface pointer requested in riid. Upon successful return, *ppv contains the /// requested interface pointer. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Location and connection to the specified class object was successful.</term> /// </item> /// <item> /// <term>REGDB_E_CLASSNOTREG</term> /// <term> /// The CLSID is not properly registered. This error can also indicate that the value you specified in dwClsContext is not in the registry. /// </term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term> /// Either the object pointed to by ppv does not support the interface identified by riid, or the QueryInterface operation on the /// class object returned E_NOINTERFACE. /// </term> /// </item> /// <item> /// <term>REGDB_E_READREGDB</term> /// <term>There was an error reading the registration database.</term> /// </item> /// <item> /// <term>CO_E_DLLNOTFOUND</term> /// <term>Either the in-process DLL or handler DLL was not found (depending on the context).</term> /// </item> /// <item> /// <term>CO_E_APPNOTFOUND</term> /// <term>The executable (.exe) was not found (CLSCTX_LOCAL_SERVER only).</term> /// </item> /// <item> /// <term>E_ACCESSDENIED</term> /// <term>There was a general access failure on load.</term> /// </item> /// <item> /// <term>CO_E_ERRORINDLL</term> /// <term>There is an error in the executable image.</term> /// </item> /// <item> /// <term>CO_E_APPDIDNTREG</term> /// <term>The executable was launched, but it did not register the class object (and it may have shut down).</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// A class object in OLE is an intermediate object that supports an interface that permits operations common to a group of objects. /// The objects in this group are instances derived from the same object definition represented by a single CLSID. Usually, the /// interface implemented on a class object is IClassFactory, through which you can create object instances of a given definition (class). /// </para> /// <para> /// A call to <c>CoGetClassObject</c> creates, initializes, and gives the caller access (through a pointer to an interface specified /// with the riid parameter) to the class object. The class object is the one associated with the CLSID that you specify in the /// rclsid parameter. The details of how the system locates the associated code and data within a computer are transparent to the /// caller, as is the dynamic loading of any code that is not already loaded. /// </para> /// <para> /// If the class context is CLSCTX_REMOTE_SERVER, indicating remote activation is required, the COSERVERINFO structure provided in /// the pServerInfo parameter allows you to specify the computer on which the server is located. For information on the algorithm /// used to locate a remote server when pServerInfo is <c>NULL</c>, refer to the CLSCTX enumeration. /// </para> /// <para>There are two places to find a CLSID for a class:</para> /// <list type="bullet"> /// <item> /// <term> /// The registry holds an association between CLSIDs and file suffixes, and between CLSIDs and file signatures for determining the /// class of an object. /// </term> /// </item> /// <item> /// <term>When an object is saved to persistent storage, its CLSID is stored with its data.</term> /// </item> /// </list> /// <para> /// To create and initialize embedded or linked OLE document objects, it is not necessary to call <c>CoGetClassObject</c> directly. /// Instead, call the OleCreate or <c>OleCreate</c> XXX function. These functions encapsulate the entire object instantiation and /// initialization process, and call, among other functions, <c>CoGetClassObject</c>. /// </para> /// <para> /// The riid parameter specifies the interface the client will use to communicate with the class object. In most cases, this /// interface is IClassFactory. This provides access to the CreateInstance method, through which the caller can then create an /// uninitialized object of the kind specified in its implementation. All classes registered in the system with a CLSID must /// implement IClassFactory. /// </para> /// <para> /// In rare cases, however, you may want to specify some other interface that defines operations common to a set of objects. For /// example, in the way OLE implements monikers, the interface on the class object is IParseDisplayName, used to transform the /// display name of an object into a moniker. /// </para> /// <para> /// The dwClsContext parameter specifies the execution context, allowing one CLSID to be associated with different pieces of code in /// different execution contexts. The CLSCTX enumeration specifies the available context flags. <c>CoGetClassObject</c> consults (as /// appropriate for the context indicated) both the registry and the class objects that are currently registered by calling the /// CoRegisterClassObject function. /// </para> /// <para> /// To release a class object, use the class object's Release method. The function CoRevokeClassObject is to be used only to remove a /// class object's CLSID from the system registry. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetclassobject HRESULT CoGetClassObject( REFCLSID // rclsid, DWORD dwClsContext, LPVOID pvReserved, REFIID riid, LPVOID *ppv ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "65e758ce-50a4-49e8-b3b2-0cd148d2781a")] public static extern HRESULT CoGetClassObject(in Guid rclsid, CLSCTX dwClsContext, IntPtr pvReserved, in Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 3)] out object ppv); /// <summary>Returns a pointer to an implementation of IObjContext for the current context.</summary> /// <param name="pToken">A pointer to an implementation of IObjContext for the current context.</param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The token was retrieved successfully.</term> /// </item> /// <item> /// <term>E_POINTER</term> /// <term>The caller did not pass a valid token pointer variable.</term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>The caller is not in an initialized apartment.</term> /// </item> /// </list> /// </returns> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetcontexttoken HRESULT CoGetContextToken( // ULONG_PTR *pToken ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "1218d928-ca3f-4bdc-9a00-ea4c214175a9")] public static extern HRESULT CoGetContextToken([MarshalAs(UnmanagedType.IUnknown)] out IObjContext pToken); /// <summary>Returns the logical thread identifier of the current physical thread.</summary> /// <param name="pguid">A pointer to a GUID that contains the logical thread ID on return.</param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The logical thread ID was retrieved successfully.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>An invalid pointer was passed in for the pguid parameter.</term> /// </item> /// <item> /// <term>E_OUTOFMEMORY</term> /// <term>A memory allocation failed during the operation of the function.</term> /// </item> /// </list> /// </returns> /// <remarks> /// This function retrieves the identifier of the current logical thread under which this physical thread is operating. The current /// physical thread takes on the logical thread identifier of any client thread that makes a COM call into this application. /// Similarly, the logical thread identifier of the current physical thread is used to denote the causality for outgoing COM calls /// from this physical thread. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetcurrentlogicalthreadid HRESULT // CoGetCurrentLogicalThreadId( GUID *pguid ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "eced2f1e-9f2b-476c-bea8-945fb4804a89")] public static extern HRESULT CoGetCurrentLogicalThreadId(out Guid pguid); /// <summary> /// Returns a value that is unique to the current thread. <c>CoGetCurrentProcess</c> can be used to avoid thread ID reuse problems. /// </summary> /// <returns>The function returns the unique identifier of the current thread.</returns> /// <remarks> /// <para> /// Using the value returned from a call to <c>CoGetCurrentProcess</c> can help you in maintaining tables that are keyed by threads /// or in uniquely identifying a thread to other threads or processes. /// </para> /// <para> /// <c>CoGetCurrentProcess</c> returns a value that is effectively unique, because it is not used again until 2³² more threads have /// been created on the current workstation or until the workstation is restarted. /// </para> /// <para> /// The value returned by <c>CoGetCurrentProcess</c> will uniquely identify the same thread for the life of the caller. Because /// thread IDs can be reused without notice as threads are created and destroyed, this value is more reliable than the value returned /// by the GetCurrentThreadId function. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetcurrentprocess DWORD CoGetCurrentProcess( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "46b0448f-f1c5-4da7-8489-bbd6d0fab79e")] public static extern uint CoGetCurrentProcess(); /// <summary>Retrieves a reference to the default context of the specified apartment.</summary> /// <param name="aptType"> /// <para>The apartment type of the default context that is being requested. This parameter can be one of the following values.</para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>APTTYPE_CURRENT -1</term> /// <term>The caller's apartment.</term> /// </item> /// <item> /// <term>APTTYPE_MTA 1</term> /// <term>The multithreaded apartment for the current process.</term> /// </item> /// <item> /// <term>APTTYPE_NA 2</term> /// <term>The neutral apartment for the current process.</term> /// </item> /// <item> /// <term>APTTYPE_MAINSTA 3</term> /// <term>The main single-threaded apartment for the current process.</term> /// </item> /// </list> /// <para> /// The APTTYPE value APTTYPE_STA (0) is not supported. A process can contain multiple single-threaded apartments, each with its own /// context, so <c>CoGetDefaultContext</c> could not determine which STA is of interest. Therefore, this function returns /// E_INVALIDARG if APTTYPE_STA is specified. /// </para> /// </param> /// <param name="riid"> /// The interface identifier (IID) of the interface that is being requested on the default context. Typically, the caller requests /// IID_IObjectContext. The default context does not support all of the normal object context interfaces. /// </param> /// <param name="ppv"> /// A reference to the interface specified by riid on the default context. If the object's component is non-configured, (that is, the /// object's component has not been imported into a COM+ application), or if the <c>CoGetDefaultContext</c> function is called from a /// constructor or an IUnknown method, this parameter is set to a <c>NULL</c> pointer. /// </param> /// <returns> /// <para>This method can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The method completed successfully.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>One of the parameters is invalid.</term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>The caller is not in an initialized apartment.</term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>The object context does not support the interface specified by riid.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// Every COM apartment has a special context called the default context. A default context is different from all the other, /// non-default contexts in an apartment because it does not provide runtime services. It does not support all of the normal object /// context interfaces. /// </para> /// <para> /// The default context is also used by instances of non-configured COM components, (that is, components that have not been part of a /// COM+ application), when they are created from an apartment that does not support their threading model. In other words, if a COM /// object creates an instance of a non-configured component and the new object cannot be added to its creator's context because of /// its threading model, the new object is instead added to the default context of an apartment that supports its threading model. /// </para> /// <para> /// An object should never pass an IObjectContext reference to another object. If you pass an <c>IObjectContext</c> reference to /// another object, it is no longer a valid reference. /// </para> /// <para> /// When an object obtains a reference to an IObjectContext, it must release the <c>IObjectContext</c> object when it is finished /// with it. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetdefaultcontext HRESULT CoGetDefaultContext( // APTTYPE aptType, REFIID riid, void **ppv ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "97a0e7da-e8bb-4bde-a8ba-35c90a1351d2")] public static extern HRESULT CoGetDefaultContext(APTTYPE aptType, in Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 1)] out object ppv); /// <summary> /// Unmarshals a buffer containing an interface pointer and releases the stream when an interface pointer has been marshaled from /// another thread to the calling thread. /// </summary> /// <param name="pStm">A pointer to the IStream interface on the stream to be unmarshaled.</param> /// <param name="iid">A reference to the identifier of the interface requested from the unmarshaled object.</param> /// <param name="ppv"> /// The address of pointer variable that receives the interface pointer requested in <paramref name="iid"/>. Upon successful return, /// <paramref name="ppv"/> contains the requested interface pointer to the unmarshaled interface. /// </param> /// <returns> /// This function can return the standard return values S_OK and E_INVALIDARG, as well as any of the values returned by CoUnmarshalInterface. /// </returns> /// <remarks> /// <para> /// <c>Important</c> Security Note: Calling this method with untrusted data is a security risk. Call this method only with trusted /// data. For more information, see Untrusted Data Security Risks. /// </para> /// <para>The <c>CoGetInterfaceAndReleaseStream</c> function performs the following tasks:</para> /// <list type="bullet"> /// <item> /// <term>Calls CoUnmarshalInterface to unmarshal an interface pointer previously passed in a call to CoMarshalInterThreadInterfaceInStream.</term> /// </item> /// <item> /// <term> /// Releases the stream pointer. Even if the unmarshaling fails, the stream is still released because there is no effective way to /// recover from a failure of this kind. /// </term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetinterfaceandreleasestream HRESULT // CoGetInterfaceAndReleaseStream( LPSTREAM pStm, REFIID iid, LPVOID *ppv ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "b529f65f-3208-4594-a772-d1cad3727dc1")] public static extern HRESULT CoGetInterfaceAndReleaseStream(IStream pStm, in Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); /// <summary> /// Retrieves a pointer to the default OLE task memory allocator (which supports the system implementation of the IMalloc interface) /// so applications can call its methods to manage memory. /// </summary> /// <param name="dwMemContext">This parameter must be 1.</param> /// <param name="ppMalloc"> /// The address of an <c>IMalloc*</c> pointer variable that receives the interface pointer to the memory allocator. /// </param> /// <returns>This function can return the standard return values S_OK, E_INVALIDARG, and E_OUTOFMEMORY.</returns> /// <remarks> /// The pointer to the IMalloc interface pointer received through the ppMalloc parameter cannot be used from a remote process; each /// process must have its own allocator. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetmalloc HRESULT CoGetMalloc( DWORD dwMemContext, // LPMALLOC *ppMalloc ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "d1d09fbe-ca5c-4480-b807-3afcc043ccb9")] public static extern HRESULT CoGetMalloc(uint dwMemContext, out IMalloc ppMalloc); /// <summary> /// Returns an upper bound on the number of bytes needed to marshal the specified interface pointer to the specified object. /// </summary> /// <param name="pulSize"> /// A pointer to the upper-bound value on the size, in bytes, of the data packet to be written to the marshaling stream. If this /// parameter is 0, the size of the packet is unknown. /// </param> /// <param name="riid"> /// A reference to the identifier of the interface whose pointer is to be marshaled. This interface must be derived from the IUnknown interface. /// </param> /// <param name="pUnk">A pointer to the interface to be marshaled. This interface must be derived from the IUnknown interface.</param> /// <param name="dwDestContext"> /// The destination context where the specified interface is to be unmarshaled. Values for dwDestContext come from the enumeration MSHCTX. /// </param> /// <param name="pvDestContext">This parameter is reserved and must be <c>NULL</c>.</param> /// <param name="mshlflags"> /// Indicates whether the data to be marshaled is to be transmitted back to the client processthe normal case or written to a global /// table, where it can be retrieved by multiple clients. Values come from the enumeration MSHLFLAGS. /// </param> /// <returns> /// <para>This function can return the standard return value E_UNEXPECTED, as well as the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The upper bound was returned successfully.</term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>Before this function can be called, either the CoInitialize or OleInitialize function must be called.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>This function performs the following tasks:</para> /// <list type="number"> /// <item> /// <term> /// Queries the object for an IMarshal pointer or, if the object does not implement <c>IMarshal</c>, gets a pointer to COM's standard marshaler. /// </term> /// </item> /// <item> /// <term>Using the pointer obtained in the preceding item, calls IMarshal::GetMarshalSizeMax.</term> /// </item> /// <item> /// <term> /// Adds to the value returned by the call to GetMarshalSizeMax the size of the marshaling data header and, possibly, that of the /// proxy CLSID to obtain the maximum size in bytes of the amount of data to be written to the marshaling stream. /// </term> /// </item> /// </list> /// <para> /// You do not explicitly call this function unless you are implementing IMarshal, in which case your marshaling stub should call /// this function to get the correct size of the data packet to be marshaled. /// </para> /// <para> /// The value returned by this method is guaranteed to be valid only as long as the internal state of the object being marshaled does /// not change. Therefore, the actual marshaling should be done immediately after this function returns, or the stub runs the risk /// that the object, because of some change in state, might require more memory to marshal than it originally indicated. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetmarshalsizemax HRESULT CoGetMarshalSizeMax( // ULONG *pulSize, REFIID riid, LPUNKNOWN pUnk, DWORD dwDestContext, LPVOID pvDestContext, DWORD mshlflags ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "c04c736c-8efe-438b-9d21-8b6ad53d36e7")] public static extern HRESULT CoGetMarshalSizeMax(ref uint pulSize, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] object pUnk, MSHCTX dwDestContext, [Optional] IntPtr pvDestContext, MSHLFLAGS mshlflags); /// <summary>Returns the context for the current object.</summary> /// <param name="riid"> /// <para>A reference to the ID of an interface that is implemented on the context object.</para> /// <para>For objects running within COM applications, IID_IComThreadingInfo, IID_IContext, and IID_IContextCallback are available.</para> /// <para> /// For objects running within COM+ applications, IID_IObjectContext, IID_IObjectContextActivity IID_IObjectContextInfo, and /// IID_IContextState are available. /// </para> /// </param> /// <param name="ppv">The address of a pointer to the interface specified by riid on the context object.</param> /// <returns> /// <para>This function can return the standard return values E_OUTOFMEMORY and E_UNEXPECTED, as well as the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The object context was successfully retrieved.</term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>The requested interface was not available.</term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>Before this function can be called, the CoInitializeEx function must be called on the current thread.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// <c>CoGetObjectContext</c> retrieves the context for the object from which it is called, and returns a pointer to an interface /// that can be used to manipulate context properties. Context properties are used to provide services to configured components /// running within COM+ applications. /// </para> /// <para> /// For components running within COM applications, the following interfaces are supported for accessing context properties: /// IComThreadingInfo, IContext, and IContextCallback. /// </para> /// <para> /// For components running within COM+ applications, the following interfaces are supported for accessing context properties: /// IObjectContext, IObjectContextActivity, IObjectContextInfo, and IContextState. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetobjectcontext HRESULT CoGetObjectContext( // REFIID riid, LPVOID *ppv ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "97a0c6c3-a011-44dc-b428-aabdad7d4364")] public static extern HRESULT CoGetObjectContext(in Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 0)] out object ppv); /// <summary>Returns the CLSID of the DLL that implements the proxy and stub for the specified interface.</summary> /// <param name="riid">The interface whose proxy/stub CLSID is to be returned.</param> /// <param name="pClsid">Specifies where to store the proxy/stub CLSID for the interface specified by riid.</param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The proxy/stub CLSID was successfully returned.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>One of the parameters is invalid.</term> /// </item> /// <item> /// <term>E_OUTOFMEMORY</term> /// <term>There is insufficient memory to complete this operation.</term> /// </item> /// </list> /// </returns> /// <remarks> /// The <c>CoGetPSClsid</c> function looks at the <c>HKEY_CLASSES_ROOT</c>&lt;b&gt;Interfaces&lt;i&gt;{string form of /// riid}&lt;b&gt;ProxyStubClsid32 key in the registry to determine the CLSID of the DLL to load in order to create the proxy and /// stub for the interface specified by riid. This function also returns the CLSID for any interface IID registered by /// CoRegisterPSClsid within the current process. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetpsclsid HRESULT CoGetPSClsid( REFIID riid, // CLSID *pClsid ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "dfe6b514-a80a-4adb-bf43-d9a7d0e5f4a3")] public static extern HRESULT CoGetPSClsid(in Guid riid, out Guid pClsid); /// <summary> /// Creates a default, or standard, marshaling object in either the client process or the server process, depending on the caller, /// and returns a pointer to that object's IMarshal implementation. /// </summary> /// <param name="riid"> /// A reference to the identifier of the interface whose pointer is to be marshaled. This interface must be derived from the IUnknown interface. /// </param> /// <param name="pUnk">A pointer to the interface to be marshaled.</param> /// <param name="dwDestContext"> /// The destination context where the specified interface is to be unmarshaled. Values come from the enumeration MSHCTX. Unmarshaling /// can occur either in another apartment of the current process (MSHCTX_INPROC) or in another process on the same computer as the /// current process (MSHCTX_LOCAL). /// </param> /// <param name="pvDestContext">This parameter is reserved and must be <c>NULL</c>.</param> /// <param name="mshlflags"> /// Indicates whether the data to be marshaled is to be transmitted back to the client process (the normal case) or written to a /// global table where it can be retrieved by multiple clients. Values come from the MSHLFLAGS enumeration. /// </param> /// <param name="ppMarshal"> /// The address of <c>IMarshal*</c> pointer variable that receives the interface pointer to the standard marshaler. /// </param> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The IMarshal instance was returned successfully.</term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>Before this function can be called, the CoInitialize or OleInitialize function must be called on the current thread.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// The <c>CoGetStandardMarshal</c> function creates a default, or standard, marshaling object in either the client process or the /// server process, as may be necessary, and returns that object's IMarshal pointer to the caller. If you implement <c>IMarshal</c>, /// you may want your implementation to call <c>CoGetStandardMarshal</c> as a way of delegating to COM's default implementation any /// destination contexts that you do not fully understand or want to handle. Otherwise, you can ignore this function, which COM calls /// as part of its internal marshaling procedures. /// </para> /// <para> /// When the COM library in the client process receives a marshaled interface pointer, it looks for a CLSID to be used in creating a /// proxy for the purposes of unmarshaling the packet. If the packet does not contain a CLSID for the proxy, COM calls /// <c>CoGetStandardMarshal</c>, passing a <c>NULL</c> pUnk value. This function creates a standard proxy in the client process and /// returns a pointer to that proxy's implementation of IMarshal. COM uses this pointer to call CoUnmarshalInterface to retrieve the /// pointer to the requested interface. /// </para> /// <para> /// If your OLE server application's implementation of IMarshal calls <c>CoGetStandardMarshal</c>, you should pass both the IID of /// (riid), and a pointer to (pUnk), the interface being requested. /// </para> /// <para>This function performs the following tasks:</para> /// <list type="number"> /// <item> /// <term>Determines whether pUnk is <c>NULL</c>.</term> /// </item> /// <item> /// <term> /// If pUnk is <c>NULL</c>, creates a standard interface proxy in the client process for the specified riid and returns the proxy's /// IMarshal pointer. /// </term> /// </item> /// <item> /// <term> /// If pUnk is not <c>NULL</c>, checks to see if a marshaler for the object already exists, creates a new one if necessary, and /// returns the marshaler's IMarshal pointer. /// </term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetstandardmarshal HRESULT CoGetStandardMarshal( // REFIID riid, LPUNKNOWN pUnk, DWORD dwDestContext, LPVOID pvDestContext, DWORD mshlflags, LPMARSHAL *ppMarshal ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "0cb74adc-e192-4ae5-9267-02c79e301681")] public static extern HRESULT CoGetStandardMarshal(in Guid riid, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnk, MSHCTX dwDestContext, [Optional] IntPtr pvDestContext, MSHLFLAGS mshlflags, out IMarshal ppMarshal); /// <summary>Creates an aggregated standard marshaler for use with lightweight client-side handlers.</summary> /// <param name="pUnkOuter">A pointer to the controlling IUnknown.</param> /// <param name="smexflags"> /// <para> /// One of two values indicating whether the aggregated standard marshaler is on the client side or the server side. These flags are /// defined in the <c>STDMSHLFLAGS</c> enumeration. /// </para> /// <list type="table"> /// <listheader> /// <term>Value</term> /// <term>Meaning</term> /// </listheader> /// <item> /// <term>SMEXF_SERVER 0x01</term> /// <term>Indicates a server-side aggregated standard marshaler.</term> /// </item> /// <item> /// <term>SMEXF_HANDLER 0x0</term> /// <term>Indicates a client-side (handler) aggregated standard marshaler.</term> /// </item> /// </list> /// </param> /// <param name="">The .</param> /// <param name="ppUnkInner"> /// On successful return, address of pointer to the IUnknown interface on the newly-created aggregated standard marshaler. If an /// error occurs, this value is <c>NULL</c>. /// </param> /// <returns>This function returns S_OK.</returns> /// <remarks> /// The server calls <c>CoGetStdMarshalEx</c> passing in the flag SMEXF_SERVER. This creates a server side standard marshaler (known /// as a stub manager). The handler calls <c>CoGetStdMarshalEx</c> passing in the flag SMEXF_HANDLER. This creates a client side /// standard marshaler (known as a proxy manager). Note that when calling this function, the handler must pass the original /// controlling unknown that was passed to the handler when the handler was created. This will be the system implemented controlling /// unknown. Failure to pass the correct IUnknown results in an error returned. On success, the ppUnkInner returned is the /// controlling unknown of the inner object. The server and handler must keep this pointer, and may use it to call /// IUnknown::QueryInterface for the IMarshal interface. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogetstdmarshalex HRESULT CoGetStdMarshalEx( // LPUNKNOWN pUnkOuter, DWORD smexflags, LPUNKNOWN *ppUnkInner ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "405c5ff3-8702-48b3-9be9-df4a9461696e")] public static extern HRESULT CoGetStdMarshalEx([In, MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, STDMSHLFLAGS smexflags, [MarshalAs(UnmanagedType.IUnknown)] out object ppUnkInner); /// <summary>Returns the CLSID of an object that can emulate the specified object.</summary> /// <param name="clsidOld">The CLSID of the object that can be emulated (treated as) an object with a different CLSID.</param> /// <param name="pClsidNew"> /// A pointer to where the CLSID that can emulate clsidOld objects is retrieved. This parameter cannot be <c>NULL</c>. If there is no /// emulation information for clsidOld objects, the clsidOld parameter is supplied. /// </param> /// <returns> /// <para>This function can return the following values, as well as any error values returned by the CLSIDFromString function.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>A new CLSID was successfully returned.</term> /// </item> /// <item> /// <term>S_FALSE</term> /// <term>There is no emulation information for the clsidOld parameter, so the pClsidNew parameter is set to clsidOld.</term> /// </item> /// <item> /// <term>REGDB_E_READREGDB</term> /// <term>There was an error reading the registry.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <c>CoGetTreatAsClass</c> returns the TreatAs entry in the registry for the specified object. The <c>TreatAs</c> entry, if set, is /// the CLSID of a registered object (an application) that can emulate the object in question. The <c>TreatAs</c> entry is set /// through a call to the CoTreatAsClass function. Emulation allows an application to open and edit an object of a different format, /// while retaining the original format of the object. Objects of the original CLSID are activated and treated as objects of the /// second CLSID. When the object is saved, this may result in loss of edits not supported by the original format. If there is no /// <c>TreatAs</c> entry for the specified object, this function returns the CLSID of the original object (clsidOld). /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cogettreatasclass HRESULT CoGetTreatAsClass( // REFCLSID clsidOld, LPCLSID pClsidNew ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "f95fefe6-dc37-45f4-93be-87c996990ab9")] public static extern HRESULT CoGetTreatAsClass(in Guid clsidOld, out Guid pClsidNew); /// <summary>Enables the server to impersonate the client of the current call for the duration of the call.</summary> /// <returns>This function supports the standard return values, including S_OK.</returns> /// <remarks> /// <para> /// This method allows the server to impersonate the client of the current call for the duration of the call. If you do not call /// CoRevertToSelf, COM reverts automatically for you. This function will fail unless the object is being called with /// RPC_C_AUTHN_LEVEL_CONNECT or higher authentication in effect (which is any authentication level except RPC_C_AUTHN_LEVEL_NONE). /// This function encapsulates the following sequence of common calls (error handling excluded): /// </para> /// <para> /// <c>CoImpersonateClient</c> encapsulates the process of getting a pointer to an instance of IServerSecurity that contains data /// about the current call, calling its ImpersonateClient method, and then releasing the pointer. One call to CoRevertToSelf (or /// IServerSecurity::RevertToSelf) will undo any number of calls to impersonate the client. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coimpersonateclient HRESULT CoImpersonateClient( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "a3cbfbbc-fc6f-4d1b-8460-1e3351cd32d7")] public static extern HRESULT CoImpersonateClient(); /// <summary>Keeps MTA support active when no MTA threads are running.</summary> /// <param name="pCookie"> /// Address of a <c>PVOID</c> variable that receives the cookie for the CoDecrementMTAUsage function, or <c>NULL</c> if the call fails. /// </param> /// <returns>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</returns> /// <remarks> /// <para> /// The <c>CoIncrementMTAUsage</c> function enables clients to create MTA workers and wait on them for completion before exiting the process. /// </para> /// <para> /// The <c>CoIncrementMTAUsage</c> function ensures that the system doesn't free resources related to MTA support., even if the MTA /// thread count goes to 0. /// </para> /// <para>On success, call the CoDecrementMTAUsage once only. On failure, don't call the <c>CoDecrementMTAUsage</c> function.</para> /// <para> /// Don't call <c>CoIncrementMTAUsage</c> during process shutdown or inside dllmain. You can call <c>CoIncrementMTAUsage</c> before /// the call to start the shutdown process. /// </para> /// <para> /// You can call <c>CoIncrementMTAUsage</c> from one thread and CoDecrementMTAUsage from another as long as a cookie previously /// returned by <c>CoIncrementMTAUsage</c> is passed to <c>CoDecrementMTAUsage</c>. /// </para> /// <para> /// <c>CoIncrementMTAUsage</c> creates the MTA, if the MTA does not already exist. <c>CoIncrementMTAUsage</c> puts the current thread /// into the MTA, if the current thread is not already in an apartment /// </para> /// <para>You can use <c>CoIncrementMTAUsage</c> when:</para> /// <list type="bullet"> /// <item> /// <term>You want a server to keep the MTA alive even when all worker threads are idle.</term> /// </item> /// <item> /// <term> /// Your API implementation requires COM to be initialized, but has no information about whether the current thread is already in an /// apartment, and does not need the current thread to go into a particular apartment. /// </term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coincrementmtausage HRESULT CoIncrementMTAUsage( // CO_MTA_USAGE_COOKIE *pCookie ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "EFE6E66A-96A3-4B51-92DD-1CE84B1F0185")] public static extern HRESULT CoIncrementMTAUsage(out CO_MTA_USAGE_COOKIE pCookie); /// <summary> /// <para>Tells the service control manager to flush any cached RPC binding handles for the specified computer.</para> /// <para>Only administrators may call this function.</para> /// </summary> /// <param name="pszMachineName"> /// The computer name for which binding handles should be flushed, or an empty string to signify that all handles in the cache should /// be flushed. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>Indicates success.</term> /// </item> /// <item> /// <term>CO_S_MACHINENAMENOTFOUND</term> /// <term> /// Indicates that the specified computer name was not found or that the binding handle cache was empty, indicating that an empty /// string was passed instead of a specific computer name. /// </term> /// </item> /// <item> /// <term>E_ACCESSDENIED</term> /// <term>Indicates the caller was not an administrator for this computer.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>Indicates that a NULL value was passed for pszMachineName.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// The OLE Service Control Manager is used by COM to send component activation requests to other machines. To do this, the OLE /// Service Control Manager maintains a cache of RPC binding handles to send activation requests to computer, keyed by computer name. /// Under normal circumstances, this works well, but in some scenarios, such as Web farms and load-balancing situations, the ability /// to purge this cache of specific handles might be needed in order to facilitate rebinding to a different physical server by the /// same name. <c>CoInvalidateRemoteMachineBindings</c> is used for this purpose. /// </para> /// <para> /// The OLE Service Control Manager will flush unused binding handles over time. It is not necessary to call /// <c>CoInvalidateRemoteMachineBindings</c> to do this. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coinvalidateremotemachinebindings HRESULT // CoInvalidateRemoteMachineBindings( LPOLESTR pszMachineName ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "6d0fa512-a9e9-44ff-929d-00b9c826da99")] public static extern HRESULT CoInvalidateRemoteMachineBindings([In, MarshalAs(UnmanagedType.LPWStr)] string pszMachineName); /// <summary>Determines whether a remote object is connected to the corresponding in-process object.</summary> /// <param name="pUnk">A pointer to the controlling IUnknown interface on the remote object.</param> /// <returns> /// If the object is not remote or if it is remote and still connected, the return value is <c>TRUE</c>; otherwise, it is <c>FALSE</c>. /// </returns> /// <remarks> /// The <c>CoIsHandlerConnected</c> function determines the status of a remote object. You can use it to determine when to release a /// remote object. You specify the remote object by giving the function a pointer to its controlling IUnknown interface (the pUnk /// parameter). A value of <c>TRUE</c> returned from the function indicates either that the specified object is not remote, or that /// it is remote and is still connected to its remote handler. A value of <c>FALSE</c> returned from the function indicates that the /// object is remote but is no longer connected to its remote handler; in this case, the caller should respond by releasing the object. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coishandlerconnected BOOL CoIsHandlerConnected( // LPUNKNOWN pUnk ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "f58bdec6-3709-439d-9867-0022a069c53d")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CoIsHandlerConnected([In, MarshalAs(UnmanagedType.IUnknown)] object pUnk); /// <summary>Called either to lock an object to ensure that it stays in memory, or to release such a lock.</summary> /// <param name="pUnk">A pointer to the IUnknown interface on the object to be locked or unlocked.</param> /// <param name="fLock"> /// Indicates whether the object is to be locked or released. If this parameter is <c>TRUE</c>, the object is kept in memory, /// independent of <c>AddRef</c>/ <c>Release</c> operations, registrations, or revocations. If this parameter is <c>FALSE</c>, the /// lock previously set with a call to this function is released. /// </param> /// <param name="fLastUnlockReleases"> /// <para> /// If the lock is the last reference that is supposed to keep an object alive, specify <c>TRUE</c> to release all pointers to the /// object (there may be other references that are not supposed to keep it alive). Otherwise, specify <c>FALSE</c>. /// </para> /// <para>If fLock is <c>TRUE</c>, this parameter is ignored.</para> /// </param> /// <returns>This function can return the standard return values E_INVALIDARG, E_OUTOFMEMORY, E_UNEXPECTED, and S_OK.</returns> /// <remarks> /// <para> /// The <c>CoLockObjectExternal</c> function must be called in the process in which the object actually resides (the EXE process, not /// the process in which handlers may be loaded). /// </para> /// <para> /// The <c>CoLockObjectExternal</c> function prevents the reference count of an object from going to zero, thereby "locking" it into /// existence until the lock is released. The same function (with different parameters) releases the lock. The lock is implemented by /// having the system call IUnknown::AddRef on the object. The system then waits to call IUnknown::Release on the object until a /// later call to <c>CoLockObjectExternal</c> with fLock set to <c>FALSE</c>. This function can be used to maintain a reference count /// on the object on behalf of the end user, because it acts outside of the object, as does the user. /// </para> /// <para> /// The end user has explicit control over the lifetime of an application, even if there are external locks on it. That is, if a user /// decides to close the application, it must shut down. In the presence of external locks (such as the lock set by /// <c>CoLockObjectExternal</c>), the application can call the CoDisconnectObject function to force these connections to close prior /// to shutdown. /// </para> /// <para> /// Calling <c>CoLockObjectExternal</c> sets a strong lock on an object. A strong lock keeps an object in memory, while a weak lock /// does not. Strong locks are required, for example, during a silent update to an OLE embedding. The embedded object's container /// must remain in memory until the update process is complete. There must also be a strong lock on an application object to ensure /// that the application stays alive until it has finished providing services to its clients. All external references place a strong /// reference lock on an object. /// </para> /// <para>The <c>CoLockObjectExternal</c> function is typically called in the following situations:</para> /// <list type="bullet"> /// <item> /// <term> /// Object servers should call <c>CoLockObjectExternal</c> with both fLock and fLastLockReleases set to <c>TRUE</c> when they become /// visible. This call creates a strong lock on behalf of the user. When the application is closing, free the lock with a call to /// <c>CoLockObjectExternal</c>, setting fLock to <c>FALSE</c> and fLastLockReleases to <c>TRUE</c>. /// </term> /// </item> /// <item> /// <term>A call to <c>CoLockObjectExternal</c> on the server can also be used in the implementation of IOleContainer::LockContainer.</term> /// </item> /// </list> /// <para> /// There are several things to be aware of when you use <c>CoLockObjectExternal</c> in the implementation of LockContainer. An /// embedded object would call <c>LockContainer</c> on its container to keep it running (to lock it) in the absence of other reasons /// to keep it running. When the embedded object becomes visible, the container must weaken its connection to the embedded object /// with a call to the OleSetContainedObject function, so other connections can affect the object. /// </para> /// <para> /// Unless an application manages all aspects of its application and document shutdown completely with calls to /// <c>CoLockObjectExternal</c>, the container must keep a private lock count in LockContainer so that it exits when the lock count /// reaches zero and the container is invisible. Maintaining all aspects of shutdown, and thereby avoiding keeping a private lock /// count, means that <c>CoLockObjectExternal</c> should be called whenever one of the following conditions occur: /// </para> /// <list type="bullet"> /// <item> /// <term>A document is created and destroyed or made visible or invisible.</term> /// </item> /// <item> /// <term>An application is started and shut down by the user.</term> /// </item> /// <item> /// <term>A pseudo-object is created and destroyed.</term> /// </item> /// </list> /// <para>For debugging purposes, it may be useful to keep a count of the number of external locks (and unlocks) set on the application.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-colockobjectexternal HRESULT CoLockObjectExternal( // LPUNKNOWN pUnk, BOOL fLock, BOOL fLastUnlockReleases ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "36eb55f1-06de-49ad-8a8d-91693ca92e99")] public static extern HRESULT CoLockObjectExternal([In, MarshalAs(UnmanagedType.IUnknown)] object pUnk, [MarshalAs(UnmanagedType.Bool)] bool fLock, [MarshalAs(UnmanagedType.Bool)] bool fLastUnlockReleases); /// <summary> /// <para>Marshals an <c>HRESULT</c> to the specified stream, from which it can be unmarshaled using the CoUnmarshalHresult function.</para> /// </summary> /// <param name="pstm"> /// <para>A pointer to the marshaling stream. See IStream.</para> /// </param> /// <param name="hresult"> /// <para>The <c>HRESULT</c> in the originating process.</para> /// </param> /// <returns> /// <para>This function can return the standard return values E_OUTOFMEMORY and E_UNEXPECTED, as well as the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The HRESULT was marshaled successfully.</term> /// </item> /// <item> /// <term>STG_E_INVALIDPOINTER</term> /// <term>A bad pointer was specified for pstm.</term> /// </item> /// <item> /// <term>STG_E_MEDIUMFULL</term> /// <term>The medium is full.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// An <c>HRESULT</c> is process-specific, so an <c>HRESULT</c> that is valid in one process might not be valid in another. If you /// are writing your own implementation of IMarshal and need to marshal an <c>HRESULT</c> from one process to another, either as a /// parameter or a return code, you must call this function. In other circumstances, you will have no need to call this function. /// </para> /// <para>This function performs the following tasks:</para> /// <list type="number"> /// <item> /// <term>Writes an <c>HRESULT</c> to a stream.</term> /// </item> /// <item> /// <term>Returns an IStream pointer to that stream.</term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-comarshalhresult HRESULT CoMarshalHresult( LPSTREAM // pstm, HRESULT hresult ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "37aaf404-49ca-4881-a369-44c5288abf1d")] public static extern HRESULT CoMarshalHresult(IStream pstm, HRESULT hresult); /// <summary>Writes into a stream the data required to initialize a proxy object in some client process.</summary> /// <param name="pStm">A pointer to the stream to be used during marshaling. See IStream.</param> /// <param name="riid"> /// A reference to the identifier of the interface to be marshaled. This interface must be derived from the IUnknown interface. /// </param> /// <param name="pUnk">A pointer to the interface to be marshaled. This interface must be derived from the IUnknown interface.</param> /// <param name="dwDestContext"> /// The destination context where the specified interface is to be unmarshaled. The possible values come from the enumeration MSHCTX. /// Currently, unmarshaling can occur in another apartment of the current process (MSHCTX_INPROC), in another process on the same /// computer as the current process (MSHCTX_LOCAL), or in a process on a different computer (MSHCTX_DIFFERENTMACHINE). /// </param> /// <param name="pvDestContext">This parameter is reserved and must be <c>NULL</c>.</param> /// <param name="mshlflags"> /// The flags that specify whether the data to be marshaled is to be transmitted back to the client process (the typical case) or /// written to a global table, where it can be retrieved by multiple clients. The possibles values come from the MSHLFLAGS enumeration. /// </param> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_OUTOFMEMORY, and E_UNEXPECTED, the stream-access error values /// returned by IStream, as well as the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The HRESULT was marshaled successfully.</term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>The CoInitialize or OleInitialize function was not called on the current thread before this function was called.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// The <c>CoMarshalInterface</c> function marshals the interface referred to by riid on the object whose IUnknown implementation is /// pointed to by pUnk. To do so, the <c>CoMarshalInterface</c> function performs the following tasks: /// </para> /// <list type="number"> /// <item> /// <term> /// Queries the object for a pointer to the IMarshal interface. If the object does not implement <c>IMarshal</c>, meaning that it /// relies on COM to provide marshaling support, <c>CoMarshalInterface</c> gets a pointer to COM's default implementation of <c>IMarshal</c>. /// </term> /// </item> /// <item> /// <term> /// Gets the CLSID of the object's proxy by calling IMarshal::GetUnmarshalClass, using whichever IMarshal interface pointer has been returned. /// </term> /// </item> /// <item> /// <term>Writes the CLSID of the proxy to the stream to be used for marshaling.</term> /// </item> /// <item> /// <term>Marshals the interface pointer by calling IMarshal::MarshalInterface.</term> /// </item> /// </list> /// <para> /// The COM library in the client process calls the CoUnmarshalInterface function to extract the data and initialize the proxy. /// Before calling <c>CoUnmarshalInterface</c>, seek back to the original position in the stream. /// </para> /// <para> /// If you are implementing existing COM interfaces or defining your own interfaces using the Microsoft Interface Definition Language /// (MIDL), the MIDL-generated proxies and stubs call <c>CoMarshalInterface</c> for you. If you are writing your own proxies and /// stubs, your proxy code and stub code should each call <c>CoMarshalInterface</c> to correctly marshal interface pointers. Calling /// IMarshal directly from your proxy and stub code is not recommended. /// </para> /// <para> /// If you are writing your own implementation of IMarshal, and your proxy needs access to a private object, you can include an /// interface pointer to that object as part of the data you write to the stream. In such situations, if you want to use COM's /// default marshaling implementation when passing the interface pointer, you can call <c>CoMarshalInterface</c> on the object to do so. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-comarshalinterface HRESULT CoMarshalInterface( // LPSTREAM pStm, REFIID riid, LPUNKNOWN pUnk, DWORD dwDestContext, LPVOID pvDestContext, DWORD mshlflags ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "04ca1217-eac1-43e2-b736-8d7522ce8592")] public static extern HRESULT CoMarshalInterface(IStream pStm, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] object pUnk, MSHCTX dwDestContext, [Optional] IntPtr pvDestContext, MSHLFLAGS mshlflags); /// <summary>Marshals an interface pointer from one thread to another thread in the same process.</summary> /// <param name="riid">A reference to the identifier of the interface to be marshaled.</param> /// <param name="pUnk">A pointer to the interface to be marshaled, which must be derived from IUnknown. This parameter can be <c>NULL</c>.</param> /// <param name="ppStm"> /// The address of the IStream* pointer variable that receives the interface pointer to the stream that contains the marshaled interface. /// </param> /// <returns>This function can return the standard return values E_OUTOFMEMORY and S_OK.</returns> /// <remarks> /// <para> /// The <c>CoMarshalInterThreadInterfaceInStream</c> function enables an object to easily and reliably marshal an interface pointer /// to another thread in the same process. The stream returned in the ppStm parameter is guaranteed to behave correctly when a client /// running in the receiving thread attempts to unmarshal the pointer. The client can then call the CoGetInterfaceAndReleaseStream to /// unmarshal the interface pointer and release the stream object. /// </para> /// <para>The <c>CoMarshalInterThreadInterfaceInStream</c> function performs the following tasks:</para> /// <list type="number"> /// <item> /// <term>Creates a stream object.</term> /// </item> /// <item> /// <term>Passes the stream object's IStream pointer to CoMarshalInterface.</term> /// </item> /// <item> /// <term>Returns the IStream pointer to the caller.</term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-comarshalinterthreadinterfaceinstream HRESULT // CoMarshalInterThreadInterfaceInStream( REFIID riid, LPUNKNOWN pUnk, LPSTREAM *ppStm ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "c9ab8713-8604-4f0b-a11b-bdfb7d595d95")] public static extern HRESULT CoMarshalInterThreadInterfaceInStream(in Guid riid, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnk, out IStream ppStm); /// <summary>Retrieves a list of the authentication services registered when the process called CoInitializeSecurity.</summary> /// <param name="pcAuthSvc">A pointer to a variable that receives the number of entries returned in the asAuthSvc array.</param> /// <param name="asAuthSvc"> /// A pointer to an array of SOLE_AUTHENTICATION_SERVICE structures. The list is allocated through a call to the CoTaskMemAlloc /// function. The caller must free the list when finished with it by calling the CoTaskMemFree function. /// </param> /// <returns>This function can return the standard return values E_INVALIDARG, E_OUTOFMEMORY, and S_OK.</returns> /// <remarks> /// <para> /// <c>CoQueryAuthenticationServices</c> retrieves a list of the authentication services currently registered. If the process calls /// CoInitializeSecurity, these are the services registered through that call. If the application does not call it, /// <c>CoInitializeSecurity</c> is called automatically by COM, registering the default security package, the first time an interface /// is marshaled or unmarshaled. /// </para> /// <para> /// This function returns only the authentication services registered with CoInitializeSecurity. It does not return all of the /// authentication services installed on the computer, but EnumerateSecurityPackages does. <c>CoQueryAuthenticationServices</c> is /// primarily useful for custom marshalers, to determine which principal names an application can use. /// </para> /// <para> /// Different authentication services support different levels of security. For example, NTLMSSP does not support delegation or /// mutual authentication while Kerberos does. The application is responsible only for registering authentication services that /// provide the features the application needs. This function provides a way to find out which services have been registered with CoInitializeSecurity. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coqueryauthenticationservices HRESULT // CoQueryAuthenticationServices( DWORD *pcAuthSvc, SOLE_AUTHENTICATION_SERVICE **asAuthSvc ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "e9e7c5a3-70ec-4a68-ac21-1ab6774d140f")] public static extern HRESULT CoQueryAuthenticationServices(out uint pcAuthSvc, out SafeCoTaskMemHandle asAuthSvc); /// <summary> Retrieves a list of the authentication services registered when the process called CoInitializeSecurity. </summary> /// <returns>An array of SOLE_AUTHENTICATION_SERVICE structures.</returns> <remarks> <c>CoQueryAuthenticationServices</c> retrieves a /// list of the authentication services currently registered. If the process calls CoInitializeSecurity, these are the services /// registered through that call. If the application does not call it, <c>CoInitializeSecurity</c> is called automatically by COM, /// registering the default security package, the first time an interface is marshaled or unmarshaled.</para><para>This function /// returns only the authentication services registered with CoInitializeSecurity. It does not return all of the authentication /// services installed on the computer, but EnumerateSecurityPackages does. <c>CoQueryAuthenticationServices</c> is primarily useful /// for custom marshalers, to determine which principal names an application can use.</para><para>Different authentication services /// support different levels of security. For example, NTLMSSP does not support delegation or mutual authentication while Kerberos /// does. The application is responsible only for registering authentication services that provide the features the application /// needs. This function provides a way to find out which services have been registered with CoInitializeSecurity. </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coqueryauthenticationservices HRESULT // CoQueryAuthenticationServices( DWORD *pcAuthSvc, SOLE_AUTHENTICATION_SERVICE **asAuthSvc ); [PInvokeData("combaseapi.h", MSDNShortId = "e9e7c5a3-70ec-4a68-ac21-1ab6774d140f")] public static SOLE_AUTHENTICATION_SERVICE[] CoQueryAuthenticationServices() { CoQueryAuthenticationServices(out var c, out var a).ThrowIfFailed(); return a.ToArray<SOLE_AUTHENTICATION_SERVICE>((int)c); } /// <summary> /// Called by the server to find out about the client that invoked the method executing on the current thread. This is a helper /// function for IServerSecurity::QueryBlanket. /// </summary> /// <param name="pAuthnSvc"> /// A pointer to a variable that receives the current authentication service. This will be a single value taken from the /// authentication service constants. If the caller specifies <c>NULL</c>, the current authentication service is not retrieved. /// </param> /// <param name="pAuthzSvc"> /// A pointer to a variable that receives the current authorization service. This will be a single value taken from the authorization /// constants. If the caller specifies <c>NULL</c>, the current authorization service is not retrieved. /// </param> /// <param name="StringBuilder">The string builder.</param> /// <param name="">The .</param> /// <param name="pAuthnLevel"> /// A pointer to a variable that receives the current authentication level. This will be a single value taken from the authentication /// level constants. If the caller specifies <c>NULL</c>, the current authentication level is not retrieved. /// </param> /// <param name="pImpLevel">This parameter must be <c>NULL</c>.</param> /// <param name="pPrivs"> /// A pointer to a handle that receives the privilege information for the client application. The format of the structure that the /// handle refers to depends on the authentication service. The application should not write or free the memory. The information is /// valid only for the duration of the current call. For NTLMSSP and Kerberos, this is a string identifying the client principal. For /// Schannel, this is a CERT_CONTEXT structure that represents the client's certificate. If the client has no certificate, /// <c>NULL</c> is returned. If the caller specifies <c>NULL</c>, the current privilege information is not retrieved. See RPC_AUTHZ_HANDLE. /// </param> /// <param name="pCapabilities"> /// A pointer to return flags indicating capabilities of the call. To request that the principal name be returned in fullsic form if /// Schannel is the authentication service, the caller can set the EOAC_MAKE_FULLSIC flag in this parameter. If the caller specifies /// <c>NULL</c>, the current capabilities are not retrieved. /// </param> /// <returns>This function can return the standard return values E_INVALIDARG, E_OUTOFMEMORY, and S_OK.</returns> /// <remarks> /// <para> /// <c>CoQueryClientBlanket</c> is called by the server to get security information about the client that invoked the method /// executing on the current thread. This function encapsulates the following sequence of common calls (error handling excluded): /// </para> /// <para> /// This sequence calls CoGetCallContext to get a pointer to IServerSecurity and, with the resulting pointer, calls /// IServerSecurity::QueryBlanket and then releases the pointer. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coqueryclientblanket HRESULT CoQueryClientBlanket( // DWORD *pAuthnSvc, DWORD *pAuthzSvc, LPOLESTR *pServerPrincName, DWORD *pAuthnLevel, DWORD *pImpLevel, RPC_AUTHZ_HANDLE *pPrivs, // DWORD *pCapabilities ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "58a2c121-c324-4c33-aaca-490b5a09738c")] public static extern HRESULT CoQueryClientBlanket(out RPC_C_AUTHN pAuthnSvc, out RPC_C_AUTHZ pAuthzSvc, out SafeCoTaskMemString pServerPrincName, out RPC_C_AUTHN_LEVEL pAuthnLevel, out RPC_C_IMP_LEVEL pImpLevel, out RPC_AUTHZ_HANDLE pPrivs, ref EOLE_AUTHENTICATION_CAPABILITIES pCapabilities); /// <summary> /// Retrieves the authentication information the client uses to make calls on the specified proxy. This is a helper function for IClientSecurity::QueryBlanket. /// </summary> /// <param name="pProxy"> /// A pointer indicating the proxy to query. This parameter cannot be <c>NULL</c>. For more information, see the Remarks section. /// </param> /// <param name="pwAuthnSvc"> /// A pointer to a variable that receives the current authentication level. This will be a single value taken from the authentication /// level constants. If the caller specifies <c>NULL</c>, the current authentication level is not retrieved. /// </param> /// <param name="pAuthzSvc"> /// A pointer to a variable that receives the current authorization service. This will be a single value taken from the authorization /// constants. If the caller specifies <c>NULL</c>, the current authorization service is not retrieved. /// </param> /// <param name="pServerPrincName"> /// The current principal name. The string will be allocated by the callee using CoTaskMemAlloc, and must be freed by the caller /// using CoTaskMemFree. The EOAC_MAKE_FULLSIC flag is not accepted in the pCapabilities parameter. For more information about the /// msstd and fullsic forms, see Principal Names. If the caller specifies <c>NULL</c>, the current principal name is not retrieved. /// </param> /// <param name="pAuthnLevel"> /// A pointer to a variable that receives the current authentication level. This will be a single value taken from the authentication /// level constants. If the caller specifies <c>NULL</c>, the current authentication level is not retrieved. /// </param> /// <param name="pImpLevel"> /// A pointer to a variable that receives the current impersonation level. This will be a single value taken from the impersonation /// level constants. If the caller specifies <c>NULL</c>, the current impersonation level is not retrieved. /// </param> /// <param name="pAuthInfo"> /// A pointer to a handle that receives the identity of the client that was passed to the last IClientSecurity::SetBlanket call (or /// the default value). Default values are only valid until the proxy is released. If the caller specifies <c>NULL</c>, the client /// identity is not retrieved. The format of the structure that the handle refers to depends on the authentication service. The /// application should not write or free the memory. For NTLMSSP and Kerberos, if the client specified a structure in the pAuthInfo /// parameter to CoInitializeSecurity, that value is returned. For Schannel, if a certificate for the client could be retrieved from /// the certificate manager, that value is returned here. Otherwise, <c>NULL</c> is returned. See RPC_AUTH_IDENTITY_HANDLE. /// </param> /// <param name="pCapabilites"> /// A pointer to a variable that receives the capabilities of the proxy. If the caller specifies <c>NULL</c>, the current capability /// flags are not retrieved. /// </param> /// <returns>This function can return the standard return values E_INVALIDARG, E_OUTOFMEMORY, and S_OK.</returns> /// <remarks> /// <para> /// <c>CoQueryProxyBlanket</c> is called by the client to retrieve the authentication information COM will use on calls made from the /// specified proxy. This function encapsulates the following sequence of common calls (error handling excluded): /// </para> /// <para> /// This sequence calls QueryInterface on the proxy to get a pointer to IClientSecurity, and with the resulting pointer, calls /// IClientSecurity::QueryBlanket and then releases the pointer. /// </para> /// <para> /// In pProxy, you can pass any proxy, such as a proxy you get through a call to CoCreateInstance or CoUnmarshalInterface, or you can /// pass an interface pointer. It can be any interface. You cannot pass a pointer to something that is not a proxy. Therefore, you /// can't pass a pointer to an interface that has the local keyword in its interface definition because no proxy is created for such /// an interface. IUnknown is the exception to this rule. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coqueryproxyblanket HRESULT CoQueryProxyBlanket( // IUnknown *pProxy, DWORD *pwAuthnSvc, DWORD *pAuthzSvc, LPOLESTR *pServerPrincName, DWORD *pAuthnLevel, DWORD *pImpLevel, // RPC_AUTH_IDENTITY_HANDLE *pAuthInfo, DWORD *pCapabilites ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "e613e06a-0900-413e-bde2-39ce1612fed1")] public static extern HRESULT CoQueryProxyBlanket([In, MarshalAs(UnmanagedType.IUnknown)] object pProxy, out RPC_C_AUTHN pAuthnLevel, out RPC_C_AUTHZ pAuthzSvc, SafeCoTaskMemString pServerPrincName, out RPC_C_AUTHN_LEVEL pwAuthnSvc, out RPC_C_IMP_LEVEL pImpLevel, out RPC_AUTH_IDENTITY_HANDLE pAuthInfo, ref EOLE_AUTHENTICATION_CAPABILITIES pCapabilites); /// <summary>Registers a process-wide filter to process activation requests.</summary> /// <param name="pActivationFilter">Pointer to the filter to register.</param> /// <returns>If this function succeeds, it returns <c>S_OK</c>. Otherwise, it returns an <c>HRESULT</c> error code.</returns> /// <remarks>This registers one and only one process-wide filter.</remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coregisteractivationfilter HRESULT // CoRegisterActivationFilter( IActivationFilter *pActivationFilter ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "4189633F-9B14-4EAD-84BD-F74355376164")] public static extern HRESULT CoRegisterActivationFilter([In] IActivationFilter pActivationFilter); /// <summary>Registers an EXE class object with OLE so other applications can connect to it.</summary> /// <param name="rclsid">The CLSID to be registered.</param> /// <param name="pUnk">A pointer to the IUnknown interface on the class object whose availability is being published.</param> /// <param name="dwClsContext"> /// The context in which the executable code is to be run. For information on these context values, see the CLSCTX enumeration. /// </param> /// <param name="flags"> /// Indicates how connections are made to the class object. For information on these flags, see the REGCLS enumeration. /// </param> /// <param name="lpdwRegister"> /// A pointer to a value that identifies the class object registered; later used by the CoRevokeClassObject function to revoke the registration. /// </param> /// <returns> /// <para> /// This function can return the standard return values E_INVALIDARG, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The class object was registered successfully.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// EXE object applications should call <c>CoRegisterClassObject</c> on startup. It can also be used to register internal objects for /// use by the same EXE or other code (such as DLLs) that the EXE uses. Only EXE object applications call /// <c>CoRegisterClassObject</c>. Object handlers or DLL object applications do not call this function — instead, they must implement /// and export the DllGetClassObject function. /// </para> /// <para> /// At startup, a multiple-use EXE object application must create a class object (with the IClassFactory interface on it), and call /// <c>CoRegisterClassObject</c> to register the class object. Object applications that support several different classes (such as /// multiple types of embeddable objects) must allocate and register a different class object for each. /// </para> /// <para> /// Multiple registrations of the same class object are independent and do not produce an error. Each subsequent registration yields /// a unique key in lpdwRegister. /// </para> /// <para> /// Multiple document interface (MDI) applications must register their class objects. Single document interface (SDI) applications /// must register their class objects only if they can be started by means of the <c>/Embedding</c> switch. /// </para> /// <para> /// The server for a class object should call CoRevokeClassObject to revoke the class object (remove its registration) when all of /// the following are true: /// </para> /// <list type="bullet"> /// <item> /// <term>There are no existing instances of the object definition.</term> /// </item> /// <item> /// <term>There are no locks on the class object.</term> /// </item> /// <item> /// <term>The application providing services to the class object is not under user control (not visible to the user on the display).</term> /// </item> /// </list> /// <para> /// After the class object is revoked, when its reference count reaches zero, the class object can be released, allowing the /// application to exit. Note that <c>CoRegisterClassObject</c> calls IUnknown::AddRef and CoRevokeClassObject calls /// IUnknown::Release, so the two functions form an <c>AddRef</c>/ <c>Release</c> pair. /// </para> /// <para> /// As of Windows Server 2003, if a COM object application is registered as a service, COM verifies the registration. COM makes sure /// the process ID of the service, in the service control manager (SCM), matches the process ID of the registering process. If not, /// COM fails the registration. If the COM object application runs in the system account with no registry key, COM treats the objects /// application identity as Launching User. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coregisterclassobject HRESULT CoRegisterClassObject( // REFCLSID rclsid, LPUNKNOWN pUnk, DWORD dwClsContext, DWORD flags, LPDWORD lpdwRegister ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "d27bfa6c-194a-41f1-8fcf-76c4dff14a8a")] public static extern HRESULT CoRegisterClassObject(in Guid rclsid, [MarshalAs(UnmanagedType.IUnknown)] object pUnk, CLSCTX dwClsContext, REGCLS flags, out uint lpdwRegister); /// <summary> /// Enables a downloaded DLL to register its custom interfaces within its running process so that the marshaling code will be able to /// marshal those interfaces. /// </summary> /// <param name="riid">A pointer to the IID of the interface to be registered.</param> /// <param name="rclsid"> /// A pointer to the CLSID of the DLL that contains the proxy/stub code for the custom interface specified by riid. /// </param> /// <returns>This function can return the standard return values E_INVALIDARG, E_OUTOFMEMORY, and S_OK.</returns> /// <remarks> /// <para> /// Typically, the code responsible for marshaling an interface pointer into the current running process reads the /// <c>HKEY_CLASSES_ROOT\Interfaces</c> section of the registry to obtain the CLSID of the DLL containing the ProxyStub code to be /// loaded. To obtain the ProxyStub CLSIDs for an existing interface, the code calls the CoGetPSClsid function. /// </para> /// <para> /// In some cases, however, it may be desirable or necessary for an in-process handler or in-process server to make its custom /// interfaces available without writing to the registry. A DLL downloaded across a network may not even have permission to access /// the local registry, and because the code originated on another computer, the user, for security purposes, may want to run it in a /// restricted environment. Or a DLL may have custom interfaces that it uses to talk to a remote server and may also include the /// ProxyStub code for those interfaces. In such cases, a DLL needs an alternative way to register its interfaces. /// <c>CoRegisterPSClsid</c>, used in conjunction with CoRegisterClassObject, provides that alternative. /// </para> /// <para>Examples</para> /// <para>A DLL would typically call <c>CoRegisterPSClsid</c> as shown in the following code fragment.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coregisterpsclsid HRESULT CoRegisterPSClsid( REFIID // riid, REFCLSID rclsid ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "a73dbd6d-d3f2-48d7-b053-b62f2f18f2d6")] public static extern HRESULT CoRegisterPSClsid(in Guid riid, in Guid rclsid); /// <summary>Registers the surrogate process through its ISurrogate interface pointer.</summary> /// <param name="pSurrogate">A pointer to the ISurrogate interface on the surrogate process to be registered.</param> /// <returns>This function returns S_OK to indicate that the surrogate process was registered successfully.</returns> /// <remarks> /// <para> /// The <c>CoRegisterSurrogate</c> function sets a global interface pointer to the ISurrogate interface implemented on the surrogate /// process. This pointer is set in the ole32 DLL loaded in the surrogate process. COM uses this global pointer in ole32 to call the /// methods of <c>ISurrogate</c>. This function is usually called by the surrogate implementation when it is launched. /// </para> /// <para> /// As of Windows Server 2003, if a COM object application is registered as a service, COM verifies the registration. COM makes sure /// the process ID of the service, in the service control manager (SCM), matches the process ID of the registering process. If not, /// COM fails the registration. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coregistersurrogate HRESULT CoRegisterSurrogate( // LPSURROGATE pSurrogate ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "4d1c6ca6-ab21-429c-9433-7c95d9e757b5")] public static extern HRESULT CoRegisterSurrogate(ISurrogate pSurrogate); /// <summary>Destroys a previously marshaled data packet.</summary> /// <param name="pStm">A pointer to the stream that contains the data packet to be destroyed. See IStream.</param> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_INVALIDARG, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the /// following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The data packet was successfully destroyed.</term> /// </item> /// <item> /// <term>STG_E_INVALIDPOINTER</term> /// <term>An error related to the pStm parameter.</term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>The CoInitialize or OleInitialize function was not called on the current thread before this function was called.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// <c>Important</c> Security Note: Calling this method with untrusted data is a security risk. Call this method only with trusted /// data. For more information, see Untrusted Data Security Risks. /// </para> /// <para>The <c>CoReleaseMarshalData</c> function performs the following tasks:</para> /// <list type="number"> /// <item> /// <term>The function reads a CLSID from the stream.</term> /// </item> /// <item> /// <term> /// If COM's default marshaling implementation is being used, the function gets an IMarshal pointer to an instance of the standard /// unmarshaler. If custom marshaling is being used, the function creates a proxy by calling the CoCreateInstance function, passing /// the CLSID it read from the stream, and requests an <c>IMarshal</c> interface pointer to the newly created proxy. /// </term> /// </item> /// <item> /// <term>Using whichever IMarshal interface pointer it has acquired, the function calls IMarshal::ReleaseMarshalData.</term> /// </item> /// </list> /// <para> /// You typically do not call this function. The only situation in which you might need to call this function is if you use custom /// marshaling (write and use your own implementation of IMarshal). Examples of when <c>CoReleaseMarshalData</c> should be called /// include the following situations: /// </para> /// <list type="bullet"> /// <item> /// <term>An attempt was made to unmarshal the data packet, but it failed.</term> /// </item> /// <item> /// <term>A marshaled data packet was removed from a global table.</term> /// </item> /// </list> /// <para> /// As an analogy, the data packet can be thought of as a reference to the original object, just as if it were another interface /// pointer being held on the object. Like a real interface pointer, that data packet must be released at some point. The use of /// IMarshal::ReleaseMarshalData to release data packets is analogous to the use of IUnknown::Release to release interface pointers. /// </para> /// <para> /// Note that you do not need to call <c>CoReleaseMarshalData</c> after a successful call of the CoUnmarshalInterface function; that /// function releases the marshal data as part of the processing that it does. /// </para> /// <para> /// <c>Important</c> You must call the <c>CoReleaseMarshalData</c> function in the same apartment that called CoMarshalInterface to /// marshal the object into the stream. Failure to do this may cause the object reference held by the marshaled packet in the stream /// to be leaked. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coreleasemarshaldata HRESULT CoReleaseMarshalData( // LPSTREAM pStm ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "a642a20f-3a3c-46bc-b833-e424dab3a16d")] public static extern HRESULT CoReleaseMarshalData(IStream pStm); /// <summary>Decrements the global per-process reference count.</summary> /// <returns> /// If the server application should initiate its cleanup, the function returns 0; otherwise, the function returns a nonzero value. /// </returns> /// <remarks> /// <para> /// Servers can call <c>CoReleaseServerProcess</c> to decrement a global per-process reference count incremented through a call to CoAddRefServerProcess. /// </para> /// <para> /// When that count reaches zero, OLE automatically calls CoSuspendClassObjects, which prevents new activation requests from coming /// in. This permits the server to deregister its class objects from its various threads without worry that another activation /// request may come in. New activation requests result in launching a new instance of the local server process. /// </para> /// <para> /// The simplest way for a local server application to make use of these functions is to call CoAddRefServerProcess in the /// constructor for each of its instance objects, and in each of its IClassFactory::LockServer methods when the fLock parameter is /// <c>TRUE</c>. The server application should also call <c>CoReleaseServerProcess</c> in the destructor of each of its instance /// objects, and in each of its <c>IClassFactory::LockServer</c> methods when the fLock parameter is <c>FALSE</c>. Finally, the /// server application must check the return code from <c>CoReleaseServerProcess</c>; if it returns 0, the server application should /// initiate its cleanup. This typically means that a server with multiple threads should signal its various threads to exit their /// message loops and call CoRevokeClassObject and CoUninitialize. /// </para> /// <para> /// If these APIs are used at all, they must be called in both the object instances and the LockServer method, otherwise the server /// application may be shutdown prematurely. In-process Servers typically should not call CoAddRefServerProcess or <c>CoReleaseServerProcess</c>. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coreleaseserverprocess ULONG CoReleaseServerProcess( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "b28d41e2-4144-413d-9963-14f2d4dc8876")] public static extern uint CoReleaseServerProcess(); /// <summary> /// Called by a server that can register multiple class objects to inform the SCM about all registered classes, and permits /// activation requests for those class objects. /// </summary> /// <returns>This function returns S_OK to indicate that the CLSID was retrieved successfully.</returns> /// <remarks> /// <para> /// Servers that can register multiple class objects call <c>CoResumeClassObjects</c> once, after having first called /// CoRegisterClassObject, specifying REGCLS_LOCAL_SERVER | REGCLS_SUSPENDED for each CLSID the server supports. This function causes /// OLE to inform the SCM about all the registered classes, and begins letting activation requests into the server process. /// </para> /// <para> /// This reduces the overall registration time, and thus the server application startup time, by making a single call to the SCM, no /// matter how many CLSIDs are registered for the server. Another advantage is that if the server has multiple apartments with /// different CLSIDs registered in different apartments, or is a free-threaded server, no activation requests will come in until the /// server calls <c>CoResumeClassObjects</c>. This gives the server a chance to register all of its CLSIDs and get properly set up /// before having to deal with activation requests, and possibly shutdown requests. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coresumeclassobjects HRESULT CoResumeClassObjects( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "c2b6e8d8-99a1-4af3-9881-bfe6932e4a76")] public static extern HRESULT CoResumeClassObjects(); /// <summary>Restores the authentication information on a thread of execution.</summary> /// <returns>This function supports the standard return values, including S_OK to indicate success.</returns> /// <remarks> /// <para> /// <c>CoRevertToSelf</c>, which is a helper function that calls IServerSecurity::RevertToSelf, restores the authentication /// information on a thread to the authentication information on the thread before impersonation began. /// </para> /// <para><c>CoRevertToSelf</c> encapsulates the following common sequence of calls (error handling excluded):</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coreverttoself HRESULT CoRevertToSelf( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "8061ddbe-ed21-47f7-9ac4-b3ec910ff89d")] public static extern HRESULT CoRevertToSelf(); /// <summary> /// Informs OLE that a class object, previously registered with the CoRegisterClassObject function, is no longer available for use. /// </summary> /// <param name="dwRegister">A token previously returned from the CoRegisterClassObject function.</param> /// <returns> /// <para> /// This function can return the standard return values E_INVALIDARG, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The class object was revoked successfully.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// A successful call to <c>CoRevokeClassObject</c> means that the class object has been removed from the global class object table /// (although it does not release the class object). If other clients still have pointers to the class object and have caused the /// reference count to be incremented by calls to IUnknown::AddRef, the reference count will not be zero. When this occurs, /// applications may benefit if subsequent calls (with the obvious exceptions of <c>AddRef</c> and IUnknown::Release) to the class /// object fail. Note that CoRegisterClassObject calls <c>AddRef</c> and <c>CoRevokeClassObject</c> calls <c>Release</c>, so the two /// functions form an <c>AddRef</c>/ <c>Release</c> pair. /// </para> /// <para> /// An object application must call <c>CoRevokeClassObject</c> to revoke registered class objects before exiting the program. Class /// object implementers should call <c>CoRevokeClassObject</c> as part of the release sequence. You must specifically revoke the /// class object even when you have specified the flags value REGCLS_SINGLEUSE in a call to CoRegisterClassObject, indicating that /// only one application can connect to the class object. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-corevokeclassobject HRESULT CoRevokeClassObject( // DWORD dwRegister ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "90b9b9ca-b5b2-48f5-8c2a-b478b6daa7ec")] public static extern HRESULT CoRevokeClassObject(uint dwRegister); /// <summary> /// Sets (registers) or resets (unregisters) a cancel object for use during subsequent cancel operations on the current thread. /// </summary> /// <param name="pUnk"> /// Pointer to the IUnknown interface on the cancel object to be set or reset on the current thread. If this parameter is /// <c>NULL</c>, the topmost cancel object is reset. /// </param> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_INVALIDARG, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the /// following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The cancel object was successfully set or reset.</term> /// </item> /// <item> /// <term>E_ACCESSDENIED</term> /// <term>The cancel object cannot be set or reset at this time because of a block on cancel operations.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// For objects that support standard marshaling, the proxy object begins marshaling a method call by calling /// <c>CoSetCancelObject</c> to register a cancel object for the current thread. /// </para> /// <para> /// <c>CoSetCancelObject</c> calls QueryInterface for ICancelMethodCalls on the cancel object. If the cancel object does not /// implement <c>ICancelMethodCalls</c>, <c>CoSetCancelObject</c> fails with E_NOINTERFACE. To disable cancel operations on a /// custom-marshaled interface, the implementation of ICancelMethodCalls::Cancel should do nothing but return E_NOTIMPL, E_FAIL, or /// some other appropriate value. /// </para> /// <para><c>CoSetCancelObject</c> calls AddRef on objects that it registers and Release on objects that it unregisters.</para> /// <para><c>CoSetCancelObject</c> does not set or reset cancel objects for asynchronous methods.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cosetcancelobject HRESULT CoSetCancelObject( // IUnknown *pUnk ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "0978e252-2206-4597-abf2-fe0dac32efc4")] public static extern HRESULT CoSetCancelObject([In, MarshalAs(UnmanagedType.IUnknown)] object pUnk); /// <summary> /// Sets the authentication information that will be used to make calls on the specified proxy. This is a helper function for IClientSecurity::SetBlanket. /// </summary> /// <param name="pProxy">The proxy to be set.</param> /// <param name="dwAuthnSvc"> /// The authentication service to be used. For a list of possible values, see Authentication Service Constants. Use RPC_C_AUTHN_NONE /// if no authentication is required. If RPC_C_AUTHN_DEFAULT is specified, DCOM will pick an authentication service following its /// normal security blanket negotiation algorithm. /// </param> /// <param name="dwAuthzSvc"> /// The authorization service to be used. For a list of possible values, see Authorization Constants. If RPC_C_AUTHZ_DEFAULT is /// specified, DCOM will pick an authorization service following its normal security blanket negotiation algorithm. RPC_C_AUTHZ_NONE /// should be used as the authorization service if NTLMSSP, Kerberos, or Schannel is used as the authentication service. /// </param> /// <param name="pServerPrincName"> /// <para> /// The server principal name to be used with the authentication service. If COLE_DEFAULT_PRINCIPAL is specified, DCOM will pick a /// principal name using its security blanket negotiation algorithm. If Kerberos is used as the authentication service, this value /// must not be <c>NULL</c>. It must be the correct principal name of the server or the call will fail. /// </para> /// <para> /// If Schannel is used as the authentication service, this value must be one of the msstd or fullsic forms described in Principal /// Names, or <c>NULL</c> if you do not want mutual authentication. /// </para> /// <para> /// Generally, specifying <c>NULL</c> will not reset the server principal name on the proxy; rather, the previous setting will be /// retained. You must be careful when using <c>NULL</c> as pServerPrincName when selecting a different authentication service for /// the proxy, because there is no guarantee that the previously set principal name would be valid for the newly selected /// authentication service. /// </para> /// </param> /// <param name="dwAuthnLevel"> /// The authentication level to be used. For a list of possible values, see Authentication Level Constants. If /// RPC_C_AUTHN_LEVEL_DEFAULT is specified, DCOM will pick an authentication level following its normal security blanket negotiation /// algorithm. If this value is none, the authentication service must also be none. /// </param> /// <param name="dwImpLevel"> /// The impersonation level to be used. For a list of possible values, see Impersonation Level Constants. If RPC_C_IMP_LEVEL_DEFAULT /// is specified, DCOM will pick an impersonation level following its normal security blanket negotiation algorithm. If NTLMSSP is /// the authentication service, this value must be RPC_C_IMP_LEVEL_IMPERSONATE or RPC_C_IMP_LEVEL_IDENTIFY. NTLMSSP also supports /// delegate-level impersonation (RPC_C_IMP_LEVEL_DELEGATE) on the same computer. If Schannel is the authentication service, this /// parameter must be RPC_C_IMP_LEVEL_IMPERSONATE. /// </param> /// <param name="pAuthInfo"> /// <para> /// A pointer to an <c>RPC_AUTH_IDENTITY_HANDLE</c> value that establishes the identity of the client. The format of the structure /// referred to by the handle depends on the provider of the authentication service. /// </para> /// <para> /// For calls on the same computer, RPC logs on the user with the supplied credentials and uses the resulting token for the method call. /// </para> /// <para> /// For NTLMSSP or Kerberos, the structure is a SEC_WINNT_AUTH_IDENTITY or SEC_WINNT_AUTH_IDENTITY_EX structure. The client can /// discard pAuthInfo after calling the API. RPC does not keep a copy of the pAuthInfo pointer, and the client cannot retrieve it /// later in the CoQueryProxyBlanket method. /// </para> /// <para> /// If this parameter is <c>NULL</c>, DCOM uses the current proxy identity (which is either the process token or the impersonation /// token). If the handle refers to a structure, that identity is used. /// </para> /// <para> /// For Schannel, this parameter must be either a pointer to a CERT_CONTEXT structure that contains the client's X.509 certificate or /// is <c>NULL</c> if the client wishes to make an anonymous connection to the server. If a certificate is specified, the caller must /// not free it as long as any proxy to the object exists in the current apartment. /// </para> /// <para> /// For Snego, this member is either <c>NULL</c>, points to a SEC_WINNT_AUTH_IDENTITY structure, or points to a /// SEC_WINNT_AUTH_IDENTITY_EX structure. If it is <c>NULL</c>, Snego will pick a list of authentication services based on those /// available on the client computer. If it points to a <c>SEC_WINNT_AUTH_IDENTITY_EX</c> structure, the structure's /// <c>PackageList</c> member must point to a string containing a comma-separated list of authentication service names and the /// <c>PackageListLength</c> member must give the number of bytes in the <c>PackageList</c> string. If <c>PackageList</c> is /// <c>NULL</c>, all calls using Snego will fail. /// </para> /// <para> /// If COLE_DEFAULT_AUTHINFO is specified for this parameter, DCOM will pick the authentication information following its normal /// security blanket negotiation algorithm. /// </para> /// <para><c>CoSetProxyBlanket</c> will fail if pAuthInfo is set and one of the cloaking flags is set in the dwCapabilities parameter.</para> /// </param> /// <param name="dwCapabilities"> /// The capabilities of this proxy. For a list of possible values, see the EOLE_AUTHENTICATION_CAPABILITIES enumeration. The only /// flags that can be set through this function are EOAC_MUTUAL_AUTH, EOAC_STATIC_CLOAKING, EOAC_DYNAMIC_CLOAKING, EOAC_ANY_AUTHORITY /// (this flag is deprecated), EOAC_MAKE_FULLSIC, and EOAC_DEFAULT. Either EOAC_STATIC_CLOAKING or EOAC_DYNAMIC_CLOAKING can be set /// if pAuthInfo is not set and Schannel is not the authentication service. (See Cloaking for more information.) If any capability /// flags other than those mentioned here are set, <c>CoSetProxyBlanket</c> will fail. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The function was successful.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>One or more arguments is invalid.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// <c>CoSetProxyBlanket</c> sets the authentication information that will be used to make calls on the specified proxy. This /// function encapsulates the following sequence of common calls (error handling excluded). /// </para> /// <para> /// This sequence calls QueryInterface on the proxy to get a pointer to IClientSecurity, and with the resulting pointer, calls /// IClientSecurity::SetBlanket and then releases the pointer. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cosetproxyblanket HRESULT CoSetProxyBlanket( // IUnknown *pProxy, DWORD dwAuthnSvc, DWORD dwAuthzSvc, OLECHAR *pServerPrincName, DWORD dwAuthnLevel, DWORD dwImpLevel, // RPC_AUTH_IDENTITY_HANDLE pAuthInfo, DWORD dwCapabilities ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)] [PInvokeData("combaseapi.h", MSDNShortId = "c2e5e681-8fa5-4b02-b59d-ba796eb0dccf")] public static extern HRESULT CoSetProxyBlanket([In, MarshalAs(UnmanagedType.IUnknown)] object pProxy, RPC_C_AUTHN dwAuthnSvc, RPC_C_AUTHZ dwAuthzSvc, string pServerPrincName, RPC_C_AUTHN_LEVEL dwAuthnLevel, RPC_C_IMP_LEVEL dwImpLevel, RPC_AUTH_IDENTITY_HANDLE pAuthInfo, EOLE_AUTHENTICATION_CAPABILITIES dwCapabilities); /// <summary>Prevents any new activation requests from the SCM on all class objects registered within the process.</summary> /// <returns>This function returns S_OK to indicate that the activation of class objects was successfully suspended.</returns> /// <remarks> /// <c>CoSuspendClassObjects</c> prevents any new activation requests from the SCM on all class objects registered within the /// process. Even though a process may call this function, the process still must call the CoRevokeClassObject function for each /// CLSID it has registered, in the apartment it registered in. Applications typically do not need to call this function, which is /// generally only called internally by OLE when used in conjunction with the CoReleaseServerProcess function. /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cosuspendclassobjects HRESULT CoSuspendClassObjects( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "a9e526f8-b7c1-47ec-a6ab-91690d93119e")] public static extern HRESULT CoSuspendClassObjects(); /// <summary>Switches the call context object used by CoGetCallContext.</summary> /// <param name="pNewObject"> /// A pointer to an interface on the new call context object. COM stores this pointer without adding a reference to the pointer until /// <c>CoSwitchCallContext</c> is called with another object. This parameter may be <c>NULL</c> if you are calling /// <c>CoSwitchCallContext</c> to switch back to the original call context but there was no original call context. /// </param> /// <param name="ppOldObject"> /// The address of pointer variable that receives a pointer to the call context object of the call currently in progress. This value /// is returned so that the original call context can be restored by the custom marshaller. The returned pointer will be <c>NULL</c> /// if there was no call in progress. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The function was successful.</term> /// </item> /// <item> /// <term>E_OUT_OF_MEMORY</term> /// <term>Out of memory.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// Custom marshallers call <c>CoSwitchCallContext</c> to change the call context object used by the CoGetCallContext function. /// Before dispatching an arriving call, custom marshallers call <c>CoSwitchCallContext</c>, specifying the new context object. After /// sending a reply, they must restore the original call context by calling <c>CoSwitchCallContext</c> again, this time passing a /// pointer to the original context object. /// </para> /// <para> /// <c>CoSwitchCallContext</c> does not add a reference to the new context object. Custom marshallers must ensure that the lifetime /// of their context object continues throughout their call and until the call to restore the original context. Custom marshallers /// should not release the value that they placed into the ppOldObject parameter when they set their context. /// </para> /// <para>Call context objects provided by custom marshallers should support the IServerSecurity interface.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coswitchcallcontext HRESULT CoSwitchCallContext( // IUnknown *pNewObject, IUnknown **ppOldObject ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "146855a2-97ec-4e71-88dc-316eaa1a24a0")] public static extern HRESULT CoSwitchCallContext([In, MarshalAs(UnmanagedType.IUnknown)] object pNewObject, [MarshalAs(UnmanagedType.IUnknown)] out object ppOldObject); /// <summary> /// <para>Determines whether the call being executed on the server has been canceled by the client.</para> /// </summary> /// <returns> /// <para> /// This function can return the standard return values E_FAIL, E_INVALIDARG, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the /// following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>RPC_S_CALLPENDING</term> /// <term>The call is still pending and has not yet been canceled by the client.</term> /// </item> /// <item> /// <term>RPC_E_CALL_CANCELED</term> /// <term>The call has been canceled by the client.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// Server objects should call <c>CoTestCancel</c> at least once before returning to detect client cancellation requests. Doing so /// can save the server unnecessary work if the client has issued a cancellation request, and it can reduce the client's wait time if /// it has set the cancel timeout as RPC_C_CANCEL_INFINITE_TIMEOUT. Furthermore, if the server object detects a cancellation request /// before returning from a pending call, it can clean up any memory, marshaled interfaces, or handles it has created or obtained. /// </para> /// <para> /// <c>CoTestCancel</c> calls CoGetCallContext to obtain the ICancelMethodCalls interface on the current cancel object and then calls /// ICancelMethodCalls::TestCancel. Objects that implement custom marshaling should first call CoSwitchCallContext to install the /// appropriate call context object. /// </para> /// <para>This function does not test cancellation for asynchronous calls.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cotestcancel HRESULT CoTestCancel( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "9432621a-be31-4b8b-83b6-069539ba06b4")] public static extern HRESULT CoTestCancel(); /// <summary>Unmarshals an <c>HRESULT</c> type from the specified stream.</summary> /// <param name="pstm">A pointer to the stream from which the <c>HRESULT</c> is to be unmarshaled.</param> /// <param name="phresult">A pointer to the unmarshaled <c>HRESULT</c>.</param> /// <returns> /// <para>This function can return the standard return values E_OUTOFMEMORY and E_UNEXPECTED, as well as the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The HRESULT was unmarshaled successfully.</term> /// </item> /// <item> /// <term>STG_E_INVALIDPOINTER</term> /// <term>pStm is an invalid pointer.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// You do not explicitly call this function unless you are performing custom marshaling (that is, writing your own implementation of /// IMarshal), and your implementation needs to unmarshal an <c>HRESULT</c>. /// </para> /// <para> /// You must use <c>CoUnmarshalHresult</c> to unmarshal <c>HRESULT</c> values previously marshaled by a call to the CoMarshalHresult function. /// </para> /// <para>This function performs the following tasks:</para> /// <list type="number"> /// <item> /// <term>an <c>HRESULT</c> from a stream.</term> /// </item> /// <item> /// <term>Returns the <c>HRESULT</c>.</term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-counmarshalhresult HRESULT CoUnmarshalHresult( // LPSTREAM pstm, HRESULT *phresult ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "a45ef72c-d385-4012-9683-7d2cc6d68b6d")] public static extern HRESULT CoUnmarshalHresult(IStream pstm, out HRESULT phresult); /// <summary> /// Initializes a newly created proxy using data written into the stream by a previous call to the CoMarshalInterface function, and /// returns an interface pointer to that proxy. /// </summary> /// <param name="pStm">A pointer to the stream from which the interface is to be unmarshaled.</param> /// <param name="riid"> /// A reference to the identifier of the interface to be unmarshaled. For <c>IID_NULL</c>, the returned interface is the one defined /// by the stream, objref.iid. /// </param> /// <param name="ppv"> /// The address of pointer variable that receives the interface pointer requested in <paramref name="riid"/>. Upon successful return, /// <paramref name="ppv"/> contains the requested interface pointer for the unmarshaled interface. /// </param> /// <returns> /// <para>This function can return the standard return value E_FAIL, errors returned by CoCreateInstance, and the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The interface pointer was unmarshaled successfully.</term> /// </item> /// <item> /// <term>STG_E_INVALIDPOINTER</term> /// <term>pStm is an invalid pointer.</term> /// </item> /// <item> /// <term>CO_E_NOTINITIALIZED</term> /// <term>The CoInitialize or OleInitialize function was not called on the current thread before this function was called.</term> /// </item> /// <item> /// <term>CO_E_OBJNOTCONNECTED</term> /// <term> /// The object application has been disconnected from the remoting system (for example, as a result of a call to the /// CoDisconnectObject function). /// </term> /// </item> /// <item> /// <term>REGDB_E_CLASSNOTREG</term> /// <term>An error occurred reading the registration database.</term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>The final QueryInterface of this function for the requested interface returned E_NOINTERFACE.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// <c>Important</c> Security Note: Calling this method with untrusted data is a security risk. Call this method only with trusted /// data. For more information, see Untrusted Data Security Risks. /// </para> /// <para>The <c>CoUnmarshalInterface</c> function performs the following tasks:</para> /// <list type="number"> /// <item> /// <term>Reads from the stream the CLSID to be used to create an instance of the proxy.</term> /// </item> /// <item> /// <term> /// Gets an IMarshal pointer to the proxy that is to do the unmarshaling. If the object uses COM's default marshaling implementation, /// the pointer thus obtained is to an instance of the generic proxy object. If the marshaling is occurring between two threads in /// the same process, the pointer is to an instance of the in-process free threaded marshaler. If the object provides its own /// marshaling code, <c>CoUnmarshalInterface</c> calls the CoCreateInstance function, passing the CLSID it read from the marshaling /// stream. <c>CoCreateInstance</c> creates an instance of the object's proxy and returns an <c>IMarshal</c> interface pointer to the proxy. /// </term> /// </item> /// <item> /// <term> /// Using whichever IMarshal interface pointer it has acquired, the function then calls IMarshal::UnmarshalInterface and, if /// appropriate, IMarshal::ReleaseMarshalData. /// </term> /// </item> /// </list> /// <para> /// The primary caller of this function is COM itself, from within interface proxies or stubs that unmarshal an interface pointer. /// There are, however, some situations in which you might call <c>CoUnmarshalInterface</c>. For example, if you are implementing a /// stub, your implementation would call <c>CoUnmarshalInterface</c> when the stub receives an interface pointer as a parameter in a /// method call. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-counmarshalinterface HRESULT CoUnmarshalInterface( // LPSTREAM pStm, REFIID riid, LPVOID *ppv ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "d0eac0da-2f41-40c4-b756-31bc22752c17")] public static extern HRESULT CoUnmarshalInterface(IStream pStm, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); /// <summary>Waits for specified handles to be signaled or for a specified timeout period to elapse.</summary> /// <param name="dwFlags">The wait options. Possible values are taken from the COWAIT_FLAGS enumeration.</param> /// <param name="dwTimeout">The timeout period, in milliseconds.</param> /// <param name="cHandles">The number of elements in the pHandles array.</param> /// <param name="pHandles">An array of handles.</param> /// <param name="lpdwindex"> /// <para> /// A pointer to a variable that, when the returned status is S_OK, receives a value indicating the event that caused the function to /// return. This value is usually the index into pHandles for the handle that was signaled. /// </para> /// <para> /// If pHandles includes one or more handles to mutex objects, a value between WAIT_ABANDONED_0 and (WAIT_ABANDONED_0 + nCount– 1) /// indicates the index into pHandles for the mutex that was abandoned. /// </para> /// <para> /// If the COWAIT_ALERTABLE flag is set in dwFlags, a value of WAIT_IO_COMPLETION indicates the wait was ended by one or more /// user-mode asynchronous procedure calls (APC) queued to the thread. /// </para> /// <para>See WaitForMultipleObjectsEx for more information.</para> /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <para> /// <c>Note</c> The return value of <c>CoWaitForMultipleHandles</c> can be nondeterministic if the COWAIT_ALERTABLE flag is set in /// dwFlags, or if pHandles includes one or more handles to mutex objects. The recommended workaround is to call /// SetLastError(ERROR_SUCCESS) before <c>CoWaitForMultipleHandles</c>. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The required handle or handles were signaled.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>pHandles was NULL, lpdwindex was NULL, or dwFlags was not a value from the COWAIT_FLAGS enumeration.</term> /// </item> /// <item> /// <term>RPC_E_NO_SYNC</term> /// <term>The value of pHandles was 0.</term> /// </item> /// <item> /// <term>RPC_S_CALLPENDING</term> /// <term>The timeout period elapsed before the required handle or handles were signaled.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// Depending on which flags are set in the dwFlags parameter, <c>CoWaitForMultipleHandles</c> blocks the calling thread until one of /// the following events occurs: /// </para> /// <list type="bullet"> /// <item> /// <term> /// One or all of the handles is signaled. In the case of mutex objects, this condition is also satisfied by a mutex being abandoned. /// </term> /// </item> /// <item> /// <term>An asynchronous procedure call (APC) has been queued to the calling thread with a call to the QueueUserAPC function.</term> /// </item> /// <item> /// <term>The timeout period expires.</term> /// </item> /// </list> /// <para> /// If the caller resides in a single-thread apartment, <c>CoWaitForMultipleHandles</c> enters the COM modal loop, and the thread's /// message loop will continue to dispatch messages using the thread's message filter. If no message filter is registered for the /// thread, the default COM message processing is used. /// </para> /// <para> /// If the calling thread resides in a multithread apartment (MTA), <c>CoWaitForMultipleHandles</c> calls the /// WaitForMultipleObjectsEx function. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cowaitformultiplehandles HRESULT // CoWaitForMultipleHandles( DWORD dwFlags, DWORD dwTimeout, ULONG cHandles, LPHANDLE pHandles, LPDWORD lpdwindex ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "3eeecd34-aa94-4a48-8b41-167a71b52860")] public static extern HRESULT CoWaitForMultipleHandles(COWAIT_FLAGS dwFlags, uint dwTimeout, uint cHandles, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] pHandles, out uint lpdwindex); /// <summary> /// A replacement for CoWaitForMultipleHandles. This replacement API hides the options for <c>CoWaitForMultipleHandles</c> that are /// not supported in ASTA. /// </summary> /// <param name="dwFlags"> /// CWMO_FLAGS flag controlling whether call/window message reentrancy is enabled from this wait. By default, neither COM calls nor /// window messages are dispatched from <c>CoWaitForMultipleObjects</c> in ASTA. /// </param> /// <param name="dwTimeout">The timeout in milliseconds of the wait.</param> /// <param name="cHandles">The length of the pHandles array. Must be &lt;= 56.</param> /// <param name="pHandles">An array of handles to waitable kernel objects.</param> /// <param name="lpdwindex">Receives the index of the handle that satisfied the wait.</param> /// <returns> /// Same return values as CoWaitForMultipleHandles, except the ASTA-specific CO_E_NOTSUPPORTED cases instead return E_INVALIDARG from /// all apartment types. /// </returns> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-cowaitformultipleobjects HRESULT // CoWaitForMultipleObjects( DWORD dwFlags, DWORD dwTimeout, ULONG cHandles, const HANDLE *pHandles, LPDWORD lpdwindex ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "7A14E4F4-20F0-43FF-8D64-9AAC34B8D56F")] public static extern HRESULT CoWaitForMultipleObjects(CWMO_FLAGS dwFlags, uint dwTimeout, uint cHandles, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] pHandles, out uint lpdwindex); /// <summary> /// <para> /// The <c>CreateStreamOnHGlobal</c> function creates a stream object that uses an HGLOBAL memory handle to store the stream /// contents. This object is the OLE-provided implementation of the IStream interface. /// </para> /// <para> /// The returned stream object supports both reading and writing, is not transacted, and does not support region locking. The object /// calls the GlobalReAlloc function to grow the memory block as required. /// </para> /// <para> /// <c>Tip</c> Consider using the SHCreateMemStream function, which produces better performance, or for Windows Store apps, consider /// using InMemoryRandomAccessStream. /// </para> /// </summary> /// <param name="hGlobal"> /// A memory handle allocated by the GlobalAlloc function, or if <c>NULL</c> a new handle is to be allocated instead. The handle must /// be allocated as moveable and nondiscardable. /// </param> /// <param name="fDeleteOnRelease"> /// A value that indicates whether the underlying handle for this stream object should be automatically freed when the stream object /// is released. If set to <c>FALSE</c>, the caller must free the hGlobal after the final release. If set to <c>TRUE</c>, the final /// release will automatically free the hGlobal parameter. /// </param> /// <param name="ppstm"> /// The address of IStream* pointer variable that receives the interface pointer to the new stream object. Its value cannot be <c>NULL</c>. /// </param> /// <returns>This function supports the standard return values E_INVALIDARG and E_OUTOFMEMORY, as well as the following.</returns> /// <remarks> /// <para>If hGlobal is <c>NULL</c>, the function allocates a new memory handle and the stream is initially empty.</para> /// <para> /// If hGlobal is not <c>NULL</c>, the initial contents of the stream are the current contents of the memory block. Thus, /// <c>CreateStreamOnHGlobal</c> can be used to open an existing stream in memory. The memory handle and its contents are undisturbed /// by the creation of the new stream object. /// </para> /// <para> /// The initial size of the stream is the size of hGlobal as returned by the GlobalSize function. Because of rounding, this is not /// necessarily the same size that was originally allocated for the handle. If the logical size of the stream is important, follow /// the call to this function with a call to the IStream::SetSize method. /// </para> /// <para>The new stream object’s initial seek position is the beginning of the stream.</para> /// <para> /// After creating the stream object with <c>CreateStreamOnHGlobal</c>, call GetHGlobalFromStream to retrieve the memory handle /// associated with the stream object. /// </para> /// <para> /// If a memory handle is passed to <c>CreateStreamOnHGlobal</c> or if GetHGlobalFromStream is called, the memory handle of this /// function can be directly accessed by the caller while it is still in use by the stream object. Appropriate caution should be /// exercised in the use of this capability and its implications: /// </para> /// <list type="bullet"> /// <item> /// <term> /// Do not free the hGlobal memory handle during the lifetime of the stream object. IStream::Release must be called before freeing /// the memory handle. /// </term> /// </item> /// <item> /// <term> /// Do not call GlobalReAlloc to change the size of the memory handle during the lifetime of the stream object or its clones. This /// may cause application crashes or memory corruption. Avoid creating multiple stream objects separately on the same memory handle, /// because the IStream::Write and IStream::SetSize methods may internally call <c>GlobalReAlloc</c>. The IStream::Clone method can /// be used to create a new stream object based on the same memory handle that will properly coordinate its access with the original /// stream object. /// </term> /// </item> /// <item> /// <term> /// If possible, avoid accessing the memory block during the lifetime of the stream object, because the object may internally call /// GlobalReAlloc and do not make assumptions about its size and location. If the memory block must be accessed, the memory access /// calls should be surrounded by calls to GlobalLock and GlobalUnLock. /// </term> /// </item> /// <item> /// <term> /// Avoid calling the object’s methods while you have the memory handle locked with GlobalLock. This can cause method calls to fail unpredictably. /// </term> /// </item> /// </list> /// <para> /// If the caller sets the fDeleteOnRelease parameter to <c>FALSE</c>, then the caller must also free the hGlobal after the final /// release. If the caller sets the fDeleteOnRelease parameter to <c>TRUE</c>, the final release will automatically free the hGlobal. /// </para> /// <para> /// The memory handle passed as the hGlobal parameter must be allocated as movable and nondiscardable, as shown in the following example: /// </para> /// <para> /// <c>CreateStreamOnHGlobal</c> will accept a memory handle allocated with GMEM_FIXED, but this usage is not recommended. HGLOBALs /// allocated with <c>GMEM_FIXED</c> are not really handles and their value can change when they are reallocated. If the memory /// handle was allocated with <c>GMEM_FIXED</c> and fDeleteOnRelease is <c>FALSE</c>, the caller must call GetHGlobalFromStream to /// get the correct handle in order to free it. /// </para> /// <para> /// Prior to Windows 7 and Windows Server 2008 R2, this implementation did not zero memory when calling GlobalReAlloc to grow the /// memory block. Increasing the size of the stream with IStream::SetSize or by writing to a location past the current end of the /// stream may leave portions of the newly allocated memory uninitialized. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-createstreamonhglobal HRESULT CreateStreamOnHGlobal( // HGLOBAL hGlobal, BOOL fDeleteOnRelease, LPSTREAM *ppstm ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "413c107b-a943-4c02-9c00-aea708e876d7")] public static extern HRESULT CreateStreamOnHGlobal(IntPtr hGlobal, [MarshalAs(UnmanagedType.Bool)] bool fDeleteOnRelease, out IStream ppstm); /// <summary> /// <para>Determines whether the DLL that implements this function is in use. If not, the caller can unload the DLL from memory.</para> /// <para> /// OLE does not provide this function. DLLs that support the OLE Component Object Model (COM) should implement and export <c>DllCanUnloadNow</c>. /// </para> /// </summary> /// <returns>If the function succeeds, the return value is S_OK. Otherwise, it is S_FALSE.</returns> /// <remarks> /// <para> /// A call to <c>DllCanUnloadNow</c> determines whether the DLL from which it is exported is still in use. A DLL is no longer in use /// when it is not managing any existing objects (the reference count on all of its objects is 0). /// </para> /// <para>Notes to Callers</para> /// <para> /// You should not have to call <c>DllCanUnloadNow</c> directly. OLE calls it only through a call to the CoFreeUnusedLibraries /// function. When it returns S_OK, <c>CoFreeUnusedLibraries</c> frees the DLL. /// </para> /// <para>Notes to Implementers</para> /// <para> /// You must implement <c>DllCanUnloadNow</c> in, and export it from, DLLs that are to be dynamically loaded through a call to the /// CoGetClassObject function. (You also need to implement and export the DllGetClassObject function in the same DLL). /// </para> /// <para> /// If a DLL loaded through a call to CoGetClassObject fails to export <c>DllCanUnloadNow</c>, the DLL will not be unloaded until the /// application calls the CoUninitialize function to release the OLE libraries. /// </para> /// <para><c>DllCanUnloadNow</c> should return S_FALSE if there are any existing references to objects that the DLL manages.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-dllcanunloadnow HRESULT DllCanUnloadNow( ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "a47df9eb-97cb-4875-a121-1dabe7bc9db6")] public static extern HRESULT DllCanUnloadNow(); /// <summary> /// <para>Retrieves the class object from a DLL object handler or object application.</para> /// <para> /// OLE does not provide this function. DLLs that support the OLE Component Object Model (COM) must implement /// <c>DllGetClassObject</c> in OLE object handlers or DLL applications. /// </para> /// </summary> /// <param name="rclsid">The CLSID that will associate the correct data and code.</param> /// <param name="riid"> /// A reference to the identifier of the interface that the caller is to use to communicate with the class object. Usually, this is /// IID_IClassFactory (defined in the OLE headers as the interface identifier for IClassFactory). /// </param> /// <param name="ppv"> /// The address of a pointer variable that receives the interface pointer requested in riid. Upon successful return, *ppv contains /// the requested interface pointer. If an error occurs, the interface pointer is <c>NULL</c>. /// </param> /// <returns> /// <para> /// This function can return the standard return values E_INVALIDARG, E_OUTOFMEMORY, and E_UNEXPECTED, as well as the following values. /// </para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The object was retrieved successfully.</term> /// </item> /// <item> /// <term>CLASS_E_CLASSNOTAVAILABLE</term> /// <term>The DLL does not support the class (object definition).</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// If a call to the CoGetClassObject function finds the class object that is to be loaded in a DLL, <c>CoGetClassObject</c> uses the /// DLL's exported <c>DllGetClassObject</c> function. /// </para> /// <para>Notes to Callers</para> /// <para> /// You should not call <c>DllGetClassObject</c> directly. When an object is defined in a DLL, CoGetClassObject calls the /// CoLoadLibrary function to load the DLL, which, in turn, calls <c>DllGetClassObject</c>. /// </para> /// <para>Notes to Implementers</para> /// <para>You need to implement <c>DllGetClassObject</c> in (and export it from) DLLs that support COM.</para> /// <para>Examples</para> /// <para> /// The following is an example (in C++) of an implementation of <c>DllGetClassObject</c>. In this example, <c>DllGetClassObject</c> /// creates a class object and calls its QueryInterface method to retrieve a pointer to the interface requested in riid. The /// implementation releases the reference it holds to the IClassFactory interface because it returns a reference-counted pointer to /// <c>IClassFactory</c> to the caller. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-dllgetclassobject HRESULT DllGetClassObject( // REFCLSID rclsid, REFIID riid, LPVOID *ppv ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "42c08149-c251-47f7-a81f-383975d7081c")] public static extern HRESULT DllGetClassObject(in Guid rclsid, in Guid riid, [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex = 1)] out object ppv); /// <summary> /// The <c>GetHGlobalFromStream</c> function retrieves the global memory handle to a stream that was created through a call to the /// CreateStreamOnHGlobal function. /// </summary> /// <param name="pstm">IStream pointer to the stream object previously created by a call to the CreateStreamOnHGlobal function.</param> /// <param name="phglobal">Pointer to the current memory handle used by the specified stream object.</param> /// <returns>This function returns HRESULT.</returns> /// <remarks> /// <para> /// The handle <c>GetHGlobalFromStream</c> returns may be different from the original handle due to intervening GlobalReAlloc calls. /// </para> /// <para>This function can be called only from within the same process from which the byte array was created.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-gethglobalfromstream HRESULT GetHGlobalFromStream( // LPSTREAM pstm, HGLOBAL *phglobal ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "79e39345-7a20-4b0f-bceb-f62de13d3260")] public static extern HRESULT GetHGlobalFromStream(IStream pstm, out IntPtr phglobal); /// <summary>Retrieves the ProgID for a given CLSID.</summary> /// <param name="clsid">The CLSID for which the ProgID is to be requested.</param> /// <param name="lplpszProgID"> /// The address of a pointer variable that receives the ProgID string. The string that represents clsid includes enclosing braces. /// </param> /// <returns> /// <para>This function can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The ProgID was returned successfully.</term> /// </item> /// <item> /// <term>REGDB_E_CLASSNOTREG</term> /// <term>Class not registered in the registry.</term> /// </item> /// <item> /// <term>REGDB_E_READREGDB</term> /// <term>There was an error reading from the registry.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// Every OLE object class listed in the <c>Insert Object</c> dialog box must have a programmatic identifier (ProgID), a string that /// uniquely identifies a given class, stored in the registry. In addition to determining the eligibility for the <c>Insert /// Object</c> dialog box, the ProgID can be used as an identifier in a macro programming language to identify a class. Finally, the /// ProgID is also the class name used for an object of an OLE class that is placed in an OLE 1 container. /// </para> /// <para> /// <c>ProgIDFromCLSID</c> uses entries in the registry to do the conversion. OLE application authors are responsible for ensuring /// that the registry is configured correctly in the application's setup program. /// </para> /// <para> /// The ProgID string must be different than the class name of any OLE 1 application, including the OLE 1 version of the same /// application, if there is one. In addition, a ProgID string must not contain more than 39 characters, start with a digit, or, /// except for a single period, contain any punctuation (including underscores). /// </para> /// <para> /// The ProgID must never be shown to the user in the user interface. If you need a short displayable string for an object, call IOleObject::GetUserType. /// </para> /// <para> /// Call the CLSIDFromProgID function to find the CLSID associated with a given ProgID. Be sure to free the returned ProgID when you /// are finished with it by calling the CoTaskMemFree function. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-progidfromclsid HRESULT ProgIDFromCLSID( REFCLSID // clsid, LPOLESTR *lplpszProgID ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)] [PInvokeData("combaseapi.h", MSDNShortId = "a863cbc2-f8ab-468a-8254-b273077a6a2b")] public static extern HRESULT ProgIDFromCLSID(in Guid clsid, out SafeCoTaskMemString lplpszProgID); /// <summary>Creates an agile reference for an object specified by the given interface.</summary> /// <param name="options">The options.</param> /// <param name="riid">The interface ID of the object for which an agile reference is being obtained.</param> /// <param name="pUnk"> /// Pointer to the interface to be encapsulated in an agile reference. It must be the same type as riid. It may be a pointer to an /// in-process object or a pointer to a proxy of an object. /// </param> /// <param name="ppAgileReference"> /// The agile reference for the object. Call the Resolve method to localize the object into the apartment in which <c>Resolve</c> is called. /// </param> /// <returns> /// <para>This function can return one of these values.</para> /// <list type="table"> /// <listheader> /// <term>Return value</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term>The function completed successfully.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The options parameter in invalid.</term> /// </item> /// <item> /// <term>E_OUTOFMEMORY</term> /// <term>The agile reference couldn't be constructed due to an out-of-memory condition.</term> /// </item> /// <item> /// <term>E_NOINTERFACE</term> /// <term>The pUnk parameter doesn't support the interface ID specified by the riid parameter.</term> /// </item> /// <item> /// <term>CO_E_NOT_SUPPORTED</term> /// <term>The object implements the INoMarshal interface.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// Call the <c>RoGetAgileReference</c> function on an existing object to request an agile reference to the object. The object may or /// may not be agile, but the returned IAgileReference is agile. The agile reference can be passed to another apartment within the /// same process, where the original object is retrieved by using the <c>IAgileReference</c> interface. /// </para> /// <para> /// This is conceptually similar to the existing Global Interface Table (GIT). Rather than interacting with the GIT, an /// IAgileReference is obtained and used to retrieve the object directly. Just as the GIT is per-process only, agile references are /// per-process and can't be marshaled. /// </para> /// <para> /// The agile reference feature provides a performance improvement over the GIT. The agile reference performs eager marshaling by /// default, which saves a cross-apartment call in cases where the object is retrieved from the agile reference in an apartment /// that's different from where the agile reference was created. For additional performance improvement, users of the /// <c>RoGetAgileReference</c> function can use the same interface to create an IAgileReference and resolve the original object. This /// saves an additional QueryInterface call to obtain the desired interface from the resolved object. /// </para> /// <para> /// For example, you have a non-agile object named CDemoExample, which implements the IDemo and IExample interfaces. Call the /// <c>RoGetAgileReference</c> function and pass the object, with IID_IDemo. You get back an IAgileReference interface pointer, which /// is agile, so you can pass it to a different apartment. In the other apartment, call the Resolve method, with IID_IExample. You /// get back an IExample pointer that you can use within this apartment. This IExample pointer is an IExample proxy that's connected /// to the original CDemoExample object. The agile reference handles the complexity of operations like manually marshaling to a /// stream and unmarshaling on the other side of the apartment boundary. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-rogetagilereference HRESULT RoGetAgileReference( // AgileReferenceOptions options , REFIID riid, IUnknown *pUnk, IAgileReference **ppAgileReference ); [DllImport(Lib.Ole32, SetLastError = false, ExactSpelling = true)] [PInvokeData("combaseapi.h", MSDNShortId = "D16224C7-1BB7-46F5-B66C-54D0B9679006")] public static extern HRESULT RoGetAgileReference(AgileReferenceOptions options, in Guid riid, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnk, out IAgileReference ppAgileReference); } }
57.79094
205
0.715882
[ "MIT" ]
gigi81/Vanara
PInvoke/Ole/Ole32/ComBaseApi.cs
222,000
C#
using System; using System.Runtime.Serialization; using BinanceNETStandard.API.Converter; using BinanceNETStandard.API.Models.Request.Interfaces; using Newtonsoft.Json; namespace BinanceNETStandard.API.Models.Request { /// <summary> /// Request object used to retrieve exchange information /// </summary> [DataContract] public class ExchangeInfo : IRequest { } }
23.117647
60
0.740458
[ "Apache-2.0" ]
Civeloo/BinanceSpotBot
BinanceNETStandard/Models/Request/ExchangeInfo.cs
395
C#
using System.Diagnostics; using System.Xml.Serialization; using Infragistics.Win.UltraWinGrid; namespace KaupischITC.InfragisticsControls.LayoutSerialization { /// <summary> /// Stellt Layout-Informationen über eine Spalten-Zusammenfassung bereit /// </summary> [DebuggerDisplay("{ColumnKey} {SummaryType}")] public class ColumnSummary { /// <summary> /// Gibt den Schlüssel der zugehörigen Spalte zurück oder legt diesen fest /// </summary> [XmlAttribute("columnKey")] public string ColumnKey { get; set; } /// <summary> /// Gibt den Typ der Zusammenfassung zurück oder legt diesen fest /// </summary> [XmlAttribute("type")] public SummaryType SummaryType { get; set; } } }
28.153846
77
0.699454
[ "MIT" ]
Kaupisch-IT/KaupischIT.Shared
KaupischITC.Infragistics/LayoutSerialization/ColumnSummary.cs
739
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.EventGrid.V20190201Preview.Inputs { /// <summary> /// NumberIn Advanced Filter. /// </summary> public sealed class NumberInAdvancedFilterArgs : Pulumi.ResourceArgs { /// <summary> /// The field/property in the event based on which you want to filter. /// </summary> [Input("key")] public Input<string>? Key { get; set; } /// <summary> /// The operator type used for filtering, e.g., NumberIn, StringContains, BoolEquals and others. /// Expected value is 'NumberIn'. /// </summary> [Input("operatorType", required: true)] public Input<string> OperatorType { get; set; } = null!; [Input("values")] private InputList<double>? _values; /// <summary> /// The set of filter values. /// </summary> public InputList<double> Values { get => _values ?? (_values = new InputList<double>()); set => _values = value; } public NumberInAdvancedFilterArgs() { } } }
29.333333
104
0.598722
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/EventGrid/V20190201Preview/Inputs/NumberInAdvancedFilterArgs.cs
1,408
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Memory; namespace LiveSplit.EldenRing.Timer { public interface ITimer { TimeSpan UpdateGameTime(ProcessMemory processMemory); } }
21.692308
62
0.734043
[ "MIT" ]
dwonisch/LiveSplit.EldenRing
LiveSplit.EldenRing/Timer/ITimer.cs
284
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace AccessibilityInsights.SharedUx.Telemetry { /// <summary> /// Container for a telemetry action and its properties /// </summary> public class TelemetryEvent { public TelemetryAction Action { get; } public IReadOnlyDictionary<TelemetryProperty, string> Properties { get; } public TelemetryEvent(TelemetryAction action, IReadOnlyDictionary<TelemetryProperty, string> properties) { this.Action = action; this.Properties = properties; } } }
32.391304
113
0.671141
[ "MIT" ]
Microsoft/accessibility-insights-windows
src/AccessibilityInsights.SharedUx/Telemetry/TelemetryEvent.cs
725
C#
using App.Server.Hubs; using App.Shared.Common; using App.Shared.MessagePackObjects; using Cysharp.Threading.Tasks; using System; using UnityEngine; using UnityEngine.UI; namespace App { /// <summary> /// マッチング /// </summary> public class MatchingLoop : ILoop, IMatchingHubReceiver { /// <summary>接続中テキスト</summary> [SerializeField] private Text connectingText = null; /// <summary>Streaming接続</summary> private HubConnector<IMatchingHub, IMatchingHubReceiver> hubConnector = null; /// <summary>マッチング参加中</summary> private bool isJoin = false; private string CONNECT_TEXT { get { return isJoin ? "MATCHING" : "CONNECTING"; } } /// <summary>Loopパラメータ</summary> private ParamMatchingLoop loopParam = null; /// <summary>戻る操作でタイトル帰れるように</summary> public override bool EnableBack { get { // マッチングが確定するまでは許容 return string.IsNullOrEmpty(roomName); } } /// <summary>部屋名</summary> private string roomName = ""; /// <summary> /// 開始時初期化 /// </summary> /// <returns></returns> public async override UniTask Enter(IBridgeLoopParam param) { loopParam = param as ParamMatchingLoop; await UniTask.Yield(PlayerLoopTiming.Update, this.GetCancellationTokenOnDestroy()); // 接続開始 connectStart().Forget(); } /// <summary> /// 接続開始 /// </summary> /// <returns></returns> private async UniTask connectStart() { while (loopExecuter.IsFading) { // フェード待ち await UniTask.Yield(PlayerLoopTiming.Update, this.GetCancellationTokenOnDestroy()); } // UI表示開始 connectingUI().Forget(); // 接続待ち try { hubConnector = new HubConnector<IMatchingHub, IMatchingHubReceiver>(this, SharedConstant.GRPC_CONNECT_ADDRESS, SharedConstant.GRPC_CONNECT_PORT); await hubConnector.ConnectStartAsync(); // 接続開始 joinOrLeave(); } catch (Exception ex) when (!(ex is OperationCanceledException)) { } } /// <summary> /// 終了時 /// </summary> /// <returns></returns> public async override UniTask Exit(eLoop nextLoop) { // 切断待機 Debug.Log("ExitLoop"); await disposeConnect(); } /// <summary> /// 破棄 /// </summary> async void OnDestroy() { await disposeConnect(); } /// <summary> /// 切断 /// </summary> /// <returns></returns> private async UniTask disposeConnect() { Debug.Log("LobbyLoop Destroy Start"); await hubConnector.DisposeConnectAsync(); Debug.Log("LobbyLoop Destroy Complete"); } /// <summary> /// 接続・切断 /// </summary> private async void joinOrLeave() { if (!isJoin) { // 接続開始 var request = new MatchingJoinRequest { withOther = loopParam.WithOther }; await hubConnector.ServerImpl.JoinAsync(request); isJoin = true; } else { // 切断 await hubConnector.ServerImpl.LeaveAsync(); // UI初期化 isJoin = false; } } /// <summary> /// 接続中 /// </summary> /// <returns></returns> private async UniTaskVoid connectingUI() { int counter = 0; connectingText.text = CONNECT_TEXT; while (!this.GetCancellationTokenOnDestroy().IsCancellationRequested && string.IsNullOrEmpty(roomName)) { connectingText.text += "."; if (counter >= 3) { connectingText.text = CONNECT_TEXT; counter = 0; } else { counter++; } await UniTask.Delay(500, cancellationToken: this.GetCancellationTokenOnDestroy()); } } /// <summary> /// ゲーム本体へ /// </summary> /// <returns></returns> private async UniTaskVoid toMainGameWithNotworking(string mineId, string enemyId, string roomName) { connectingText.text = "Game Start"; await AppLib.LibFunction.FlashUIAsync(connectingText, this.GetCancellationTokenOnDestroy()); loopExecuter.Push(eLoop.MainGameWithNetworking, new ParamMainGameWithNetwork { MineId = mineId, EnemyId = enemyId, RoomName = roomName, WithOther = loopParam.WithOther }); } /// <summary> /// マッチング成功 /// </summary> /// <param name="response"></param> public void OnMatchingSuccess(MatchingRequestSuccessResponse response) { Debug.Log(response.RoomName); roomName = response.RoomName; // ゲームへ移動 toMainGameWithNotworking(response.MineId, response.EnemeyId, roomName).Forget(); } } /// <summary> /// マッチングループ用Param /// </summary> public class ParamMatchingLoop : IBridgeLoopParam { public bool WithOther; } }
28.817708
183
0.525032
[ "MIT" ]
y-tomita/UnityGame
LineDeleteGame/Assets/Scripts/App/Loop/MatchingLoop.cs
5,831
C#
using Recipes.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Recipes.Domain.Contracts { public interface ICommentService : IServiceBase<CommentModel> { } }
18.785714
64
0.775665
[ "MIT" ]
VangelIliev/Recipies
Recipies/Domain.Contracts/ICommentService.cs
265
C#
/* * Copyright 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 events-2015-10-07.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CloudWatchEvents.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CloudWatchEvents.Model.Internal.MarshallTransformations { /// <summary> /// UpdateConnectionOAuthRequestParameters Marshaller /// </summary> public class UpdateConnectionOAuthRequestParametersMarshaller : IRequestMarshaller<UpdateConnectionOAuthRequestParameters, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(UpdateConnectionOAuthRequestParameters requestObject, JsonMarshallerContext context) { if(requestObject.IsSetAuthorizationEndpoint()) { context.Writer.WritePropertyName("AuthorizationEndpoint"); context.Writer.Write(requestObject.AuthorizationEndpoint); } if(requestObject.IsSetClientParameters()) { context.Writer.WritePropertyName("ClientParameters"); context.Writer.WriteObjectStart(); var marshaller = UpdateConnectionOAuthClientRequestParametersMarshaller.Instance; marshaller.Marshall(requestObject.ClientParameters, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetHttpMethod()) { context.Writer.WritePropertyName("HttpMethod"); context.Writer.Write(requestObject.HttpMethod); } if(requestObject.IsSetOAuthHttpParameters()) { context.Writer.WritePropertyName("OAuthHttpParameters"); context.Writer.WriteObjectStart(); var marshaller = ConnectionHttpParametersMarshaller.Instance; marshaller.Marshall(requestObject.OAuthHttpParameters, context); context.Writer.WriteObjectEnd(); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static UpdateConnectionOAuthRequestParametersMarshaller Instance = new UpdateConnectionOAuthRequestParametersMarshaller(); } }
36.377778
150
0.677764
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/CloudWatchEvents/Generated/Model/Internal/MarshallTransformations/UpdateConnectionOAuthRequestParametersMarshaller.cs
3,274
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MinPriorityQueueLesson")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MinPriorityQueueLesson")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cfc11318-439b-4b3b-91ef-553da3d439ca")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.27027
85
0.730213
[ "MIT" ]
mainframebot/csharp-datastructures-priorityqueue
MinPriorityQueueLesson/Properties/AssemblyInfo.cs
1,456
C#
using System; namespace Vertex.Transaction.Exceptions { public class TxSnapshotException : Exception { public TxSnapshotException(string actorId, long snapshotVersion, long backupSnapshotVersion) { this.ActorId = actorId; this.SnapshotVersion = snapshotVersion; this.BackupSnapshotVersion = backupSnapshotVersion; } public string ActorId { get; set; } public long SnapshotVersion { get; set; } public long BackupSnapshotVersion { get; set; } } }
26.047619
100
0.656307
[ "MIT" ]
Cloud33/Vertex
src/Vertex.Transaction/Exceptions/TxSnapshotException.cs
549
C#
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; namespace memamjome.AppveyorVSPackage.Services.Impl { [Export(typeof(memamjome.AppveyorVSPackage.Services.IMessenger))] internal class Messenger : memamjome.AppveyorVSPackage.Services.IMessenger { private GalaSoft.MvvmLight.Messaging.IMessenger _messenger; public Messenger() { _messenger = GalaSoft.MvvmLight.Messaging.Messenger.Default; } public void Subscribe<T>(object recipient, Action<T> action) { _messenger.Register<T>(recipient, action); } public void Send<T>(T message) { _messenger.Send(message); } } }
26.064516
78
0.675743
[ "MIT" ]
misamae/AppveyorVSPackage
AppveyorVSPackage/Services/Impl/Messenger.cs
810
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using OwlCore.Remoting; using OwlCore.Extensions; using System.Collections.Generic; using System.Linq; using OwlCore.Tests.Remoting.Transfer; using OwlCore.Tests.Remoting.Mock; namespace OwlCore.Tests.Remoting { /// <remarks> /// These tests assume that the code running on both machines are identical, which might not always be the case. /// <para/> /// In the scenarios defined above, /// anything defining only OutboundHost/OutboundClient will send but never receive and /// anything defining only InboundHost/InboundClient will receive but never send. /// </remarks> [TestClass] public partial class MemberRemoteTests { private List<MemberRemoteTestClass> CreateMemberRemoteTestClasses(IEnumerable<RemotingMode> nodesModes) { var testClasses = new List<MemberRemoteTestClass>(); var handlers = new List<LoopbackMockMessageHandler>(); foreach (var mode in nodesModes) { var loopbackHandler = new LoopbackMockMessageHandler(mode); handlers.Add(loopbackHandler); testClasses.Add(new MemberRemoteTestClass("TestClass", loopbackHandler)); } foreach (var handler in handlers) handler.LoopbackListeners.AddRange(handlers.Except(handler.IntoList())); return testClasses; } } }
35.292683
116
0.682792
[ "MIT" ]
Arlodotexe/OwlCore
tests/Remoting/MemberRemoteTests.cs
1,449
C#
// <copyright file="HttpHeaderCodecTests.cs" company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> using System; using Xunit; namespace Datadog.Trace.OpenTracing.Tests { public class HttpHeaderCodecTests { // The values are duplicated here to make sure that if they are changed it will break tests private const string HttpHeaderTraceId = "x-datadog-trace-id"; private const string HttpHeaderParentId = "x-datadog-parent-id"; private const string HttpHeaderSamplingPriority = "x-datadog-sampling-priority"; private readonly HttpHeadersCodec _codec = new HttpHeadersCodec(); [Fact] public void Extract_ValidParentAndTraceId_ProperSpanContext() { const ulong traceId = 10; const ulong parentId = 120; var headers = new MockTextMap(); headers.Set(HttpHeaderTraceId, traceId.ToString()); headers.Set(HttpHeaderParentId, parentId.ToString()); var spanContext = _codec.Extract(headers) as OpenTracingSpanContext; Assert.NotNull(spanContext); Assert.Equal(traceId, spanContext.Context.TraceId); Assert.Equal(parentId, spanContext.Context.SpanId); } [Fact] public void Extract_WrongHeaderCase_ExtractionStillWorks() { const ulong traceId = 10; const ulong parentId = 120; const int samplingPriority = SamplingPriorityValues.UserKeep; var headers = new MockTextMap(); headers.Set(HttpHeaderTraceId.ToUpper(), traceId.ToString()); headers.Set(HttpHeaderParentId.ToUpper(), parentId.ToString()); headers.Set(HttpHeaderSamplingPriority.ToUpper(), samplingPriority.ToString()); var spanContext = _codec.Extract(headers) as OpenTracingSpanContext; Assert.NotNull(spanContext); Assert.Equal(traceId, spanContext.Context.TraceId); Assert.Equal(parentId, spanContext.Context.SpanId); } [Fact] public void Inject_SpanContext_HeadersWithCorrectInfo() { const ulong spanId = 10; const ulong traceId = 7; const int samplingPriority = SamplingPriorityValues.UserKeep; var ddSpanContext = new SpanContext(traceId, spanId, (SamplingPriority)samplingPriority); var spanContext = new OpenTracingSpanContext(ddSpanContext); var headers = new MockTextMap(); _codec.Inject(spanContext, headers); Assert.Equal(spanId.ToString(), headers.Get(HttpHeaderParentId)); Assert.Equal(traceId.ToString(), headers.Get(HttpHeaderTraceId)); Assert.Equal(samplingPriority.ToString(), headers.Get(HttpHeaderSamplingPriority)); } } }
40.2
113
0.667993
[ "Apache-2.0" ]
DataDog/dd-trace-csharp
tracer/test/Datadog.Trace.OpenTracing.Tests/HttpHeaderCodecTests.cs
3,015
C#
using System; using Prowlin; using FeuerwehrCloud.Plugin; using Prowlin.Interfaces; using System.IO; using System.Reflection; namespace FeuerwehrCloud.Output { public class Prowl : Plugin.IPlugin { #region IPlugin implementation public event PluginEvent Event; private FeuerwehrCloud.Plugin.IHost My; public string Name { get { return "Prowl"; } } public string FriendlyName { get { return "Prowl"; } } public Guid GUID { get { return new Guid ("A"); } } public byte[] Icon { get { var assembly = typeof(FeuerwehrCloud.Output.Prowl).GetTypeInfo().Assembly; string[] resources = assembly.GetManifestResourceNames(); Stream stream = assembly.GetManifestResourceStream("icon.ico"); return ((MemoryStream)stream).ToArray(); } } public bool IsAsync { get { return true; } } public ServiceType ServiceType { get { return ServiceType.output; } } public void Dispose() { } public void Execute(params object[] list) { INotification notification = new Prowlin.Notification() { Application = "FeuerwehrCloud", Description = (string)list[1], Event = (string)list[0], Priority = NotificationPriority.Emergency, Url = "https://"+System.Environment.MachineName + ".feuerwehrcloud.de:10443/alert.php?alerid="+(string)list[2] }; notification.AddApiKey("6b9ea4e98c84381c2606dd3ec48ea1033a4d127a"); ProwlClient prowlClient = new ProwlClient(); NotificationResult notificationResult = prowlClient.SendNotification(notification); } public bool Initialize(IHost hostApplication) { My = hostApplication; FeuerwehrCloud.Helper.Logger.WriteLine ("| *** Prowl loaded..."); return true; } #endregion public Prowl () { } } }
20.425287
114
0.689364
[ "MIT" ]
bhuebschen/feuerwehrcloud-deiva
FeuerwehrCloud.Output.Prowl/MyClass.cs
1,779
C#
using System; using System.Reflection; using NUnit.Common; using NUnitLite; namespace coding_challenges_csharp { class Program { static void Main(string[] args) { new AutoRun(typeof(Program).GetTypeInfo().Assembly) .Execute(args, new ExtendedTextWrapper(Console.Out), Console.In); } } }
21.705882
82
0.609756
[ "MIT" ]
ashleybarrett/CodingChallenges-CSharp
Program.cs
371
C#
using System; using System.Collections.Generic; using System.Linq; using Uno.Compiler.Backends.UnoDoc.ViewModels; using Uno.Compiler.Backends.UnoDoc.ViewModels.MetaData; namespace Uno.Compiler.Backends.UnoDoc.Rendering { public class TableOfContentsBuilder { private readonly DocumentViewModel _viewModel; private readonly Dictionary<string, HashSet<DocumentViewModel>> _viewModelsByParent; private readonly Dictionary<string, DocumentViewModel> _viewModelsById; public TableOfContentsBuilder(DocumentViewModel viewModel, Dictionary<string, HashSet<DocumentViewModel>> viewModelsByParent, Dictionary<string, DocumentViewModel> viewModelsById) { _viewModel = viewModel; _viewModelsByParent = viewModelsByParent; _viewModelsById = viewModelsById; } public TableOfContentsViewModel Build() { var toc = new TableOfContentsViewModel(GetGroupedChildren("UxProperty", false, IsUxMember), GetGroupedChildren("AttachedUxProperty", true, IsAttachedMember), GetGroupedChildren("UxEvent", false, IsUxMember), GetGroupedChildren("AttachedUxEvent", true, IsAttachedMember), GetGroupedChildren("JsModule", false), GetGroupedChildren("JsEvent", false), GetGroupedChildren("JsProperty", false), GetGroupedChildren("JsMethod", false), GetGroupedChildren("Namespace", false), GetGroupedChildren("UxClass", false, IsUxClass), GetGroupedChildren("Class", false, e => !IsUxClass(e)), GetGroupedChildren("Delegate", false), GetGroupedChildren("Enum", false), GetGroupedChildren("Interface", false), GetGroupedChildren("Struct", false), GetGroupedChildren("Constructor", false), GetGroupedChildren("Property", false, e => !IsUxMember(e) && !IsAttachedMember(e)), GetGroupedChildren("Method", false), GetGroupedChildren("Event", false, e => !IsUxMember(e) && !IsAttachedMember(e)), GetGroupedChildren("Field", false), GetGroupedChildren("Cast", false), GetGroupedChildren("Operator", false), GetGroupedChildren("Literal", false), GetGroupedChildren("SwizzlerType", false)); return toc; } private static bool IsUxClass(DocumentViewModel model) { var dataType = model as DataTypeViewModel; if (dataType == null || (dataType.Comment?.Attributes?.Advanced ?? false)) { return false; } return dataType.UxProperties != null; } private static bool IsUxMember(DocumentViewModel model) { var member = model as MemberViewModel; if (member == null || (member.Comment?.Attributes?.Advanced ?? false)) { return false; } return member.UxProperties != null; } private static bool IsAttachedMember(DocumentViewModel model) { return model is AttachedMemberViewModel; } private List<TableOfContentsEntryGroupViewModel> GetGroupedChildren(string typeId, bool isAttached, Func<DocumentViewModel, bool> filter = null) { var result = GroupByAncestry(GetChildren(typeId, filter), isAttached); return result; } private List<TableOfContentsEntryViewModel> GetChildren(string typeId, Func<DocumentViewModel, bool> filter = null) { var children = _viewModelsByParent.ContainsKey(_viewModel.Id.Id) ? _viewModelsByParent[_viewModel.Id.Id].Where(e => e.Id.Type == typeId) .OrderBy(e => e.Titles.IndexTitle) .ToList() : new List<DocumentViewModel>(); if (filter != null) { children = children.Where(filter).ToList(); } var models = children.Select(e => { var member = e as MemberViewModel; var returns = e as IReturnEnabledViewModel; var parameters = e as IParameterEnabledViewModel; var titles = new IndexTitlesViewModel(e.Titles.IndexTitle, e.Titles.FullyQualifiedIndexTitle); return new TableOfContentsEntryViewModel(e.Id, e.Uri, titles, e.Comment?.ToBasicComment(), returns?.Returns, parameters?.Parameters, member?.Flags, e.DeclaredIn); }).ToList(); return models; } private List<TableOfContentsEntryGroupViewModel> GroupByAncestry(List<TableOfContentsEntryViewModel> entries, bool isAttached) { var dataType = _viewModel as DataTypeViewModel; if (dataType != null) { return GroupByAncestry(dataType.Inheritance, entries, isAttached); } var member = _viewModel as MemberViewModel; if (member != null) { // Find the data type the member is declared in dataType = _viewModelsById[member.Id.ParentId] as DataTypeViewModel; if (dataType == null) { throw new Exception("Parent " + member.Id.ParentId + " for member " + member.Id + " was not a data type, bug?"); } return GroupByAncestry(dataType.Inheritance, entries, isAttached); } // If it was neither a data type or member, it's likely a namespace and we don't group those. return entries.Count == 0 ? new List<TableOfContentsEntryGroupViewModel>() : new List<TableOfContentsEntryGroupViewModel> { new TableOfContentsEntryGroupViewModel(null, entries) }; } private List<TableOfContentsEntryGroupViewModel> GroupByAncestry(InheritanceViewModel inheritance, List<TableOfContentsEntryViewModel> entries, bool isAttached) { // If there is no inheritance, just return an empty group if (inheritance == null) { return entries.Count == 0 ? new List<TableOfContentsEntryGroupViewModel>() : new List<TableOfContentsEntryGroupViewModel> { new TableOfContentsEntryGroupViewModel(null, entries) }; } var rootGroupItems = new List<TableOfContentsEntryViewModel>(); // Build a cache var entriesByDeclaringType = new Dictionary<string, Tuple<DocumentReferenceViewModel, List<TableOfContentsEntryViewModel>>>(); foreach (var entry in entries) { if (isAttached) { if (entry.Parameters == null || entry.Parameters.Count < 1) { throw new ArgumentException($"Found attached member without required amount of parameters: {entry.Id.Id}"); } rootGroupItems.Add(entry); } else { if (entry.DeclaredIn == null) { rootGroupItems.Add(entry); } else { if (!entriesByDeclaringType.ContainsKey(entry.DeclaredIn.Id.Id)) { entriesByDeclaringType.Add(entry.DeclaredIn.Id.Id, new Tuple<DocumentReferenceViewModel, List<TableOfContentsEntryViewModel>>(entry.DeclaredIn, new List<TableOfContentsEntryViewModel>())); } entriesByDeclaringType[entry.DeclaredIn.Id.Id].Item2.Add(entry); } } } var groups = new List<TableOfContentsEntryGroupViewModel>(); BuildTocGroupsFrom(inheritance.Root, entriesByDeclaringType, groups); groups.Reverse(); // Get the closest ancestors first in the list // If we have root items, add them first if (rootGroupItems.Any()) { groups.Insert(0, new TableOfContentsEntryGroupViewModel(null, rootGroupItems)); } return groups; } private void BuildTocGroupsFrom(InheritanceNodeViewModel ancestor, Dictionary<string, Tuple<DocumentReferenceViewModel, List<TableOfContentsEntryViewModel>>> entriesByDeclaringType, List<TableOfContentsEntryGroupViewModel> target) { var key = ancestor.Uri; if (entriesByDeclaringType.ContainsKey(key)) { var entryInfo = entriesByDeclaringType[key]; var group = new TableOfContentsEntryGroupViewModel(entryInfo.Item1, entryInfo.Item2); target.Add(group); } // Add groups from descendants foreach (var child in ancestor.Children) { BuildTocGroupsFrom(child, entriesByDeclaringType, target); } } } }
50.432558
238
0.500784
[ "MIT" ]
Nicero/uno
src/compiler/backend/unodoc/Rendering/TableOfContentsBuilder.cs
10,845
C#
namespace Kenc.ACMELib.Exceptions.API { using System; [Serializable] [ACMEException("urn:ietf:params:acme:error:rejectedidentifier")] public class RejectedIdentifierException : ACMEException { public RejectedIdentifierException(int status, string detail) : base(status, detail) { } } }
24
92
0.684524
[ "MIT" ]
Kencdk/Kenc.ACMELib
src/Libraries/ACMELib/Exceptions/API/RejectedIdentifierException.cs
338
C#
// 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.ComponentModel; using System.Linq.CompilerServices; using System.Linq.Expressions; using System.Memory; using System.Reflection; namespace Reaqtive.Expressions { /// <summary> /// A default implementation of the expression policy. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public class DefaultExpressionPolicy : IExpressionPolicy { /// <summary> /// Default expression policy without any side-effects. /// </summary> public static readonly DefaultExpressionPolicy Instance = new(); private DefaultExpressionPolicy() { } /// <summary> /// Compiled delegate cache for reuse across expressions. /// </summary> public ICache<Expression> InMemoryCache => DefaultExpressionCache.Instance; /// <summary> /// Cache for in-memory storage of expressions. /// </summary> public ICompiledDelegateCache DelegateCache => DefaultCompiledDelegateCache.Instance; /// <summary> /// Constant hoister for optimized sharing in expressions and evaluation. /// </summary> public IConstantHoister ConstantHoister { get; } = System.Linq.CompilerServices.ConstantHoister.Create(useDefaultForNull: false); /// <summary> /// Specifies whether nested lambda expressions should be outlined into /// delegate constants by recursive compilation using the cache. /// </summary> public bool OutlineCompilation => false; /// <summary> /// Gets the reflection provider to use for reducing ExpressionSlim instances /// to Expression instances during deserialization. /// </summary> public IReflectionProvider ReflectionProvider => DefaultReflectionProvider.Instance; /// <summary> /// Gets the expression factory to use for reducing ExpressionSlim instances /// to Expression instances during deserialization. /// </summary> public IExpressionFactory ExpressionFactory => System.Linq.Expressions.ExpressionFactory.Instance; /// <summary> /// Gets the memoizer used to memoize strongly typed lift functions used /// by the expression serializer. /// </summary> public IMemoizer LiftMemoizer { get; } = Memoizer.Create(ConcurrentMemoizationCacheFactory.Unbounded); /// <summary> /// Gets the memoizer used to memoize strongly typed reduce functions used /// by the expression deserializer. /// </summary> public IMemoizer ReduceMemoizer => LiftMemoizer; private sealed class DefaultCompiledDelegateCache : ICompiledDelegateCache { public static readonly DefaultCompiledDelegateCache Instance = new(); private DefaultCompiledDelegateCache() { } public int Count => 0; public Delegate GetOrAdd(LambdaExpression expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } return expression.Compile(); } public void Clear() { } } private sealed class DefaultExpressionCache : ICache<Expression> { public static readonly DefaultExpressionCache Instance = new(); private DefaultExpressionCache() { } public IDiscardable<Expression> Create(Expression value) => new CacheReference(value); private sealed class CacheReference : IDiscardable<Expression> { public CacheReference(Expression expression) { Value = expression; } public Expression Value { get; } public void Dispose() { } } } } }
34.94958
137
0.627074
[ "MIT" ]
Botcoin-com/reaqtor
Reaqtive/Core/Reaqtive.Quotation/Reaqtive/Expressions/DefaultExpressionPolicy.cs
4,161
C#
namespace Telerik.Sitefinity.Frontend.Forms.Mvc.Models.Fields.SectionHeader { /// <summary> /// Implements API for working with form section header elements. /// </summary> public class SectionHeaderModel : FormElementModel, ISectionHeaderModel { /// <inheritDocs /> public string Text { get; set; } /// <inheritDocs /> public bool Hidden { get; set; } /// <inheritDocs /> public override object GetViewModel(object value) { return new SectionHeaderViewModel() { CssClass = this.CssClass, Text = this.Text, Hidden = this.Hidden }; } } }
26
76
0.525199
[ "Apache-2.0" ]
MrJustPeachy/feather-widgets
Telerik.Sitefinity.Frontend.Forms/Mvc/Models/Fields/SectionHeader/SectionHeaderModel.cs
756
C#
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class WizardCreate : ScriptableWizard { public Transform renderFromPosition; public Cubemap cubemap; void OnWizardUpdate() { helpString = "Select transform to render from and cubemap to render into"; isValid = (renderFromPosition != null) && (cubemap != null); } void OnWizardCreate() { // create temporary camera for rendering GameObject go = new GameObject("CubemapCamera"); go.AddComponent<Camera>(); // place it on the object go.transform.position = renderFromPosition.position; // render into cubemap go.GetComponent<Camera>().RenderToCubemap(cubemap); // destroy temporary camera DestroyImmediate(go); } [MenuItem("GameObject/Render into Cubemap")] static void RenderCubemap() { ScriptableWizard.DisplayWizard<WizardCreate>( "Render cubemap", "Render!"); } }
27.210526
82
0.658607
[ "MIT" ]
getker/UnityShaderLibrary
Assets/ShaderBook/10.2/Editor/WizardCreate.cs
1,036
C#
using System.Windows; using System.Windows.Controls; namespace FarsiLibrary.WPF.Controls { public class FXMonthViewItem : ListBoxItem { static FXMonthViewItem() { DefaultStyleKeyProperty.OverrideMetadata(typeof(FXMonthViewItem), new FrameworkPropertyMetadata(typeof(FXMonthViewItem))); } /// <summary> /// Override right-click item selection /// </summary> /// <param name="e"></param> protected override void OnMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e) { } } }
28.142857
134
0.651438
[ "MIT" ]
HEskandari/FarsiLibrary
FarsiLibrary.WPF/Controls/MonthView/FXMonthViewItem.cs
591
C#
// Project: Aguafrommars/TheIdServer // Copyright (c) 2022 @Olivier Lefebvre using System; using System.Collections.Generic; using System.Linq; using Entity = Aguacongas.IdentityServer.Store.Entity; namespace Aguacongas.TheIdServer.BlazorApp.Pages.Client.Components { public partial class ClientSecrets { private IEnumerable<Entity.ClientSecret> Secrets => Collection.Where(s => s.Id == null || (s.Description != null && s.Description.Contains(HandleModificationState.FilterTerm)) || (s.Type != null && s.Type.Contains(HandleModificationState.FilterTerm))); private static void GenerateSecret(Entity.ClientSecret secret) { secret.Value = Guid.NewGuid().ToString(); } } }
36.5
260
0.720548
[ "Apache-2.0" ]
LibertyEngineeringMovement/TheIdServer
src/BlazorApp/Aguacongas.TheIdServer.BlazorApp.Pages.Client/Components/ClientSecrets.razor.cs
732
C#
using System.Collections.Generic; namespace SeaBlog.Roles.Dto { public class GetRoleForEditOutput { public RoleEditDto Role { get; set; } public List<FlatPermissionDto> Permissions { get; set; } public List<string> GrantedPermissionNames { get; set; } } }
22.692308
64
0.674576
[ "MIT" ]
crybigsea/SeaBlog.ABP
aspnet-core/src/SeaBlog.Application/Roles/Dto/GetRoleForEditOutput.cs
297
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.Diagnostics.Runtime.Interop; namespace MS.Dbg { public class DbgExceptionEventFilter : DbgEventFilter // TODO: IEquatable? { public uint ExceptionCode { get; private set; } public string SecondCommand { get; private set; } private const uint STATUS_ACCESS_VIOLATION = 0xC0000005; private const uint STATUS_ASSERTION_FAILURE = 0xC0000420; private const uint STATUS_APPLICATION_HANG = 0xcfffffff; private const uint STATUS_BREAKPOINT = 0x80000003; private const uint STATUS_CPP_EH_EXCEPTION = 0xE06D7363; private const uint STATUS_CLR_EXCEPTION = 0xe0434f4d; private const uint CLRDATA_NOTIFY_EXCEPTION = 0xe0444143; private const uint DBG_CONTROL_BREAK = 0x40010008; private const uint DBG_CONTROL_C = 0x40010005; private const uint STATUS_DATATYPE_MISALIGNMENT = 0x80000002; private const uint DBG_COMMAND_EXCEPTION = 0x40010009; private const uint STATUS_GUARD_PAGE_VIOLATION = 0x80000001; private const uint STATUS_ILLEGAL_INSTRUCTION = 0xC000001D; private const uint STATUS_IN_PAGE_ERROR = 0xC0000006; private const uint STATUS_INTEGER_DIVIDE_BY_ZERO = 0xC0000094; private const uint STATUS_INTEGER_OVERFLOW = 0xC0000095; private const uint STATUS_INVALID_HANDLE = 0xC0000008; private const uint STATUS_INVALID_LOCK_SEQUENCE = 0xC000001E; private const uint STATUS_INVALID_SYSTEM_SERVICE = 0xC000001C; private const uint STATUS_PORT_DISCONNECTED = 0xC0000037; private const uint STATUS_SERVICE_HANG = 0xefffffff; private const uint STATUS_SINGLE_STEP = 0x80000004; private const uint STATUS_STACK_BUFFER_OVERRUN = 0xC0000409; private const uint STATUS_STACK_OVERFLOW = 0xC00000FD; private const uint STATUS_VERIFIER_STOP = 0xC0000421; private const uint STATUS_VCPP_EXCEPTION = 0x406d1388; private const uint STATUS_WAKE_SYSTEM_DEBUGGER = 0x80000007; private const uint STATUS_WX86_BREAKPOINT = 0x4000001F; private const uint STATUS_WX86_SINGLE_STEP = 0x4000001E; // "DKSN": Don't Know Symbolic Name (these constants seem to be hardcoded in // dbgeng's filter table). private const uint _DKSN_RT_ORIGINATE_ERROR = 0x40080201; private const uint _DKSN_RT_TRANSFORM_ERROR = 0x40080202; private static string _GetNameForException( uint exceptionCode ) { switch( exceptionCode ) { case STATUS_ACCESS_VIOLATION: return "av"; case STATUS_ASSERTION_FAILURE: return "asrt"; case STATUS_APPLICATION_HANG: return "aph"; case STATUS_BREAKPOINT: return "bpe"; case STATUS_CPP_EH_EXCEPTION: return "eh"; case STATUS_CLR_EXCEPTION: return "clr"; case CLRDATA_NOTIFY_EXCEPTION: return "clrn"; case DBG_CONTROL_BREAK: return "cce"; case DBG_CONTROL_C: return "cce"; // TODO: duplicate! case STATUS_DATATYPE_MISALIGNMENT: return "dm"; case DBG_COMMAND_EXCEPTION: return "dbce"; case STATUS_GUARD_PAGE_VIOLATION: return "gp"; case STATUS_ILLEGAL_INSTRUCTION: return "ii"; case STATUS_IN_PAGE_ERROR: return "ip"; case STATUS_INTEGER_DIVIDE_BY_ZERO: return "dz"; case STATUS_INTEGER_OVERFLOW: return "iov"; case STATUS_INVALID_HANDLE: return "ch"; case STATUS_INVALID_LOCK_SEQUENCE: return "lsq"; case STATUS_INVALID_SYSTEM_SERVICE: return "isc"; case STATUS_PORT_DISCONNECTED: return "3c"; case STATUS_SERVICE_HANG: return "svh"; case STATUS_SINGLE_STEP: return "sse"; case STATUS_STACK_BUFFER_OVERRUN: return "sbo"; case STATUS_STACK_OVERFLOW: return "sov"; case STATUS_VERIFIER_STOP: return "vs"; case STATUS_VCPP_EXCEPTION: return "vcpp"; case STATUS_WAKE_SYSTEM_DEBUGGER: return "wkd"; case STATUS_WX86_BREAKPOINT: return "wob"; case STATUS_WX86_SINGLE_STEP: return "wos"; case _DKSN_RT_ORIGINATE_ERROR: return "rto"; case _DKSN_RT_TRANSFORM_ERROR: return "rtt"; } return null; } // end _GetNameForException() private static Dictionary< string, uint > sm_nameToExceptionMap = new Dictionary< string, uint >( StringComparer.OrdinalIgnoreCase ) { { "av", STATUS_ACCESS_VIOLATION }, { "asrt", STATUS_ASSERTION_FAILURE }, { "aph", STATUS_APPLICATION_HANG }, { "bpe", STATUS_BREAKPOINT }, { "eh", STATUS_CPP_EH_EXCEPTION }, { "clr", STATUS_CLR_EXCEPTION }, { "clrn", CLRDATA_NOTIFY_EXCEPTION }, // "cce" is used for both DBG_CONTROL_BREAK and DBG_CONTROL_C... { "cce", DBG_CONTROL_BREAK }, //{ "cce", DBG_CONTROL_C }, { "dm", STATUS_DATATYPE_MISALIGNMENT }, { "dbce", DBG_COMMAND_EXCEPTION }, { "gp", STATUS_GUARD_PAGE_VIOLATION }, { "ii", STATUS_ILLEGAL_INSTRUCTION }, { "ip", STATUS_IN_PAGE_ERROR }, { "dz", STATUS_INTEGER_DIVIDE_BY_ZERO }, { "iov", STATUS_INTEGER_OVERFLOW }, { "ch", STATUS_INVALID_HANDLE }, { "lsq", STATUS_INVALID_LOCK_SEQUENCE }, { "isc", STATUS_INVALID_SYSTEM_SERVICE }, { "3c", STATUS_PORT_DISCONNECTED }, { "svh", STATUS_SERVICE_HANG }, { "sse", STATUS_SINGLE_STEP }, { "sbo", STATUS_STACK_BUFFER_OVERRUN }, { "sov", STATUS_STACK_OVERFLOW }, { "vs", STATUS_VERIFIER_STOP }, { "vcpp", STATUS_VCPP_EXCEPTION }, { "wkd", STATUS_WAKE_SYSTEM_DEBUGGER }, { "wob", STATUS_WX86_BREAKPOINT }, { "wos", STATUS_WX86_SINGLE_STEP }, { "rto", _DKSN_RT_ORIGINATE_ERROR }, { "rtt", _DKSN_RT_TRANSFORM_ERROR }, }; // TODO: or should this be internal public DbgExceptionEventFilter( uint exceptionCode, string friendlyName, DEBUG_FILTER_EXEC_OPTION executionOption, DEBUG_FILTER_CONTINUE_OPTION continueOption, string command, string secondCommand ) : this( exceptionCode, friendlyName, executionOption, continueOption, command, secondCommand, _GetNameForException( exceptionCode ) ) { } internal DbgExceptionEventFilter( uint exceptionCode, string friendlyName, DEBUG_FILTER_EXEC_OPTION executionOption, DEBUG_FILTER_CONTINUE_OPTION continueOption, string command, string secondCommand, string name ) : base( friendlyName, executionOption, continueOption, command, name ) { ExceptionCode = exceptionCode; SecondCommand = secondCommand ?? String.Empty; } // end constructor public override string ToString() { StringBuilder sb = new StringBuilder(); if( String.IsNullOrEmpty( FriendlyName ) ) sb.Append( "(custom)" ); else sb.Append( FriendlyName ); sb.AppendFormat( " ({0:x8}), {1} / {2}", ExceptionCode, ExecutionOption, ContinueOption ); if( !String.IsNullOrEmpty( Command ) ) { sb.Append( ", 1st-chance cmd: \"" ); sb.Append( Command ); sb.Append( "\"" ); } if( !string.IsNullOrEmpty( SecondCommand ) ) { sb.Append( ", 2nd-chance cmd: \"" ); sb.Append( SecondCommand ); sb.Append( "\"" ); } return sb.ToString(); } // end ToString() } // end class DbgExceptionEventFilter }
44.174312
103
0.52378
[ "MIT" ]
jazzdelightsme/tmp_DbgShell2
DbgProvider/public/Debugger/DbgExceptionEventFilter.cs
9,632
C#
using System.IO; namespace TeleSharp.TL { [TLObject(548253432)] public class TLInputPeerChannel : TLAbsInputPeer { public override int Constructor { get { return 548253432; } } public int ChannelId { get; set; } public long AccessHash { get; set; } public void ComputeFlags() { } public override void DeserializeBody(BinaryReader br) { ChannelId = br.ReadInt32(); AccessHash = br.ReadInt64(); } public override void SerializeBody(BinaryWriter bw) { bw.Write(Constructor); bw.Write(ChannelId); bw.Write(AccessHash); } } }
19.225
61
0.513654
[ "MIT" ]
cobra91/TelegramCSharpForward
TeleSharp.TL/TL/TLInputPeerChannel.cs
769
C#
using System; using System.IO; namespace Calamari.Common.Features.ConfigurationTransforms { public class XmlConfigTransformDefinition { readonly string definition; public XmlConfigTransformDefinition(string definition) { this.definition = definition; if (definition.Contains("=>")) { Advanced = true; var separators = new[] {"=>"}; var parts = definition.Split(separators, StringSplitOptions.RemoveEmptyEntries); TransformPattern = parts[0].Trim(); SourcePattern = parts[1].Trim(); if (Path.GetFileName(TransformPattern).StartsWith("*.")) { IsTransformWildcard = true; TransformPattern = TrimWildcardPattern(TransformPattern); } if (Path.GetFileName(SourcePattern).StartsWith("*.")) { IsSourceWildcard = true; SourcePattern = TrimWildcardPattern(SourcePattern); } } else { TransformPattern = definition; } } static string TrimWildcardPattern(string pattern) { var wildcardIndex = pattern.IndexOf('*'); return (pattern.LastIndexOf('.') > wildcardIndex + 1) ? pattern.Remove(wildcardIndex, 2) : pattern.Remove(wildcardIndex, 1); } public string TransformPattern { get; private set; } public string? SourcePattern { get; private set; } public bool IsTransformWildcard { get; private set; } public bool IsSourceWildcard { get; private set; } public bool Advanced { get; private set; } public override string ToString() { return definition; } } }
32.844828
96
0.542782
[ "Apache-2.0" ]
OctopusDeploy/Calamari
source/Calamari.Common/Features/ConfigurationTransforms/XmlConfigTransformDefinition.cs
1,907
C#
namespace BotBase.Exceptions { public class CommandNotSupportedException : BotException { public override string Message => "this command does not exist"; } }
22.5
72
0.705556
[ "MIT" ]
Topinambur223606/BotBase
BotBase/Exceptions/CommandNotSupportedException.cs
182
C#
using System.Threading.Tasks; using ConfigureAwaitChecker.Lib; using ConfigureAwaitChecker.Tests; [CheckerTests.ExpectedResult(CheckerProblem.MissingConfigureAwaitFalse)] [CodeFixTests.TestThis] public class AwaitForEach_Missing { public async Task FooBar() { await foreach (var item in TestsBase.AsyncEnumerable()) { } } }
22.2
72
0.804805
[ "MIT" ]
cincuranet/ConfigureAwaitChecker
ConfigureAwaitChecker.Tests/TestClasses/AwaitForeach_Missing.cs
335
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Iotvideoindustry.V20201201.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeChannelsByLiveRecordPlanResponse : AbstractModel { /// <summary> /// 总个数 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("TotalCount")] public long? TotalCount{ get; set; } /// <summary> /// 通道详情数组 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("LiveChannels")] public LiveChannelItem[] LiveChannels{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount); this.SetParamArrayObj(map, prefix + "LiveChannels.", this.LiveChannels); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
31.783333
84
0.635553
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Iotvideoindustry/V20201201/Models/DescribeChannelsByLiveRecordPlanResponse.cs
2,063
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("XamBindingSample.Resource", IsApplication=true)] namespace XamBindingSample { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { // aapt resource value: 0x7f010000 public const int layoutManager = 2130771968; // aapt resource value: 0x7f010002 public const int reverseLayout = 2130771970; // aapt resource value: 0x7f010001 public const int spanCount = 2130771969; // aapt resource value: 0x7f010003 public const int stackFromEnd = 2130771971; static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Dimension { // aapt resource value: 0x7f040000 public const int item_touch_helper_max_drag_scroll_per_frame = 2130968576; static Dimension() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Dimension() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int Icon = 2130837504; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { // aapt resource value: 0x7f050021 public const int AddButton = 2131034145; // aapt resource value: 0x7f050023 public const int BindingsButton = 2131034147; // aapt resource value: 0x7f05001e public const int ButtonsPanel = 2131034142; // aapt resource value: 0x7f050024 public const int CommandsButton = 2131034148; // aapt resource value: 0x7f050016 public const int CustomEventEditText = 2131034134; // aapt resource value: 0x7f050018 public const int DynamicParameterButton = 2131034136; // aapt resource value: 0x7f05001a public const int ItemCheck = 2131034138; // aapt resource value: 0x7f05001b public const int ItemText = 2131034139; // aapt resource value: 0x7f050019 public const int LayoutRoot = 2131034137; // aapt resource value: 0x7f050025 public const int ListsButton = 2131034149; // aapt resource value: 0x7f050001 public const int MyButtonA1 = 2131034113; // aapt resource value: 0x7f050012 public const int MyButtonJ1 = 2131034130; // aapt resource value: 0x7f050014 public const int MyCheckBox = 2131034132; // aapt resource value: 0x7f050002 public const int MyCheckBoxA1 = 2131034114; // aapt resource value: 0x7f050005 public const int MyCheckBoxC1 = 2131034117; // aapt resource value: 0x7f050006 public const int MyCheckBoxC2 = 2131034118; // aapt resource value: 0x7f05000b public const int MyCheckBoxF1 = 2131034123; // aapt resource value: 0x7f05000d public const int MyCheckBoxG1 = 2131034125; // aapt resource value: 0x7f05000f public const int MyCheckBoxH1 = 2131034127; // aapt resource value: 0x7f050017 public const int MyEditText = 2131034135; // aapt resource value: 0x7f050003 public const int MyEditTextB1 = 2131034115; // aapt resource value: 0x7f050007 public const int MyEditTextD1 = 2131034119; // aapt resource value: 0x7f050009 public const int MyEditTextE1 = 2131034121; // aapt resource value: 0x7f05000c public const int MyEditTextF1 = 2131034124; // aapt resource value: 0x7f05000e public const int MyEditTextG1 = 2131034126; // aapt resource value: 0x7f05001c public const int MyRecycler = 2131034140; // aapt resource value: 0x7f050004 public const int MyTextViewB1 = 2131034116; // aapt resource value: 0x7f050008 public const int MyTextViewD1 = 2131034120; // aapt resource value: 0x7f05000a public const int MyTextViewE1 = 2131034122; // aapt resource value: 0x7f050010 public const int MyTextViewH1 = 2131034128; // aapt resource value: 0x7f050011 public const int MyTextViewJ1 = 2131034129; // aapt resource value: 0x7f050022 public const int RemoveButton = 2131034146; // aapt resource value: 0x7f05001d public const int SelectedItemNamePanel = 2131034141; // aapt resource value: 0x7f05001f public const int SelectedItemNameText = 2131034143; // aapt resource value: 0x7f050013 public const int SimpleCommandButton = 2131034131; // aapt resource value: 0x7f050015 public const int StaticParameterButton = 2131034133; // aapt resource value: 0x7f050020 public const int ToggledItemsText = 2131034144; // aapt resource value: 0x7f050000 public const int item_touch_helper_previous_elevation = 2131034112; static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int Bindings = 2130903040; // aapt resource value: 0x7f030001 public const int Commands = 2130903041; // aapt resource value: 0x7f030002 public const int ItemTemplate = 2130903042; // aapt resource value: 0x7f030003 public const int Lists = 2130903043; // aapt resource value: 0x7f030004 public const int Main = 2130903044; static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } public partial class String { // aapt resource value: 0x7f060001 public const int ApplicationName = 2131099649; // aapt resource value: 0x7f060000 public const int Hello = 2131099648; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } public partial class Style { // aapt resource value: 0x7f070001 public const int BindingTextStyle = 2131165185; // aapt resource value: 0x7f070003 public const int ButtonStyle = 2131165187; // aapt resource value: 0x7f070007 public const int CheckBoxStyle = 2131165191; // aapt resource value: 0x7f070008 public const int EditTextStyle = 2131165192; // aapt resource value: 0x7f070000 public const int LabelStyle = 2131165184; // aapt resource value: 0x7f070005 public const int SeparatorStyle = 2131165189; // aapt resource value: 0x7f070002 public const int SmallBindingTextStyle = 2131165186; // aapt resource value: 0x7f070004 public const int SmallButtonStyle = 2131165188; // aapt resource value: 0x7f070006 public const int SubSeparatorStyle = 2131165190; static Style() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Style() { } } public partial class Styleable { public static int[] RecyclerView = new int[] { 16842948, 2130771968, 2130771969, 2130771970, 2130771971}; // aapt resource value: 0 public const int RecyclerView_android_orientation = 0; // aapt resource value: 1 public const int RecyclerView_layoutManager = 1; // aapt resource value: 3 public const int RecyclerView_reverseLayout = 3; // aapt resource value: 2 public const int RecyclerView_spanCount = 2; // aapt resource value: 4 public const int RecyclerView_stackFromEnd = 4; static Styleable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Styleable() { } } } } #pragma warning restore 1591
25.330383
111
0.648306
[ "MIT" ]
lbugnion/sample-2018-ndcsydney
Mvvm/XamBindingSample/XamBindingSample/XamBindingSample.Droid/Resources/Resource.Designer.cs
8,587
C#
 using YourBrand.ApiKeys.Application.Commands; using MediatR; namespace YourBrand.ApiKeys.Application; public static class ServiceExtensions { public static IServiceCollection AddApplication(this IServiceCollection services, IConfiguration configuration) { services.AddMediatR(typeof(CheckApiKeyCommand)); return services; } }
23.375
116
0.745989
[ "MIT" ]
marinasundstrom/YourBrand
ApiKeys/ApiKeys/Application/ServiceExtensions.cs
376
C#
using System; using SDRSharp.Radio; namespace SDRSharp.DNR { public unsafe class NoiseFilter : FftProcessor { private const int WindowSize = 32; private float _noiseThreshold; private readonly UnsafeBuffer _gainBuffer; private readonly float* _gainPtr; private readonly UnsafeBuffer _smoothedGainBuffer; private readonly float* _smoothedGainPtr; private readonly UnsafeBuffer _powerBuffer; private readonly float* _powerPtr; public NoiseFilter(int fftSize) : base(fftSize) { _gainBuffer = UnsafeBuffer.Create(fftSize, sizeof(float)); _gainPtr = (float*) _gainBuffer; _smoothedGainBuffer = UnsafeBuffer.Create(fftSize, sizeof(float)); _smoothedGainPtr = (float*) _smoothedGainBuffer; _powerBuffer = UnsafeBuffer.Create(fftSize, sizeof(float)); _powerPtr = (float*) _powerBuffer; } public float NoiseThreshold { get { return _noiseThreshold; } set { _noiseThreshold = value; } } protected override void ProcessFft(Complex* buffer, int length) { Fourier.SpectrumPower(buffer, _powerPtr, length); for (var i = 0; i < length; i++) { _gainPtr[i] = _powerPtr[i] > _noiseThreshold ? 1.0f : 0.0f; } for (var i = 0; i < length; i++) { var sum = 0.0f; for (var j = -WindowSize / 2; j < WindowSize / 2; j++) { var index = i + j; if (index >= length) { index -= length; } if (index < 0) { index += length; } sum += _gainPtr[index]; } var gain = sum / WindowSize; _smoothedGainPtr[i] = gain; } for (var i = 0; i < length; i++) { buffer[i] *= _smoothedGainPtr[i]; } } } }
27.469136
78
0.478652
[ "MIT" ]
lukeattard/SDRSharpNG
DNR/NoiseFilter.cs
2,227
C#
using System; using System.Collections.Generic; using System.Text; using EDziekanat.Core.Departments; using EDziekanat.Core.Messages; using EDziekanat.Core.Users; namespace EDziekanat.Core.DeansOffices { public class DeansOffice : BaseEntity { public string Name { get; set; } public string Description { get; set; } public Guid DepartmentId { get; set; } public virtual Department Department { get; set; } public virtual ICollection<User> Users { get; set; } public virtual ICollection<Operation> Operations { get; set; } public virtual ICollection<Reservation> Reservations { get; set; } public virtual ICollection<Message> Messages { get; set; } } }
31.826087
74
0.692623
[ "MIT" ]
jendruss/EDziekanatAPI
src/EDziekanat.Core/DeansOffices/DeansOffice.cs
734
C#
// ======================================== // Project Name : WodiLib // File Name : ChoiceStartForkingRightKey.cs // // MIT License Copyright(c) 2019 kameske // see LICENSE file // ======================================== using System; using System.ComponentModel; using WodiLib.Project; namespace WodiLib.Event.EventCommand { /// <inheritdoc /> /// <summary> /// イベントコマンド・右キー分岐 /// </summary> [Serializable] public class ChoiceStartForkingRightKey : ChoiceStartForkingSpecialBase { // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // Private Constant // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ private const string EventCommandSentenceFormat = "-◇右キーの場合"; // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // OverrideMethod // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ /// <inheritdoc /> public override EventCommandCode EventCommandCode => EventCommandCode.ChoiceStartForkingEtc; /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] protected override string MakeEventCommandMainSentence( EventCommandSentenceResolver resolver, EventCommandSentenceType type, EventCommandSentenceResolveDesc? desc) { return EventCommandSentenceFormat; } // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ // Property // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ /// <inheritdoc /> protected override byte ChoiceCode => EventCommandConstant.ChoiceStartForkingEtc.ChoiceCode.RightKey; } }
34.862745
110
0.559055
[ "MIT" ]
kameske/WodiLib
WodiLib/WodiLib/Event/EventCommand/Implement/ChoiceStartForkingRightKey.cs
1,820
C#
using Bonsai; using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Text; using OpenCV.Net; using NationalInstruments.DAQmx; using System.Runtime.InteropServices; using System.Reactive.Disposables; using System.Collections.ObjectModel; using System.ComponentModel; namespace Bonsai.DAQmx { [Description("Writes a sequence of logical values to one or more DAQmx digital output channels.")] public class DigitalOutput : Sink<bool> { readonly Collection<DigitalOutputChannelConfiguration> channels = new Collection<DigitalOutputChannelConfiguration>(); [Description("The collection of digital output channels used to generate digital signals.")] public Collection<DigitalOutputChannelConfiguration> Channels { get { return channels; } } public override IObservable<bool> Process(IObservable<bool> source) { return Observable.Defer(() => { var task = new Task(); foreach (var channel in channels) { task.DOChannels.CreateChannel(channel.Lines, channel.ChannelName, channel.Grouping); } task.Control(TaskAction.Verify); var digitalInReader = new DigitalMultiChannelWriter(task.Stream); return Observable.Using( () => Disposable.Create(() => { task.WaitUntilDone(); task.Stop(); task.Dispose(); }), resource => source.Do(input => { digitalInReader.WriteSingleSampleSingleLine(true, new[] { input }); })); }); } } }
35.12963
127
0.566157
[ "MIT" ]
bonsai-rx/daqmx
Bonsai.DAQmx/DigitalOutput.cs
1,899
C#
using System; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Text.RegularExpressions; using Discord.WebSocket; namespace SharpBot.Utility { public static class TimeUtil { /// <summary> /// Date format used to convert time to a human-readable detailed form. /// </summary> private const string DATE_FORMAT_NICE = "dddd, dd MMMM yyyy HH:mm:ss"; /// <summary> /// Date format used to convert time to a human-readable less detailed form. /// </summary> private const string DATE_FORMAT_SMALLER = "ddd, dd MMM yyy HH:mm:ss"; /// <summary> /// Date format used to convert time to a human-readable compact form. /// </summary> private const string DATE_FORMAT_COMPACT = "MM/dd/yyyy HH:mm:ss"; /// <summary> /// Converts the <para>millis</para> to a human-readable time lapse. /// </summary> /// <param name="millis">The time in millis to convert.</param> public static string Convert(long millis) { var span = TimeSpan.FromMilliseconds(millis); var parts = $"{span.Days:D2}d:{span.Hours:D2}h:{span.Minutes:D2}m:{span.Seconds:D2}s:{span.Milliseconds:D3}ms" .Split(':') .SkipWhile(s => Regex.Match(s, @"^00\w").Success) // skip zero-valued components .ToArray(); return string.Join(" ", parts); } public static string NowCompact() { return DateTime.Now.ToString(DATE_FORMAT_COMPACT); } public static string NowDetailed() { return DateTime.Now.ToString(DATE_FORMAT_NICE); } public static string NowSmall() { return DateTime.Now.ToString(DATE_FORMAT_SMALLER); } public static string WhenCompact(long millis) { return DateTimeOffset.FromUnixTimeMilliseconds(millis).ToString(DATE_FORMAT_COMPACT); } public static string WhenDetailed(long millis) { return DateTimeOffset.FromUnixTimeMilliseconds(millis).ToString(DATE_FORMAT_NICE); } public static string WhenSmall(long millis) { return DateTimeOffset.FromUnixTimeMilliseconds(millis).ToString(DATE_FORMAT_SMALLER); } } }
38.064516
122
0.613559
[ "MIT" ]
arrayofc/SharpBot
SharpBot/Utility/TimeUtil.cs
2,362
C#
using Microsoft.Win32; using MonoMod.Utils; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace MonoMod.Installer { public class SteamFinder : GameFinder { // "" -> " public readonly static Regex BaseInstallFolderRegex = new Regex(@"BaseInstallFolder[^""]*""\s*""([^""]*)""", RegexOptions.Compiled); public override string ID => "steam"; public string SteamDir { get { if ((PlatformHelper.Current & Platform.Windows) == Platform.Windows) { string regKey = (PlatformHelper.Current & Platform.X64) == Platform.X64 ? @"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Valve\Steam" : @"HKEY_LOCAL_MACHINE\SOFTWARE\Valve\Steam"; // Win32 is case-insensitive. return (string) Registry.GetValue(regKey, "InstallPath", null); } if ((PlatformHelper.Current & Platform.MacOS) == Platform.MacOS) { return Path.Combine(Environment.GetEnvironmentVariable("HOME"), "Library/Application Support/Steam"); } if ((PlatformHelper.Current & Platform.Linux) == Platform.Linux) { return Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".local/share/Steam"); } return null; } } public List<string> LibraryDirs { get { List<string> dirs = new List<string>(); string steam = SteamDir; if (steam == null || !Directory.Exists(steam)) return dirs; string steamapps = Path.Combine(steam, "SteamApps"); if (!Directory.Exists(steamapps)) // Unix is case-sensitive. steamapps = Path.Combine(steam, "steamapps"); if (Directory.Exists(steamapps)) { steamapps = Path.Combine(steamapps, "common"); if (Directory.Exists(steamapps)) dirs.Add(steamapps); } string config = Path.Combine(steam, "config"); config = Path.Combine(config, "config.vdf"); if (!File.Exists(config)) return dirs; using (StreamReader reader = new StreamReader(config)) while (!reader.EndOfStream) { string path = reader.ReadLine().Trim(); Match match = BaseInstallFolderRegex.Match(path); if (!match.Success) continue; path = Regex.Unescape(match.Groups[1].Value); dirs.Add(GetSteamAppsCommon(path) ?? path); } return dirs; } } public override string FindGameDir(string gameid) { List<string> dirs = LibraryDirs; for (int i = 0; i < dirs.Count; i++) { string path = Path.Combine(dirs[i], gameid); if (Directory.Exists(path)) return path; } return null; } public static string GetSteamAppsCommon(string path) { string dir = Path.Combine(path, "SteamApps"); if (!Directory.Exists(dir)) // Unix is case-sensitive. dir = Path.Combine(path, "steamapps"); if (!Directory.Exists(dir)) return null; dir = Path.Combine(dir, "common"); if (!Directory.Exists(dir)) return null; return dir; } } }
37.126214
140
0.507061
[ "MIT" ]
EverestAPI/Everest.Installer
src/Finders/SteamFinder.cs
3,826
C#
namespace Cryptofolio.Infrastructure.Entities { /// <summary> /// Models a transaction of type "Buy" or "Sell". /// </summary> public class BuyOrSellTransaction : Transaction { /// <summary> /// Defines the transaction type: /// - Buy /// - Sell /// </summary> public string Type { get; set; } /// <summary> /// The currency it was bought with/sold for. /// </summary> public Currency Currency { get; set; } /// <summary> /// The price per asset in the currency. /// </summary> public decimal Price { get; set; } } }
25.192308
53
0.520611
[ "MIT" ]
fperronnet/cryptofolio
src/Cryptofolio.Infrastructure/Entities/BuyOrSellTransaction.cs
655
C#
/* * Copyright(c) 2018 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.ComponentModel; using System.Runtime.InteropServices; using Tizen.NUI.BaseComponents; using Tizen.NUI.Binding; namespace Tizen.NUI { /// <summary> /// ScrollView contains views that can be scrolled manually (via touch). /// </summary> /// <since_tizen> 3 </since_tizen> public class ScrollView : Scrollable { /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty WrapEnabledProperty = BindableProperty.Create("WrapEnabled", typeof(bool), typeof(ScrollView), false, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.WRAP_ENABLED, new Tizen.NUI.PropertyValue((bool)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; bool temp = false; Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.WRAP_ENABLED).Get(out temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PanningEnabledProperty = BindableProperty.Create("PanningEnabled", typeof(bool), typeof(ScrollView), false, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.PANNING_ENABLED, new Tizen.NUI.PropertyValue((bool)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; bool temp = false; Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.PANNING_ENABLED).Get(out temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty AxisAutoLockEnabledProperty = BindableProperty.Create("AxisAutoLockEnabled", typeof(bool), typeof(ScrollView), false, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.AXIS_AUTO_LOCK_ENABLED, new Tizen.NUI.PropertyValue((bool)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; bool temp = false; Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.AXIS_AUTO_LOCK_ENABLED).Get(out temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty WheelScrollDistanceStepProperty = BindableProperty.Create("WheelScrollDistanceStep", typeof(Vector2), typeof(ScrollView), Vector2.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.WHEEL_SCROLL_DISTANCE_STEP, new Tizen.NUI.PropertyValue((Vector2)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector2 temp = new Vector2(0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.WHEEL_SCROLL_DISTANCE_STEP).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollPositionProperty = BindableProperty.Create("ScrollPosition", typeof(Vector2), typeof(ScrollView), Vector2.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_POSITION, new Tizen.NUI.PropertyValue((Vector2)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector2 temp = new Vector2(0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_POSITION).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollPrePositionProperty = BindableProperty.Create("ScrollPrePosition", typeof(Vector2), typeof(ScrollView), Vector2.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_PRE_POSITION, new Tizen.NUI.PropertyValue((Vector2)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector2 temp = new Vector2(0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_PRE_POSITION).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollPrePositionMaxProperty = BindableProperty.Create("ScrollPrePositionMax", typeof(Vector2), typeof(ScrollView), Vector2.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_PRE_POSITION_MAX, new Tizen.NUI.PropertyValue((Vector2)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector2 temp = new Vector2(0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_PRE_POSITION_MAX).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty OvershootXProperty = BindableProperty.Create("OvershootX", typeof(float), typeof(ScrollView), default(float), propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.OVERSHOOT_X, new Tizen.NUI.PropertyValue((float)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; float temp = 0.0f; Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.OVERSHOOT_X).Get(out temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty OvershootYProperty = BindableProperty.Create("OvershootY", typeof(float), typeof(ScrollView), default(float), propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.OVERSHOOT_Y, new Tizen.NUI.PropertyValue((float)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; float temp = 0.0f; Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.OVERSHOOT_Y).Get(out temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollFinalProperty = BindableProperty.Create("ScrollFinal", typeof(Vector2), typeof(ScrollView), Vector2.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_FINAL, new Tizen.NUI.PropertyValue((Vector2)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector2 temp = new Vector2(0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_FINAL).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty WrapProperty = BindableProperty.Create("Wrap", typeof(bool), typeof(ScrollView), false, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.WRAP, new Tizen.NUI.PropertyValue((bool)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; bool temp = false; Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.WRAP).Get(out temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty PanningProperty = BindableProperty.Create("Panning", typeof(bool), typeof(ScrollView), false, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.PANNING, new Tizen.NUI.PropertyValue((bool)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; bool temp = false; Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.PANNING).Get(out temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollingProperty = BindableProperty.Create("Scrolling", typeof(bool), typeof(ScrollView), false, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLLING, new Tizen.NUI.PropertyValue((bool)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; bool temp = false; Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLLING).Get(out temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollDomainSizeProperty = BindableProperty.Create("ScrollDomainSize", typeof(Vector2), typeof(ScrollView), Vector2.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_DOMAIN_SIZE, new Tizen.NUI.PropertyValue((Vector2)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector2 temp = new Vector2(0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_DOMAIN_SIZE).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollDomainOffsetProperty = BindableProperty.Create("ScrollDomainOffset", typeof(Vector2), typeof(ScrollView), Vector2.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_DOMAIN_OFFSET, new Tizen.NUI.PropertyValue((Vector2)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector2 temp = new Vector2(0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_DOMAIN_OFFSET).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollPositionDeltaProperty = BindableProperty.Create("ScrollPositionDelta", typeof(Vector2), typeof(ScrollView), Vector2.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_POSITION_DELTA, new Tizen.NUI.PropertyValue((Vector2)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector2 temp = new Vector2(0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_POSITION_DELTA).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty StartPagePositionProperty = BindableProperty.Create("StartPagePosition", typeof(Vector3), typeof(ScrollView), Vector3.Zero, propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.START_PAGE_POSITION, new Tizen.NUI.PropertyValue((Vector3)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; Vector3 temp = new Vector3(0.0f, 0.0f, 0.0f); Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.START_PAGE_POSITION).Get(temp); return temp; }); /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static readonly BindableProperty ScrollModeProperty = BindableProperty.Create("ScrollMode", typeof(PropertyMap), typeof(ScrollView), new PropertyMap(), propertyChanged: (bindable, oldValue, newValue) => { var scrollView = (ScrollView)bindable; if (newValue != null) { Tizen.NUI.Object.SetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_MODE, new Tizen.NUI.PropertyValue((PropertyMap)newValue)); } }, defaultValueCreator: (bindable) => { var scrollView = (ScrollView)bindable; PropertyValue value = Tizen.NUI.Object.GetProperty(scrollView.swigCPtr, ScrollView.Property.SCROLL_MODE); PropertyMap map = new PropertyMap(); value.Get(map); return map; }); private global::System.Runtime.InteropServices.HandleRef swigCPtr; private DaliEventHandler<object, SnapStartedEventArgs> _scrollViewSnapStartedEventHandler; private SnapStartedCallbackDelegate _scrollViewSnapStartedCallbackDelegate; /// <summary> /// Create an instance of ScrollView. /// </summary> /// <since_tizen> 3 </since_tizen> public ScrollView() : this(Interop.ScrollView.ScrollView_New(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal ScrollView(global::System.IntPtr cPtr, bool cMemoryOwn) : base(Interop.ScrollView.ScrollView_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void SnapStartedCallbackDelegate(IntPtr data); /// <summary> /// SnapStarted can be used to subscribe or unsubscribe the event handler /// The SnapStarted signal is emitted when the ScrollView has started to snap or flick (it tells the target /// position, scale, rotation for the snap or flick). /// </summary> /// <since_tizen> 3 </since_tizen> public event DaliEventHandler<object, SnapStartedEventArgs> SnapStarted { add { lock (this) { // Restricted to only one listener if (_scrollViewSnapStartedEventHandler == null) { _scrollViewSnapStartedEventHandler += value; _scrollViewSnapStartedCallbackDelegate = new SnapStartedCallbackDelegate(OnSnapStarted); this.SnapStartedSignal().Connect(_scrollViewSnapStartedCallbackDelegate); } } } remove { lock (this) { if (_scrollViewSnapStartedEventHandler != null) { this.SnapStartedSignal().Disconnect(_scrollViewSnapStartedCallbackDelegate); } _scrollViewSnapStartedEventHandler -= value; } } } /// <summary> /// Sets and Gets WrapEnabled property. /// </summary> /// <since_tizen> 3 </since_tizen> public bool WrapEnabled { get { return (bool)GetValue(WrapEnabledProperty); } set { SetValue(WrapEnabledProperty, value); } } /// <summary> /// Sets and Gets PanningEnabled property. /// </summary> /// <since_tizen> 3 </since_tizen> public bool PanningEnabled { get { return (bool)GetValue(PanningEnabledProperty); } set { SetValue(PanningEnabledProperty, value); } } /// <summary> /// Sets and Gets AxisAutoLockEnabled property. /// </summary> /// <since_tizen> 3 </since_tizen> public bool AxisAutoLockEnabled { get { return (bool)GetValue(AxisAutoLockEnabledProperty); } set { SetValue(AxisAutoLockEnabledProperty, value); } } /// <summary> /// Sets and Gets WheelScrollDistanceStep property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 WheelScrollDistanceStep { get { return (Vector2)GetValue(WheelScrollDistanceStepProperty); } set { SetValue(WheelScrollDistanceStepProperty, value); } } /// <summary> /// Sets and Gets ScrollPosition property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 ScrollPosition { get { return (Vector2)GetValue(ScrollPositionProperty); } set { SetValue(ScrollPositionProperty, value); } } /// <summary> /// Sets and Gets ScrollPrePosition property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 ScrollPrePosition { get { return (Vector2)GetValue(ScrollPrePositionProperty); } set { SetValue(ScrollPrePositionProperty, value); } } /// <summary> /// Sets and Gets ScrollPrePositionMax property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 ScrollPrePositionMax { get { return (Vector2)GetValue(ScrollPrePositionMaxProperty); } set { SetValue(ScrollPrePositionMaxProperty, value); } } /// <summary> /// Sets and Gets OvershootX property. /// </summary> /// <since_tizen> 3 </since_tizen> public float OvershootX { get { return (float)GetValue(OvershootXProperty); } set { SetValue(OvershootXProperty, value); } } /// <summary> /// Sets and Gets OvershootY property. /// </summary> /// <since_tizen> 3 </since_tizen> public float OvershootY { get { return (float)GetValue(OvershootYProperty); } set { SetValue(OvershootYProperty, value); } } /// <summary> /// Sets and Gets ScrollFinal property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 ScrollFinal { get { return (Vector2)GetValue(ScrollFinalProperty); } set { SetValue(ScrollFinalProperty, value); } } /// <summary> /// Sets and Gets Wrap property. /// </summary> /// <since_tizen> 3 </since_tizen> public bool Wrap { get { return (bool)GetValue(WrapProperty); } set { SetValue(WrapProperty, value); } } /// <summary> /// Sets and Gets Panning property. /// </summary> /// <since_tizen> 3 </since_tizen> public bool Panning { get { return (bool)GetValue(PanningProperty); } set { SetValue(PanningProperty, value); } } /// <summary> /// Sets and Gets Scrolling property. /// </summary> /// <since_tizen> 3 </since_tizen> public bool Scrolling { get { return (bool)GetValue(ScrollingProperty); } set { SetValue(ScrollingProperty, value); } } /// <summary> /// Sets and Gets ScrollDomainSize property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 ScrollDomainSize { get { return (Vector2)GetValue(ScrollDomainSizeProperty); } set { SetValue(ScrollDomainSizeProperty, value); } } /// <summary> /// Sets and Gets ScrollDomainOffset property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 ScrollDomainOffset { get { return (Vector2)GetValue(ScrollDomainOffsetProperty); } set { SetValue(ScrollDomainOffsetProperty, value); } } /// <summary> /// Sets and Gets ScrollPositionDelta property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 ScrollPositionDelta { get { return (Vector2)GetValue(ScrollPositionDeltaProperty); } set { SetValue(ScrollPositionDeltaProperty, value); } } /// <summary> /// Sets and Gets StartPagePosition property. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector3 StartPagePosition { get { return (Vector3)GetValue(StartPagePositionProperty); } set { SetValue(StartPagePositionProperty, value); } } /// <summary> /// Sets and Gets ScrollMode property. /// </summary> /// <since_tizen> 3 </since_tizen> public PropertyMap ScrollMode { get { return (PropertyMap)GetValue(ScrollModeProperty); } set { SetValue(ScrollModeProperty, value); } } /// <summary> /// Gets snap-animation's AlphaFunction. /// </summary> /// <returns>Current easing alpha function of the snap animation.</returns> /// <since_tizen> 3 </since_tizen> public AlphaFunction GetScrollSnapAlphaFunction() { AlphaFunction ret = new AlphaFunction(Interop.ScrollView.ScrollView_GetScrollSnapAlphaFunction(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets snap-animation's AlphaFunction. /// </summary> /// <param name="alpha">Easing alpha function of the snap animation.</param> /// <since_tizen> 3 </since_tizen> public void SetScrollSnapAlphaFunction(AlphaFunction alpha) { Interop.ScrollView.ScrollView_SetScrollSnapAlphaFunction(swigCPtr, AlphaFunction.getCPtr(alpha)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets flick-animation's AlphaFunction. /// </summary> /// <returns>Current easing alpha function of the flick animation.</returns> /// <since_tizen> 3 </since_tizen> public AlphaFunction GetScrollFlickAlphaFunction() { AlphaFunction ret = new AlphaFunction(Interop.ScrollView.ScrollView_GetScrollFlickAlphaFunction(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets flick-animation's AlphaFunction. /// </summary> /// <param name="alpha">Easing alpha function of the flick animation.</param> /// <since_tizen> 3 </since_tizen> public void SetScrollFlickAlphaFunction(AlphaFunction alpha) { Interop.ScrollView.ScrollView_SetScrollFlickAlphaFunction(swigCPtr, AlphaFunction.getCPtr(alpha)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the time for the scroll snap-animation. /// </summary> /// <returns>The time in seconds for the animation to take.</returns> /// <since_tizen> 3 </since_tizen> public float GetScrollSnapDuration() { float ret = Interop.ScrollView.ScrollView_GetScrollSnapDuration(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the time for the scroll snap-animation. /// </summary> /// <param name="time">The time in seconds for the animation to take.</param> /// <since_tizen> 3 </since_tizen> public void SetScrollSnapDuration(float time) { Interop.ScrollView.ScrollView_SetScrollSnapDuration(swigCPtr, time); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the time for the scroll flick-animation. /// </summary> /// <returns>The time in seconds for the animation to take.</returns> /// <since_tizen> 3 </since_tizen> public float GetScrollFlickDuration() { float ret = Interop.ScrollView.ScrollView_GetScrollFlickDuration(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the time for the scroll snap-animation. /// </summary> /// <param name="time">The time in seconds for the animation to take.</param> /// <since_tizen> 3 </since_tizen> public void SetScrollFlickDuration(float time) { Interop.ScrollView.ScrollView_SetScrollFlickDuration(swigCPtr, time); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets scroll sensibility of pan gesture. /// </summary> /// <param name="sensitive">True to enable scroll, false to disable scrolling.</param> /// <since_tizen> 3 </since_tizen> public void SetScrollSensitive(bool sensitive) { Interop.ScrollView.ScrollView_SetScrollSensitive(swigCPtr, sensitive); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets maximum overshoot amount. /// </summary> /// <param name="overshootX">The maximum number of horizontally scrolled pixels before overshoot X reaches 1.0f.</param> /// <param name="overshootY">The maximum number of vertically scrolled pixels before overshoot X reaches 1.0f.</param> /// <since_tizen> 3 </since_tizen> public void SetMaxOvershoot(float overshootX, float overshootY) { Interop.ScrollView.ScrollView_SetMaxOvershoot(swigCPtr, overshootX, overshootY); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets Snap Overshoot animation's AlphaFunction. /// </summary> /// <param name="alpha">Easing alpha function of the overshoot snap animation.</param> /// <since_tizen> 3 </since_tizen> public void SetSnapOvershootAlphaFunction(AlphaFunction alpha) { Interop.ScrollView.ScrollView_SetSnapOvershootAlphaFunction(swigCPtr, AlphaFunction.getCPtr(alpha)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets Snap Overshoot animation's Duration. /// </summary> /// <param name="duration">duration The duration of the overshoot snap animation.</param> /// <since_tizen> 3 </since_tizen> public void SetSnapOvershootDuration(float duration) { Interop.ScrollView.ScrollView_SetSnapOvershootDuration(swigCPtr, duration); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Enables or Disables Actor Auto-Snap mode.<br /> /// When Actor Auto-Snap mode has been enabled, ScrollView will automatically, /// snap to the closest actor (The closest actor will appear in the center of the ScrollView). /// </summary> /// <param name="enable">Enables (true), or disables (false) Actor AutoSnap.</param> /// <since_tizen> 3 </since_tizen> public void SetViewAutoSnap(bool enable) { Interop.ScrollView.ScrollView_SetActorAutoSnap(swigCPtr, enable); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Enables or Disables Wrap mode for ScrollView contents.<br /> /// When enabled, the ScrollView contents are wrapped over the X/Y Domain. /// </summary> /// <param name="enable">Enables (true), or disables (false) Wrap Mode.</param> /// <since_tizen> 3 </since_tizen> public void SetWrapMode(bool enable) { Interop.ScrollView.ScrollView_SetWrapMode(swigCPtr, enable); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the current distance needed to scroll for ScrollUpdatedSignal to be emitted. /// </summary> /// <returns>Current scroll update distance.</returns> /// <since_tizen> 3 </since_tizen> public int GetScrollUpdateDistance() { int ret = Interop.ScrollView.ScrollView_GetScrollUpdateDistance(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the distance needed to scroll for ScrollUpdatedSignal to be emitted.<br /> /// The scroll update distance tells ScrollView how far to move before ScrollUpdatedSignal the informs application.<br /> /// Each time the ScrollView crosses this distance the signal will be emitted.<br /> /// </summary> /// <param name="distance">The distance for ScrollView to move before emitting update signal.</param> /// <since_tizen> 3 </since_tizen> public void SetScrollUpdateDistance(int distance) { Interop.ScrollView.ScrollView_SetScrollUpdateDistance(swigCPtr, distance); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Returns state of Axis Auto Lock mode. /// </summary> /// <returns>Whether Axis Auto Lock mode has been enabled or not.</returns> /// <since_tizen> 3 </since_tizen> public bool GetAxisAutoLock() { bool ret = Interop.ScrollView.ScrollView_GetAxisAutoLock(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Enables or Disables Axis Auto Lock mode for panning within the ScrollView.<br /> /// When enabled, any pan gesture that appears mostly horizontal or mostly /// vertical, will be automatically restricted to horizontal only or vertical /// only panning, until the pan gesture has completed. /// </summary> /// <param name="enable">Enables (true), or disables (false) AxisAutoLock mode.</param> /// <since_tizen> 3 </since_tizen> public void SetAxisAutoLock(bool enable) { Interop.ScrollView.ScrollView_SetAxisAutoLock(swigCPtr, enable); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the gradient threshold at which a panning gesture should be locked to the Horizontal or Vertical axis. /// </summary> /// <returns>The gradient, a value between 0.0 and 1.0f.</returns> /// <since_tizen> 3 </since_tizen> public float GetAxisAutoLockGradient() { float ret = Interop.ScrollView.ScrollView_GetAxisAutoLockGradient(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the gradient threshold at which a panning gesture should be locked to the Horizontal or Vertical axis.<br /> /// By default, this is 0.36 (0.36:1) which means angles less than 20 degrees to an axis will lock to that axis.<br /> /// </summary> /// <param name="gradient">gradient A value between 0.0 and 1.0 (auto-lock for all angles).</param> /// <since_tizen> 3 </since_tizen> public void SetAxisAutoLockGradient(float gradient) { Interop.ScrollView.ScrollView_SetAxisAutoLockGradient(swigCPtr, gradient); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the friction coefficient setting for ScrollView when flicking in free panning mode. /// This is a value in stage-diagonals per second^2, stage-diagonal = Length( stage.width, stage.height ) /// </summary> /// <returns>Friction coefficient is returned.</returns> /// <since_tizen> 3 </since_tizen> public float GetFrictionCoefficient() { float ret = Interop.ScrollView.ScrollView_GetFrictionCoefficient(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the friction coefficient for ScrollView when flicking.<br /> /// </summary> /// <param name="friction">Friction coefficient must be greater than 0.0 (default = 1.0).</param> /// <since_tizen> 3 </since_tizen> public void SetFrictionCoefficient(float friction) { Interop.ScrollView.ScrollView_SetFrictionCoefficient(swigCPtr, friction); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the flick speed coefficient for ScrollView when flicking in free panning mode.<br /> /// This is a constant which multiplies the input touch flick velocity to determine the actual velocity at which to move the scrolling area. /// </summary> /// <returns>The flick speed coefficient is returned.</returns> /// <since_tizen> 3 </since_tizen> public float GetFlickSpeedCoefficient() { float ret = Interop.ScrollView.ScrollView_GetFlickSpeedCoefficient(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the flick speed coefficient for ScrollView when flicking in free panning mode.<br /> /// This is a constant which multiplies the input touch flick velocity to determine the actual velocity at /// which to move the scrolling area.<br /> /// </summary> /// <param name="speed">The flick speed coefficient (default = 1.0).</param> /// <since_tizen> 3 </since_tizen> public void SetFlickSpeedCoefficient(float speed) { Interop.ScrollView.ScrollView_SetFlickSpeedCoefficient(swigCPtr, speed); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the minimum pan distance required for a flick gesture in pixels.<br /> /// </summary> /// <returns>Minimum pan distance vector with separate x and y distance.</returns> /// <since_tizen> 3 </since_tizen> public Vector2 GetMinimumDistanceForFlick() { Vector2 ret = new Vector2(Interop.ScrollView.ScrollView_GetMinimumDistanceForFlick(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the minimum pan distance required for a flick in pixels.<br /> /// Takes a Vector2 containing separate x and y values. As long as the pan distance exceeds one of these axes, a flick will be allowed. /// </summary> /// <param name="distance">The flick speed coefficient (default = 1.0).</param> /// <since_tizen> 3 </since_tizen> public void SetMinimumDistanceForFlick(Vector2 distance) { Interop.ScrollView.ScrollView_SetMinimumDistanceForFlick(swigCPtr, Vector2.getCPtr(distance)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Returns the minimum pan speed required for a flick gesture in pixels per second. /// </summary> /// <returns>Minimum pan speed.</returns> /// <since_tizen> 3 </since_tizen> public float GetMinimumSpeedForFlick() { float ret = Interop.ScrollView.ScrollView_GetMinimumSpeedForFlick(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the minimum pan speed required for a flick in pixels per second.<br /> /// </summary> /// <param name="speed">The minimum pan speed for a flick.</param> /// <since_tizen> 3 </since_tizen> public void SetMinimumSpeedForFlick(float speed) { Interop.ScrollView.ScrollView_SetMinimumSpeedForFlick(swigCPtr, speed); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the maximum flick speed setting for ScrollView when flicking in free panning mode.<br /> /// This is a value in stage-diagonals per second. /// </summary> /// <returns>Maximum flick speed is returned.</returns> /// <since_tizen> 3 </since_tizen> public float GetMaxFlickSpeed() { float ret = Interop.ScrollView.ScrollView_GetMaxFlickSpeed(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the maximum flick speed for the ScrollView when flicking in free panning mode.<br /> /// This is a value in stage-diagonals per second. stage-diagonal = Length( stage.width, stage.height ).<br /> /// </summary> /// <param name="speed">Maximum flick speed (default = 3.0).</param> /// <since_tizen> 3 </since_tizen> public void SetMaxFlickSpeed(float speed) { Interop.ScrollView.ScrollView_SetMaxFlickSpeed(swigCPtr, speed); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the step of scroll distance in actor coordinates for each wheel event received in free panning mode.<br /> /// </summary> /// <returns>The step of scroll distance(pixel) in X and Y axes.</returns> /// <since_tizen> 3 </since_tizen> public Vector2 GetWheelScrollDistanceStep() { Vector2 ret = new Vector2(Interop.ScrollView.ScrollView_GetWheelScrollDistanceStep(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the step of scroll distance in actor coordinates for each wheel event received in free panning mode.<br /> /// </summary> /// <param name="step">step The step of scroll distance(pixel) in X and Y axes.</param> /// <since_tizen> 3 </since_tizen> public void SetWheelScrollDistanceStep(Vector2 step) { Interop.ScrollView.ScrollView_SetWheelScrollDistanceStep(swigCPtr, Vector2.getCPtr(step)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Retrieves current scroll position.<br /> /// </summary> /// <returns>The current scroll position.</returns> /// <since_tizen> 3 </since_tizen> public Vector2 GetCurrentScrollPosition() { Vector2 ret = new Vector2(Interop.ScrollView.ScrollView_GetCurrentScrollPosition(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Retrieves current scroll page based on ScrollView dimensions being the size of one page, and all pages laid out in<br /> /// a grid fashion, increasing from left to right until the end of the X-domain. /// </summary> /// <returns>The current scroll position.</returns> /// <since_tizen> 3 </since_tizen> public uint GetCurrentPage() { uint ret = Interop.ScrollView.ScrollView_GetCurrentPage(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="position">The position to scroll to.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(Vector2 position) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_0(swigCPtr, Vector2.getCPtr(position)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="position">The position to scroll to.</param> /// <param name="duration">The duration of the animation in seconds.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(Vector2 position, float duration) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_1(swigCPtr, Vector2.getCPtr(position), duration); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="position">The position to scroll to.</param> /// <param name="duration">The duration of the animation in seconds.</param> /// <param name="alpha">The alpha function to use.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(Vector2 position, float duration, AlphaFunction alpha) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_2(swigCPtr, Vector2.getCPtr(position), duration, AlphaFunction.getCPtr(alpha)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="position">The position to scroll to.</param> /// <param name="duration">The duration of the animation in seconds.</param> /// <param name="horizontalBias">Whether to bias scrolling to left or right.</param> /// <param name="verticalBias">Whether to bias scrolling to top or bottom.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(Vector2 position, float duration, DirectionBias horizontalBias, DirectionBias verticalBias) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_3(swigCPtr, Vector2.getCPtr(position), duration, (int)horizontalBias, (int)verticalBias); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="position">The position to scroll to.</param> /// <param name="duration">The duration of the animation in seconds.</param> /// <param name="alpha">Alpha function to use.</param> /// <param name="horizontalBias">Whether to bias scrolling to left or right.</param> /// <param name="verticalBias">Whether to bias scrolling to top or bottom.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(Vector2 position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_4(swigCPtr, Vector2.getCPtr(position), duration, AlphaFunction.getCPtr(alpha), (int)horizontalBias, (int)verticalBias); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="page">The page to scroll to.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(uint page) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_5(swigCPtr, page); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="page">The page to scroll to.</param> /// <param name="duration">The duration of the animation in seconds.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(uint page, float duration) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_6(swigCPtr, page, duration); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="page">The page to scroll to.</param> /// <param name="duration">The duration of the animation in seconds.</param> /// <param name="bias">Whether to bias scrolling to left or right.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(uint page, float duration, DirectionBias bias) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_7(swigCPtr, page, duration, (int)bias); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="view">The view to center in on (via Scrolling).</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(View view) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_8(swigCPtr, View.getCPtr(view)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to position specified (contents will scroll to this position). /// </summary> /// <param name="view">The view to center in on (via Scrolling).</param> /// <param name="duration">The duration of the animation in seconds.</param> /// <since_tizen> 3 </since_tizen> public void ScrollTo(View view, float duration) { Interop.ScrollView.ScrollView_ScrollTo__SWIG_9(swigCPtr, View.getCPtr(view), duration); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Scrolls View to the nearest snap points as specified by the Rulers.<br /> /// If already at snap points, then will return false, and not scroll.<br /> /// </summary> /// <returns>True if Snapping necessary.</returns> /// <since_tizen> 3 </since_tizen> public bool ScrollToSnapPoint() { bool ret = Interop.ScrollView.ScrollView_ScrollToSnapPoint(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Applies Effect to ScrollView. /// </summary> /// <param name="effect">The effect to apply to scroll view.</param> /// <since_tizen> 3 </since_tizen> public void ApplyEffect(ScrollViewEffect effect) { Interop.ScrollView.ScrollView_ApplyEffect(swigCPtr, ScrollViewEffect.getCPtr(effect)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Removes Effect from ScrollView. /// </summary> /// <param name="effect">The effect to remove.</param> /// <since_tizen> 3 </since_tizen> public void RemoveEffect(ScrollViewEffect effect) { Interop.ScrollView.ScrollView_RemoveEffect(swigCPtr, ScrollViewEffect.getCPtr(effect)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Remove All Effects from ScrollView. /// </summary> /// <since_tizen> 3 </since_tizen> public void RemoveAllEffects() { Interop.ScrollView.ScrollView_RemoveAllEffects(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Binds view to this ScrollView. /// Once an actor is bound to a ScrollView, it will be subject to that ScrollView's properties. /// </summary> /// <param name="child">The view to add to this ScrollView.</param> /// <since_tizen> 3 </since_tizen> public void BindView(View child) { Interop.ScrollView.ScrollView_BindActor(swigCPtr, View.getCPtr(child)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Unbinds view to this ScrollView. /// Once an actor is bound to a ScrollView, it will be subject to that ScrollView's properties. /// </summary> /// <param name="child">The view to remove to this ScrollView.</param> /// <since_tizen> 3 </since_tizen> public void UnbindView(View child) { Interop.ScrollView.ScrollView_UnbindActor(swigCPtr, View.getCPtr(child)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Allows the user to constrain the scroll view in a particular direction. /// </summary> /// <param name="direction">The axis to constrain the scroll-view to.</param> /// <param name="threshold">The threshold to apply around the axis.</param> /// <since_tizen> 3 </since_tizen> public void SetScrollingDirection(Radian direction, Radian threshold) { Interop.ScrollView.ScrollView_SetScrollingDirection__SWIG_0(swigCPtr, Radian.getCPtr(direction), Radian.getCPtr(threshold)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Allows the user to constrain the scroll view in a particular direction. /// </summary> /// <param name="direction">The axis to constrain the scroll-view to.</param> /// <since_tizen> 3 </since_tizen> public void SetScrollingDirection(Radian direction) { Interop.ScrollView.ScrollView_SetScrollingDirection__SWIG_1(swigCPtr, Radian.getCPtr(direction)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Removes a direction constraint from the scroll view. /// </summary> /// <param name="direction">The axis to constrain the scroll-view to.</param> /// <since_tizen> 3 </since_tizen> public void RemoveScrollingDirection(Radian direction) { Interop.ScrollView.ScrollView_RemoveScrollingDirection(swigCPtr, Radian.getCPtr(direction)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Set ruler X /// </summary> /// This will be public opened in next tizen after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetRulerX(RulerPtr ruler) { Interop.ScrollView.ScrollView_SetRulerX(swigCPtr, RulerPtr.getCPtr(ruler)); } /// <summary> /// Set ruler Y /// </summary> /// This will be public opened in next tizen after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetRulerY(RulerPtr ruler) { Interop.ScrollView.ScrollView_SetRulerY(swigCPtr, RulerPtr.getCPtr(ruler)); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(ScrollView obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } internal void ApplyConstraintToChildren(SWIGTYPE_p_Dali__Constraint constraint) { Interop.ScrollView.ScrollView_ApplyConstraintToChildren(swigCPtr, SWIGTYPE_p_Dali__Constraint.getCPtr(constraint)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal ScrollViewSnapStartedSignal SnapStartedSignal() { ScrollViewSnapStartedSignal ret = new ScrollViewSnapStartedSignal(Interop.ScrollView.ScrollView_SnapStartedSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Dispose /// </summary> /// <param name="type">the dispose type</param> /// <since_tizen> 3 </since_tizen> protected override void Dispose(DisposeTypes type) { if (disposed) { return; } if (type == DisposeTypes.Explicit) { //Called by User //Release your own managed resources here. //You should release all of your own disposable objects here. } //Release your own unmanaged resources here. //You should not access any managed member here except static instance. //because the execution order of Finalizes is non-deterministic. if (this != null && _scrollViewSnapStartedCallbackDelegate != null) { this.SnapStartedSignal().Disconnect(_scrollViewSnapStartedCallbackDelegate); } if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; Interop.ScrollView.delete_ScrollView(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } base.Dispose(type); } // Callback for ScrollView SnapStarted signal private void OnSnapStarted(IntPtr data) { SnapStartedEventArgs e = new SnapStartedEventArgs(); // Populate all members of "e" (SnapStartedEventArgs) with real data e.SnapEventInfo = SnapEvent.GetSnapEventFromPtr(data); if (_scrollViewSnapStartedEventHandler != null) { //here we send all data to user event handlers _scrollViewSnapStartedEventHandler(this, e); } } /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public new class Property { /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int WRAP_ENABLED = Interop.ScrollView.ScrollView_Property_WRAP_ENABLED_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int PANNING_ENABLED = Interop.ScrollView.ScrollView_Property_PANNING_ENABLED_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int AXIS_AUTO_LOCK_ENABLED = Interop.ScrollView.ScrollView_Property_AXIS_AUTO_LOCK_ENABLED_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int WHEEL_SCROLL_DISTANCE_STEP = Interop.ScrollView.ScrollView_Property_WHEEL_SCROLL_DISTANCE_STEP_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_MODE = Interop.ScrollView.ScrollView_Property_SCROLL_MODE_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_POSITION = Interop.ScrollView.ScrollView_Property_SCROLL_POSITION_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_PRE_POSITION = Interop.ScrollView.ScrollView_Property_SCROLL_PRE_POSITION_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_PRE_POSITION_X = Interop.ScrollView.ScrollView_Property_SCROLL_PRE_POSITION_X_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_PRE_POSITION_Y = Interop.ScrollView.ScrollView_Property_SCROLL_PRE_POSITION_Y_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_PRE_POSITION_MAX = Interop.ScrollView.ScrollView_Property_SCROLL_PRE_POSITION_MAX_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_PRE_POSITION_MAX_X = Interop.ScrollView.ScrollView_Property_SCROLL_PRE_POSITION_MAX_X_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_PRE_POSITION_MAX_Y = Interop.ScrollView.ScrollView_Property_SCROLL_PRE_POSITION_MAX_Y_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int OVERSHOOT_X = Interop.ScrollView.ScrollView_Property_OVERSHOOT_X_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int OVERSHOOT_Y = Interop.ScrollView.ScrollView_Property_OVERSHOOT_Y_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_FINAL = Interop.ScrollView.ScrollView_Property_SCROLL_FINAL_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_FINAL_X = Interop.ScrollView.ScrollView_Property_SCROLL_FINAL_X_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_FINAL_Y = Interop.ScrollView.ScrollView_Property_SCROLL_FINAL_Y_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int WRAP = Interop.ScrollView.ScrollView_Property_WRAP_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int PANNING = Interop.ScrollView.ScrollView_Property_PANNING_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLLING = Interop.ScrollView.ScrollView_Property_SCROLLING_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_DOMAIN_SIZE = Interop.ScrollView.ScrollView_Property_SCROLL_DOMAIN_SIZE_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_DOMAIN_SIZE_X = Interop.ScrollView.ScrollView_Property_SCROLL_DOMAIN_SIZE_X_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_DOMAIN_SIZE_Y = Interop.ScrollView.ScrollView_Property_SCROLL_DOMAIN_SIZE_Y_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_DOMAIN_OFFSET = Interop.ScrollView.ScrollView_Property_SCROLL_DOMAIN_OFFSET_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_POSITION_DELTA = Interop.ScrollView.ScrollView_Property_SCROLL_POSITION_DELTA_get(); /// <summary> /// This should be internal, please do not use. /// </summary> /// <since_tizen> 3 </since_tizen> public static readonly int START_PAGE_POSITION = Interop.ScrollView.ScrollView_Property_START_PAGE_POSITION_get(); } /// <summary> /// Snaps signal event's data. /// </summary> /// <since_tizen> 3 </since_tizen> public class SnapEvent : global::System.IDisposable { /// <summary> /// swigCMemOwn /// </summary> /// <since_tizen> 3 </since_tizen> protected bool swigCMemOwn; /// <summary> /// A Flat to check if it is already disposed. /// </summary> /// swigCMemOwn /// <since_tizen> 3 </since_tizen> protected bool disposed = false; private global::System.Runtime.InteropServices.HandleRef swigCPtr; //A Flag to check who called Dispose(). (By User or DisposeQueue) private bool isDisposeQueued = false; /// <summary> /// Create an instance of SnapEvent. /// </summary> /// <since_tizen> 3 </since_tizen> public SnapEvent() : this(Interop.ScrollView.new_ScrollView_SnapEvent(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal SnapEvent(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } /// <summary> /// Dispose /// </summary> /// <since_tizen> 3 </since_tizen> ~SnapEvent() { if (!isDisposeQueued) { isDisposeQueued = true; DisposeQueue.Instance.Add(this); } } /// <summary> /// Scroll position. /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 position { set { Interop.ScrollView.ScrollView_SnapEvent_position_set(swigCPtr, Vector2.getCPtr(value)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } get { global::System.IntPtr cPtr = Interop.ScrollView.ScrollView_SnapEvent_position_get(swigCPtr); Vector2 ret = (cPtr == global::System.IntPtr.Zero) ? null : new Vector2(cPtr, false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } } /// <summary> /// Scroll duration. /// </summary> /// <since_tizen> 3 </since_tizen> public float duration { set { Interop.ScrollView.ScrollView_SnapEvent_duration_set(swigCPtr, value); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } get { float ret = Interop.ScrollView.ScrollView_SnapEvent_duration_get(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } } internal SnapType type { set { Interop.ScrollView.ScrollView_SnapEvent_type_set(swigCPtr, (int)value); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } get { SnapType ret = (SnapType)Interop.ScrollView.ScrollView_SnapEvent_type_get(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } } /// <summary> /// Get SnapEvent From Ptr /// </summary> /// <since_tizen> 3 </since_tizen> public static SnapEvent GetSnapEventFromPtr(global::System.IntPtr cPtr) { SnapEvent ret = new SnapEvent(cPtr, false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Dispose. /// </summary> /// <since_tizen> 3 </since_tizen> public void Dispose() { //Throw excpetion if Dispose() is called in separate thread. if (!Window.IsInstalled()) { throw new System.InvalidOperationException("This API called from separate thread. This API must be called from MainThread."); } if (isDisposeQueued) { Dispose(DisposeTypes.Implicit); } else { Dispose(DisposeTypes.Explicit); System.GC.SuppressFinalize(this); } } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SnapEvent obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } /// <summary> /// Dispose /// </summary> /// <param name="type">the dispose type</param> /// <since_tizen> 3 </since_tizen> protected virtual void Dispose(DisposeTypes type) { if (disposed) { return; } if (type == DisposeTypes.Explicit) { //Called by User //Release your own managed resources here. //You should release all of your own disposable objects here. } //Release your own unmanaged resources here. //You should not access any managed member here except static instance. //because the execution order of Finalizes is non-deterministic. if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; Interop.ScrollView.delete_ScrollView_SnapEvent(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } disposed = true; } } /// <summary> /// Event arguments that passed via the SnapStarted signal. /// </summary> /// <since_tizen> 3 </since_tizen> public class SnapStartedEventArgs : EventArgs { private Tizen.NUI.ScrollView.SnapEvent _snapEvent; /// <summary> /// SnapEventInfo is the SnapEvent information like snap or flick (it tells the target position, scale, rotation for the snap or flick). /// </summary> /// <since_tizen> 3 </since_tizen> public Tizen.NUI.ScrollView.SnapEvent SnapEventInfo { get { return _snapEvent; } set { _snapEvent = value; } } } } }
44.882587
234
0.605045
[ "Apache-2.0" ]
sparrow74/TizenFX
src/Tizen.NUI/src/public/UIComponents/ScrollView.cs
79,128
C#
using System; using System.Collections; using System.Globalization; using System.Linq; #if HAS_UNO using Windows.UI.Xaml; using Windows.UI.Xaml.Data; using _CultureInfo = System.String; #else using System.Windows; using _CultureInfo = System.Globalization.CultureInfo; using System.Windows.Data; #endif namespace PackageExplorer { public class NullToVisibilityConverter : IValueConverter { public bool Inverted { get; set; } #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, _CultureInfo culture) { if (targetType == typeof(Visibility)) { Visibility returnValue; if (value is string stringValue) { returnValue = string.IsNullOrEmpty(stringValue) ? Visibility.Collapsed : Visibility.Visible; } else if(value is ICollection collection) { returnValue = collection.Count == 0 ? Visibility.Collapsed : Visibility.Visible; } else if (value is IEnumerable enu) { returnValue = enu.Cast<object>().Any() ? Visibility.Visible : Visibility.Collapsed; } else { returnValue = value == null ? Visibility.Collapsed : Visibility.Visible; } if (Inverted) { if (returnValue == Visibility.Visible) { returnValue = Visibility.Collapsed; } else { returnValue = Visibility.Visible; } } return returnValue; } return value; } public object ConvertBack(object value, Type targetType, object parameter, _CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
28.162162
112
0.528791
[ "MIT" ]
MarcelWolf1983/NuGetPackageExplorer
PackageExplorer/Converters/NullToVisibilityConverter.cs
2,086
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Media.Devices { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] #endif public partial class DefaultAudioCaptureDeviceChangedEventArgs : global::Windows.Media.Devices.IDefaultAudioDeviceChangedEventArgs { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public string Id { get { throw new global::System.NotImplementedException("The member string DefaultAudioCaptureDeviceChangedEventArgs.Id is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Media.Devices.AudioDeviceRole Role { get { throw new global::System.NotImplementedException("The member AudioDeviceRole DefaultAudioCaptureDeviceChangedEventArgs.Role is not implemented in Uno."); } } #endif // Forced skipping of method Windows.Media.Devices.DefaultAudioCaptureDeviceChangedEventArgs.Id.get // Forced skipping of method Windows.Media.Devices.DefaultAudioCaptureDeviceChangedEventArgs.Role.get // Processing: Windows.Media.Devices.IDefaultAudioDeviceChangedEventArgs } }
35.971429
157
0.772836
[ "Apache-2.0" ]
nv-ksavaria/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Devices/DefaultAudioCaptureDeviceChangedEventArgs.cs
1,259
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class MethodSymbolExtensions { public static bool IsParams(this MethodSymbol method) { return method.ParameterCount != 0 && method.Parameters[method.ParameterCount - 1].IsParams; } /// <summary> /// If the extension method is applicable based on the "this" argument type, return /// the method constructed with the inferred type arguments. If the method is not an /// unconstructed generic method, type inference is skipped. If the method is not /// applicable, or if constraints when inferring type parameters from the "this" type /// are not satisfied, the return value is null. /// </summary> public static MethodSymbol InferExtensionMethodTypeArguments(this MethodSymbol method, TypeSymbol thisType, Compilation compilation, ref HashSet<DiagnosticInfo> useSiteDiagnostics) { Debug.Assert(method.IsExtensionMethod); Debug.Assert((object)thisType != null); if (!method.IsGenericMethod || method != method.ConstructedFrom) { return method; } // We never resolve extension methods on a dynamic receiver. if (thisType.IsDynamic()) { return null; } var containingAssembly = method.ContainingAssembly; var errorNamespace = containingAssembly.GlobalNamespace; var conversions = new TypeConversions(containingAssembly.CorLibrary); // There is absolutely no plausible syntax/tree that we could use for these // synthesized literals. We could be speculatively binding a call to a PE method. var syntaxTree = CSharpSyntaxTree.Dummy; var syntax = (CSharpSyntaxNode)syntaxTree.GetRoot(); // Create an argument value for the "this" argument of specific type, // and pass the same bad argument value for all other arguments. var thisArgumentValue = new BoundLiteral(syntax, ConstantValue.Bad, thisType) { WasCompilerGenerated = true }; var otherArgumentType = new ExtendedErrorTypeSymbol(errorNamespace, name: string.Empty, arity: 0, errorInfo: null, unreported: false); var otherArgumentValue = new BoundLiteral(syntax, ConstantValue.Bad, otherArgumentType) { WasCompilerGenerated = true }; var paramCount = method.ParameterCount; var arguments = new BoundExpression[paramCount]; for (int i = 0; i < paramCount; i++) { var argument = (i == 0) ? thisArgumentValue : otherArgumentValue; arguments[i] = argument; } var typeArgs = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument( conversions, method, arguments.AsImmutable(), ref useSiteDiagnostics); if (typeArgs.IsDefault) { return null; } int firstNullInTypeArgs = -1; // For the purpose of constraint checks we use error type symbol in place of type arguments that we couldn't infer from the first argument. // This prevents constraint checking from failing for corresponding type parameters. var notInferredTypeParameters = PooledHashSet<TypeParameterSymbol>.GetInstance(); var typeParams = method.TypeParameters; var typeArgsForConstraintsCheck = typeArgs; for (int i = 0; i < typeArgsForConstraintsCheck.Length; i++) { if ((object)typeArgsForConstraintsCheck[i] == null) { firstNullInTypeArgs = i; var builder = ArrayBuilder<TypeSymbol>.GetInstance(); builder.AddRange(typeArgs, firstNullInTypeArgs); for (; i < typeArgsForConstraintsCheck.Length; i++) { var typeArg = typeArgsForConstraintsCheck[i]; if ((object)typeArg == null) { notInferredTypeParameters.Add(typeParams[i]); builder.Add(ErrorTypeSymbol.UnknownResultType); } else { builder.Add(typeArg); } } typeArgsForConstraintsCheck = builder.ToImmutableAndFree(); break; } } // Check constraints. var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var substitution = new TypeMap(typeParams, typeArgsForConstraintsCheck.SelectAsArray(TypeMap.TypeSymbolAsTypeWithModifiers)); ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder = null; var success = method.CheckConstraints(conversions, substitution, typeParams, typeArgsForConstraintsCheck, compilation, diagnosticsBuilder, ref useSiteDiagnosticsBuilder, ignoreTypeConstraintsDependentOnTypeParametersOpt: notInferredTypeParameters.Count > 0 ? notInferredTypeParameters : null); diagnosticsBuilder.Free(); notInferredTypeParameters.Free(); if (useSiteDiagnosticsBuilder != null && useSiteDiagnosticsBuilder.Count > 0) { if (useSiteDiagnostics == null) { useSiteDiagnostics = new HashSet<DiagnosticInfo>(); } foreach (var diag in useSiteDiagnosticsBuilder) { useSiteDiagnostics.Add(diag.DiagnosticInfo); } } if (!success) { return null; } // For the purpose of construction we use original type parameters in place of type arguments that we couldn't infer from the first argument. var typeArgsForConstruct = typeArgs; if (firstNullInTypeArgs != -1) { var builder = ArrayBuilder<TypeSymbol>.GetInstance(); builder.AddRange(typeArgs, firstNullInTypeArgs); for (int i = firstNullInTypeArgs; i < typeArgsForConstruct.Length; i++) { builder.Add(typeArgsForConstruct[i] ?? typeParams[i]); } typeArgsForConstruct = builder.ToImmutableAndFree(); } return method.Construct(typeArgsForConstruct); } internal static bool IsSynthesizedLambda(this MethodSymbol method) { Debug.Assert((object)method != null); return method.IsImplicitlyDeclared && method.MethodKind == MethodKind.AnonymousFunction; } /// <summary> /// The runtime considers a method to be a finalizer (i.e. a method that should be invoked /// by the garbage collector) if it (directly or indirectly) overrides System.Object.Finalize. /// </summary> /// <remarks> /// As an optimization, return true immediately for metadata methods with MethodKind /// Destructor - they are guaranteed to be finalizers. /// </remarks> /// <param name="method">Method to inspect.</param> /// <param name="skipFirstMethodKindCheck">This method is used to determine the method kind of /// a PEMethodSymbol, so we may need to avoid using MethodKind until we move on to a different /// MethodSymbol.</param> public static bool IsRuntimeFinalizer(this MethodSymbol method, bool skipFirstMethodKindCheck = false) { // Note: Flipping the metadata-virtual bit on a method can't change it from not-a-runtime-finalize // to runtime-finalizer (since it will also be marked newslot), so it is safe to use // IsMetadataVirtualIgnoringInterfaceImplementationChanges. This also has the advantage of making // this method safe to call before declaration diagnostics have been computed. if ((object)method == null || method.Name != WellKnownMemberNames.DestructorName || method.ParameterCount != 0 || method.Arity != 0 || !method.IsMetadataVirtual(ignoreInterfaceImplementationChanges: true)) { return false; } while ((object)method != null) { if (!skipFirstMethodKindCheck && method.MethodKind == MethodKind.Destructor) { // For metadata symbols (and symbols that wrap them), having MethodKind // Destructor guarantees that the method is a runtime finalizer. // This is also true for source symbols, since we make them explicitly // override System.Object.Finalize. return true; } else if (method.ContainingType.SpecialType == SpecialType.System_Object) { return true; } else if (method.IsMetadataNewSlot(ignoreInterfaceImplementationChanges: true)) { // If the method isn't a runtime override, then it can't be a finalizer. return false; } // At this point, we know method originated with a DestructorDeclarationSyntax in source, // so it can't have the "new" modifier. // First is fine, since there should only be one, since there are no parameters. method = method.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(ignoreInterfaceImplementationChanges: true); skipFirstMethodKindCheck = false; } return false; } /// <summary> /// Returns a constructed method symbol if 'method' is generic, otherwise just returns 'method' /// </summary> public static MethodSymbol ConstructIfGeneric(this MethodSymbol method, ImmutableArray<TypeSymbol> typeArguments) { Debug.Assert(method.IsGenericMethod == (typeArguments.Length > 0)); return method.IsGenericMethod ? method.Construct(typeArguments) : method; } /// <summary> /// Some kinds of methods are not considered to be hideable by certain kinds of members. /// Specifically, methods, properties, and types cannot hide constructors, destructors, /// operators, conversions, or accessors. /// </summary> public static bool CanBeHiddenByMemberKind(this MethodSymbol hiddenMethod, SymbolKind hidingMemberKind) { Debug.Assert((object)hiddenMethod != null); // Nothing can hide a destructor (see SymbolPreparer::ReportHiding) if (hiddenMethod.MethodKind == MethodKind.Destructor) { return false; } switch (hidingMemberKind) { case SymbolKind.ErrorType: case SymbolKind.NamedType: case SymbolKind.Method: case SymbolKind.Property: return CanBeHiddenByMethodPropertyOrType(hiddenMethod); case SymbolKind.Field: case SymbolKind.Event: // Events are not covered by CSemanticChecker::FindSymHiddenByMethPropAgg. return true; default: throw ExceptionUtilities.UnexpectedValue(hidingMemberKind); } } /// <summary> /// Some kinds of methods are never considered hidden by methods, properties, or types /// (constructors, destructors, operators, conversions, and accessors). /// </summary> private static bool CanBeHiddenByMethodPropertyOrType(MethodSymbol method) { switch (method.MethodKind) { // See CSemanticChecker::FindSymHiddenByMethPropAgg. case MethodKind.Destructor: case MethodKind.Constructor: case MethodKind.StaticConstructor: case MethodKind.UserDefinedOperator: case MethodKind.Conversion: return false; case MethodKind.EventAdd: case MethodKind.EventRemove: case MethodKind.PropertyGet: case MethodKind.PropertySet: return method.IsIndexedPropertyAccessor(); default: return true; } } /// <summary> /// Returns whether this method is async and returns void. /// </summary> public static bool IsVoidReturningAsync(this MethodSymbol method) { return method.IsAsync && method.ReturnsVoid; } /// <summary> /// Returns whether this method is async and returns a task. /// </summary> public static bool IsTaskReturningAsync(this MethodSymbol method, CSharpCompilation compilation) { return method.IsAsync && method.ReturnType.IsNonGenericTaskType(compilation); } /// <summary> /// Returns whether this method is async and returns a generic task. /// </summary> public static bool IsGenericTaskReturningAsync(this MethodSymbol method, CSharpCompilation compilation) { return method.IsAsync && method.ReturnType.IsGenericTaskType(compilation); } internal static CSharpSyntaxNode ExtractReturnTypeSyntax(this MethodSymbol method) { method = method.PartialDefinitionPart ?? method; foreach (var reference in method.DeclaringSyntaxReferences) { if (reference.GetSyntax() is MethodDeclarationSyntax methodDeclaration) { return methodDeclaration.ReturnType; } } return (CSharpSyntaxNode)CSharpSyntaxTree.Dummy.GetRoot(); } } }
45.71028
188
0.600014
[ "Apache-2.0" ]
AdamSpeight2008/roslyn-1
src/Compilers/CSharp/Portable/Symbols/MethodSymbolExtensions.cs
14,675
C#
using System; // ReSharper disable CheckNamespace namespace TouchPortalSDK.Extensions.Attributes { public static partial class Data { [AttributeUsage(AttributeTargets.Parameter)] public class TextAttribute : DataAttribute { public override string Type => "text"; public string Default { get; set; } = string.Empty; } } }
21.833333
63
0.641221
[ "MIT" ]
oddbear/TouchPortalSDK.Extensions
TouchPortalSDK.Extensions.Attributes/Data/Data.TextAttribute.cs
395
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("ADOAccelerator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ADOAccelerator")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("d568e801-4daf-4ebb-8fbd-16cd1bf7dd92")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.567568
103
0.750833
[ "MIT" ]
obrassard/ADO-Accelerator
PainlessADO/Properties/AssemblyInfo.cs
1,526
C#
using System; using System.Net; using System.Net.Sockets; using System.Security; using System.Threading; namespace ExitGames.Client.Photon { internal class SocketUdp : IPhotonSocket { private Socket sock; private readonly object syncer = new object(); public SocketUdp(PeerBase npeer) : base(npeer) { if (ReportDebugOfLevel(DebugLevel.ALL)) { base.Listener.DebugReturn(DebugLevel.ALL, "CSharpSocket: UDP, Unity3d."); } base.Protocol = ConnectionProtocol.Udp; PollReceive = false; } public override bool Connect() { //Discarded unreachable code: IL_0059 lock (syncer) { if (!base.Connect()) { return false; } base.State = PhotonSocketState.Connecting; Thread thread = new Thread(DnsAndConnect); thread.Name = "photon dns thread"; thread.IsBackground = true; thread.Start(); return true; } } public override bool Disconnect() { if (ReportDebugOfLevel(DebugLevel.INFO)) { EnqueueDebugReturn(DebugLevel.INFO, "CSharpSocket.Disconnect()"); } base.State = PhotonSocketState.Disconnecting; lock (syncer) { if (sock != null) { try { sock.Close(); sock = null; } catch (Exception arg) { EnqueueDebugReturn(DebugLevel.INFO, "Exception in Disconnect(): " + arg); } } } base.State = PhotonSocketState.Disconnected; return true; } public override PhotonSocketError Send(byte[] data, int length) { //Discarded unreachable code: IL_0041 lock (syncer) { if (!sock.Connected) { return PhotonSocketError.Skipped; } try { sock.Send(data, 0, length, SocketFlags.None); } catch { return PhotonSocketError.Exception; } } return PhotonSocketError.Success; } public override PhotonSocketError Receive(out byte[] data) { data = null; return PhotonSocketError.NoData; } internal void DnsAndConnect() { //Discarded unreachable code: IL_008b, IL_00c9 try { lock (syncer) { sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPAddress ipAddress = IPhotonSocket.GetIpAddress(base.ServerAddress); sock.Connect(ipAddress, base.ServerPort); base.State = PhotonSocketState.Connected; } } catch (SecurityException ex) { if (ReportDebugOfLevel(DebugLevel.ERROR)) { base.Listener.DebugReturn(DebugLevel.ERROR, "Connect() failed: " + ex.ToString()); } HandleException(StatusCode.SecurityExceptionOnConnect); return; } catch (Exception ex2) { if (ReportDebugOfLevel(DebugLevel.ERROR)) { base.Listener.DebugReturn(DebugLevel.ERROR, "Connect() failed: " + ex2.ToString()); } HandleException(StatusCode.ExceptionOnConnect); return; } Thread thread = new Thread(ReceiveLoop); thread.Name = "photon receive thread"; thread.IsBackground = true; thread.Start(); } public void ReceiveLoop() { byte[] array = new byte[base.MTU]; while (base.State == PhotonSocketState.Connected) { try { int length = sock.Receive(array); HandleReceivedDatagram(array, length, willBeReused: true); } catch (Exception ex) { if (base.State != PhotonSocketState.Disconnecting && base.State != 0) { if (ReportDebugOfLevel(DebugLevel.ERROR)) { EnqueueDebugReturn(DebugLevel.ERROR, "Receive issue. State: " + base.State + " Exception: " + ex); } HandleException(StatusCode.ExceptionOnReceive); } } } Disconnect(); } } }
22.46875
105
0.652295
[ "Apache-2.0" ]
alerithe/guardian
Assembly-CSharp/ExitGames.Client.Photon/SocketUdp.cs
3,595
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2019 // // 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. // This file was automatically generated and should not be edited directly. namespace SharpVk { /// <summary> /// Indicate which dynamic state is taken from dynamic state commands. /// </summary> public enum DynamicState { /// <summary> /// Indicates that the pViewports state in /// PipelineViewportStateCreateInfo will be ignored and must be set /// dynamically with flink:vkCmdSetViewport before any draw commands. /// The number of viewports used by a pipeline is still specified by /// the viewportCount member of PipelineViewportStateCreateInfo. /// </summary> Viewport = 0, /// <summary> /// Indicates that the pScissors state in /// PipelineViewportStateCreateInfo will be ignored and must be set /// dynamically with flink:vkCmdSetScissor before any draw commands. /// The number of scissor rectangles used by a pipeline is still /// specified by the scissorCount member of /// PipelineViewportStateCreateInfo. /// </summary> Scissor = 1, /// <summary> /// Indicates that the lineWidth state in /// PipelineRasterizationStateCreateInfo will be ignored and must be /// set dynamically with flink:vkCmdSetLineWidth before any draw /// commands that generate line primitives for the rasterizer. /// </summary> LineWidth = 2, /// <summary> /// Indicates that the depthBiasConstantFactor, depthBiasClamp and /// depthBiasSlopeFactor states in PipelineRasterizationStateCreateInfo /// will be ignored and must be set dynamically with /// flink:vkCmdSetDepthBias before any draws are performed with /// depthBiasEnable in PipelineRasterizationStateCreateInfo set to /// VK_TRUE. /// </summary> DepthBias = 3, /// <summary> /// Indicates that the blendConstants state in /// PipelineColorBlendStateCreateInfo will be ignored and must be set /// dynamically with flink:vkCmdSetBlendConstants before any draws are /// performed with a pipeline state with /// PipelineColorBlendAttachmentState member blendEnable set to VK_TRUE /// and any of the blend functions using a constant blend color. /// </summary> BlendConstants = 4, /// <summary> /// Indicates that the minDepthBounds and maxDepthBounds states of /// PipelineDepthStencilStateCreateInfo will be ignored and must be set /// dynamically with flink:vkCmdSetDepthBounds before any draws are /// performed with a pipeline state with /// PipelineDepthStencilStateCreateInfo member depthBoundsTestEnable /// set to VK_TRUE. /// </summary> DepthBounds = 5, /// <summary> /// Indicates that the compareMask state in /// PipelineDepthStencilStateCreateInfo for both front and back will be /// ignored and must be set dynamically with /// flink:vkCmdSetStencilCompareMask before any draws are performed /// with a pipeline state with PipelineDepthStencilStateCreateInfo /// member stencilTestEnable set to VK_TRUE /// </summary> StencilCompareMask = 6, /// <summary> /// Indicates that the writeMask state in /// PipelineDepthStencilStateCreateInfo for both front and back will be /// ignored and must be set dynamically with /// flink:vkCmdSetStencilWriteMask before any draws are performed with /// a pipeline state with PipelineDepthStencilStateCreateInfo member /// stencilTestEnable set to VK_TRUE /// </summary> StencilWriteMask = 7, /// <summary> /// Indicates that the reference state in /// PipelineDepthStencilStateCreateInfo for both front and back will be /// ignored and must be set dynamically with /// flink:vkCmdSetStencilReference before any draws are performed with /// a pipeline state with PipelineDepthStencilStateCreateInfo member /// stencilTestEnable set to VK_TRUE /// </summary> StencilReference = 8, /// <summary> /// /// </summary> ViewportWScaling = 1000087000, /// <summary> /// /// </summary> DiscardRectangle = 1000099000, /// <summary> /// /// </summary> SampleLocations = 1000143000, /// <summary> /// /// </summary> ViewportShadingRatePalette = 1000164004, /// <summary> /// /// </summary> ViewportCoarseSampleOrder = 1000164006, /// <summary> /// /// </summary> ExclusiveScissor = 1000205001, } }
40.866667
81
0.641272
[ "MIT" ]
Y-Less/SharpVk
src/SharpVk/DynamicState.gen.cs
6,130
C#
namespace SoftUniClone.Data { using Configurations; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Models; public class SoftUniCloneDbContext : IdentityDbContext<User> { public DbSet<Course> Courses { get; set; } public DbSet<CourseInstance> Course { get; set; } public DbSet<Lecture> Lectures { get; set; } public DbSet<Resource> Resources { get; set; } public DbSet<ResourceType> ResourceTypes { get; set; } public DbSet<StudentCourse> StudentsCourses { get; set; } public SoftUniCloneDbContext(DbContextOptions<SoftUniCloneDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { builder.ApplyConfiguration(new CourseConfig()); builder.ApplyConfiguration(new StudentConfig()); builder.ApplyConfiguration(new StudentCourseConfig()); base.OnModelCreating(builder); } } }
29.027027
85
0.654562
[ "MIT" ]
Shtereva/CSharp-MVC-ASP.Net-Core
SoftUniClone/SoftUniClone.Data/SoftUniCloneDbContext.cs
1,076
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Sakuracloud { public static class GetIcon { /// <summary> /// Get information about an existing Icon. /// /// {{% examples %}} /// ## Example Usage /// {{% example %}} /// /// ```csharp /// using Pulumi; /// using Sakuracloud = Pulumi.Sakuracloud; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var foobar = Output.Create(Sakuracloud.GetIcon.InvokeAsync(new Sakuracloud.GetIconArgs /// { /// Filter = new Sakuracloud.Inputs.GetIconFilterArgs /// { /// Names = /// { /// "foobar", /// }, /// }, /// })); /// } /// /// } /// ``` /// {{% /example %}} /// {{% /examples %}} /// </summary> public static Task<GetIconResult> InvokeAsync(GetIconArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetIconResult>("sakuracloud:index/getIcon:getIcon", args ?? new GetIconArgs(), options.WithVersion()); } public sealed class GetIconArgs : Pulumi.InvokeArgs { /// <summary> /// One or more values used for filtering, as defined below. /// </summary> [Input("filter")] public Inputs.GetIconFilterArgs? Filter { get; set; } public GetIconArgs() { } } [OutputType] public sealed class GetIconResult { public readonly Outputs.GetIconFilterResult? Filter; /// <summary> /// The provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; /// <summary> /// The name of the Icon. /// </summary> public readonly string Name; /// <summary> /// Any tags assigned to the Icon. /// </summary> public readonly ImmutableArray<string> Tags; /// <summary> /// The URL for getting the icon's raw data. /// </summary> public readonly string Url; [OutputConstructor] private GetIconResult( Outputs.GetIconFilterResult? filter, string id, string name, ImmutableArray<string> tags, string url) { Filter = filter; Id = id; Name = name; Tags = tags; Url = url; } } }
28.160377
156
0.496147
[ "ECL-2.0", "Apache-2.0" ]
sacloud/pulumi-sakuracloud
sdk/dotnet/GetIcon.cs
2,985
C#
using System; using Unity.Lifetime; using Unity.Policy; using Unity.Storage; namespace Unity { public partial class UnityContainer { /// <inheritdoc /> public partial class ContainerContext { #region Extension Context public override UnityContainer Container { get; } public override ILifetimeContainer Lifetime => Container.LifetimeContainer; public override IPolicyList Policies => this as IPolicyList; #endregion #region Pipelines public override IStagedStrategyChain<Pipeline, Stage> TypePipeline { get; } public override IStagedStrategyChain<Pipeline, Stage> FactoryPipeline { get; } public override IStagedStrategyChain<Pipeline, Stage> InstancePipeline { get; } #endregion #region Lifetime public override ITypeLifetimeManager TypeLifetimeManager { get => (ITypeLifetimeManager)_typeLifetimeManager; set { _typeLifetimeManager = (LifetimeManager)(value ?? throw new ArgumentNullException(error)); _typeLifetimeManager.InUse = true; } } public override IFactoryLifetimeManager FactoryLifetimeManager { get => (IFactoryLifetimeManager)_factoryLifetimeManager; set { _factoryLifetimeManager = (LifetimeManager)(value ?? throw new ArgumentNullException(error)); _factoryLifetimeManager.InUse = true; } } public override IInstanceLifetimeManager InstanceLifetimeManager { get => (IInstanceLifetimeManager)_instanceLifetimeManager; set { _instanceLifetimeManager = (LifetimeManager)(value ?? throw new ArgumentNullException(error)); _instanceLifetimeManager.InUse = true; } } #endregion } } }
29.859155
114
0.578774
[ "Apache-2.0" ]
danielp37/container
src/UnityContainer/Context/Context.cs
2,122
C#
using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Serializers; using Chinook.Data; using EasyLOB.Persistence; namespace Chinook.Persistence { public static partial class ChinookMongoDBMap { public static void CustomerDocumentMap() { if (!BsonClassMap.IsClassMapRegistered(typeof(CustomerDocument))) { BsonClassMap.RegisterClassMap<CustomerDocument>(map => { map.MapIdProperty(x => x.CustomerDocumentId) .SetIdGenerator(MongoDBInt32IdGenerator.Instance) .SetSerializer(new Int32Serializer(BsonType.String)); map.MapProperty(x => x.CustomerId); map.MapProperty(x => x.Description); map.MapProperty(x => x.FileAcronym); }); } } } }
33.642857
78
0.569002
[ "MIT" ]
EasyLOB/EasyLOB-Chinook-1
Chinook.PersistenceMongoDB/Maps/CustomerDocumentMap.cs
942
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OrbitLayout : MonoBehaviour { public GameObject prefab; public int num = 4; public float radius = 1.5f; public Vector3 axis = Vector3.up; // Use this for initialization void Start () { float angleDiff = 2 * Mathf.PI / num; for(int i = 0; i < num; i++) { GameObject obj = GameObject.Instantiate(prefab, this.transform); float angle = angleDiff * i; obj.transform.localPosition = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius; } } }
25.24
102
0.62599
[ "MIT" ]
kaiware007/UnityVJShaderSlide20181108
Assets/Scripts/OrbitLayout.cs
633
C#
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace FarseerPhysics.Common { public static class TextureConverter { //User contribution from Sickbattery /// <summary> /// TODO: /// 1.) Das Array welches ich bekomme am besten in einen bool array verwandeln. Würde die Geschwindigkeit verbessern /// </summary> private static readonly int[,] ClosePixels = new int[8,2] { {-1, -1}, {0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1} , {-1, 0} }; public static Vertices CreateVertices(uint[] data, int width, int height) { PolygonCreationAssistance pca = new PolygonCreationAssistance(data, width, height); List<Vertices> verts = CreateVertices(pca); return verts[0]; } public static Vertices CreateVertices(uint[] data, int width, int height, bool holeDetection) { PolygonCreationAssistance pca = new PolygonCreationAssistance(data, width, height); pca.HoleDetection = holeDetection; List<Vertices> verts = CreateVertices(pca); return verts[0]; } public static List<Vertices> CreateVertices(uint[] data, int width, int height, float hullTolerance, byte alphaTolerance, bool multiPartDetection, bool holeDetection) { PolygonCreationAssistance pca = new PolygonCreationAssistance(data, width, height); pca.HullTolerance = hullTolerance; pca.AlphaTolerance = alphaTolerance; pca.MultipartDetection = multiPartDetection; pca.HoleDetection = holeDetection; return CreateVertices(pca); } private static List<Vertices> CreateVertices(PolygonCreationAssistance pca) { List<Vertices> polygons = new List<Vertices>(); Vertices polygon; Vertices holePolygon; Vector2? holeEntrance = null; Vector2? polygonEntrance = null; List<Vector2> blackList = new List<Vector2>(); // First of all: Check the array you just got. if (pca.IsValid()) { bool searchOn; do { if (polygons.Count == 0) { polygon = CreateSimplePolygon(pca, Vector2.Zero, Vector2.Zero); if (polygon != null && polygon.Count > 2) { polygonEntrance = GetTopMostVertex(polygon); } } else if (polygonEntrance.HasValue) { polygon = CreateSimplePolygon(pca, polygonEntrance.Value, new Vector2(polygonEntrance.Value.X - 1f, polygonEntrance.Value.Y)); } else { break; } searchOn = false; if (polygon != null && polygon.Count > 2) { if (pca.HoleDetection) { do { holeEntrance = GetHoleHullEntrance(pca, polygon, holeEntrance); if (holeEntrance.HasValue) { if (!blackList.Contains(holeEntrance.Value)) { blackList.Add(holeEntrance.Value); holePolygon = CreateSimplePolygon(pca, holeEntrance.Value, new Vector2(holeEntrance.Value.X + 1, holeEntrance.Value.Y)); if (holePolygon != null && holePolygon.Count > 2) { holePolygon.Add(holePolygon[0]); int vertex2Index; int vertex1Index; if (SplitPolygonEdge(polygon, EdgeAlignment.Vertical, holeEntrance.Value, out vertex1Index, out vertex2Index)) { polygon.InsertRange(vertex2Index, holePolygon); } } } else { break; } } else { break; } } while (true); } polygons.Add(polygon); if (pca.MultipartDetection) { // 1: 95 / 151 // 2: 232 / 252 // while (GetNextHullEntrance(pca, polygonEntrance.Value, out polygonEntrance)) { bool inPolygon = false; for (int i = 0; i < polygons.Count; i++) { polygon = polygons[i]; if (InPolygon(pca, ref polygon, polygonEntrance.Value)) { inPolygon = true; break; } } if (!inPolygon) { searchOn = true; break; } } } } } while (searchOn); } else { throw new Exception( "Sizes don't match: Color array must contain texture width * texture height elements."); } return polygons; } private static Vector2? GetHoleHullEntrance(PolygonCreationAssistance pca, Vertices polygon, Vector2? startVertex) { List<CrossingEdgeInfo> edges = new List<CrossingEdgeInfo>(); Vector2? entrance; int startLine; int endLine; int lastSolid = 0; bool foundSolid; bool foundTransparent; if (polygon != null && polygon.Count > 0) { if (startVertex.HasValue) { startLine = (int) startVertex.Value.Y; } else { startLine = (int) GetTopMostCoord(polygon); } endLine = (int) GetBottomMostCoord(polygon); if (startLine > 0 && startLine < pca.Height && endLine > 0 && endLine < pca.Height) { // go from top to bottom of the polygon for (int y = startLine; y <= endLine; y += pca.HoleDetectionLineStepSize) { // get x-coord of every polygon edge which crosses y edges = GetCrossingEdges(polygon, EdgeAlignment.Vertical, y); // we need an even number of crossing edges if (edges.Count > 1 && edges.Count % 2 == 0) { for (int i = 0; i < edges.Count; i += 2) { foundSolid = false; foundTransparent = false; for (int x = (int) edges[i].CrossingPoint.X; x <= (int) edges[i + 1].CrossingPoint.X; x++) { if (pca.IsSolid(x, y)) { if (!foundTransparent) { foundSolid = true; lastSolid = x; } if (foundSolid && foundTransparent) { entrance = new Vector2(lastSolid, y); if (DistanceToHullAcceptable(pca, polygon, entrance.Value, true)) { return entrance; } entrance = null; break; } } else { if (foundSolid) { foundTransparent = true; } } } } } } } } return null; } private static bool DistanceToHullAcceptable(PolygonCreationAssistance pca, Vertices polygon, Vector2 point, bool higherDetail) { if (polygon != null && polygon.Count > 2) { Vector2 edgeVertex2 = polygon[polygon.Count - 1]; Vector2 edgeVertex1; if (higherDetail) { for (int i = 0; i < polygon.Count; i++) { edgeVertex1 = polygon[i]; if (LineTools.DistanceBetweenPointAndLineSegment(ref point, ref edgeVertex1, ref edgeVertex2) <= pca.HullTolerance || LineTools.DistanceBetweenPointAndPoint(ref point, ref edgeVertex1) <= pca.HullTolerance) { return false; } edgeVertex2 = polygon[i]; } return true; } else { for (int i = 0; i < polygon.Count; i++) { edgeVertex1 = polygon[i]; if (LineTools.DistanceBetweenPointAndLineSegment(ref point, ref edgeVertex1, ref edgeVertex2) <= pca.HullTolerance) { return false; } edgeVertex2 = polygon[i]; } return true; } } return false; } private static bool InPolygon(PolygonCreationAssistance pca, ref Vertices polygon, Vector2 point) { bool inPolygon = !DistanceToHullAcceptable(pca, polygon, point, true); if (!inPolygon) { List<CrossingEdgeInfo> edges = GetCrossingEdges(polygon, EdgeAlignment.Vertical, (int) point.Y); if (edges.Count > 0 && edges.Count % 2 == 0) { for (int i = 0; i < edges.Count; i += 2) { if (edges[i].CrossingPoint.X <= point.X && edges[i + 1].CrossingPoint.X >= point.X) { return true; } } return false; } return false; } return true; } private static Vector2? GetTopMostVertex(Vertices vertices) { float topMostValue = float.MaxValue; Vector2? topMost = null; for (int i = 0; i < vertices.Count; i++) { if (topMostValue > vertices[i].Y) { topMostValue = vertices[i].Y; topMost = vertices[i]; } } return topMost; } private static float GetTopMostCoord(Vertices vertices) { float returnValue = float.MaxValue; for (int i = 0; i < vertices.Count; i++) { if (returnValue > vertices[i].Y) { returnValue = vertices[i].Y; } } return returnValue; } private static float GetBottomMostCoord(Vertices vertices) { float returnValue = float.MinValue; for (int i = 0; i < vertices.Count; i++) { if (returnValue < vertices[i].Y) { returnValue = vertices[i].Y; } } return returnValue; } private static List<CrossingEdgeInfo> GetCrossingEdges(Vertices polygon, EdgeAlignment edgeAlign, int checkLine) { List<CrossingEdgeInfo> edges = new List<CrossingEdgeInfo>(); Vector2 slope; Vector2 edgeVertex1; Vector2 edgeVertex2; Vector2 slopePreview; Vector2 edgeVertexPreview; Vector2 crossingPoint; bool addCrossingPoint; if (polygon.Count > 1) { edgeVertex2 = polygon[polygon.Count - 1]; switch (edgeAlign) { case EdgeAlignment.Vertical: for (int i = 0; i < polygon.Count; i++) { edgeVertex1 = polygon[i]; if ((edgeVertex1.Y >= checkLine && edgeVertex2.Y <= checkLine) || (edgeVertex1.Y <= checkLine && edgeVertex2.Y >= checkLine)) { if (edgeVertex1.Y != edgeVertex2.Y) { addCrossingPoint = true; slope = edgeVertex2 - edgeVertex1; if (edgeVertex1.Y == checkLine) { edgeVertexPreview = polygon[(i + 1) % polygon.Count]; slopePreview = edgeVertex1 - edgeVertexPreview; if (slope.Y > 0) { addCrossingPoint = (slopePreview.Y <= 0); } else { addCrossingPoint = (slopePreview.Y >= 0); } } if (addCrossingPoint) { crossingPoint = new Vector2((checkLine - edgeVertex1.Y) / slope.Y * slope.X + edgeVertex1.X, checkLine); edges.Add(new CrossingEdgeInfo(edgeVertex1, edgeVertex2, crossingPoint, edgeAlign)); } } } edgeVertex2 = edgeVertex1; } break; case EdgeAlignment.Horizontal: throw new Exception("EdgeAlignment.Horizontal isn't implemented yet. Sorry."); } } edges.Sort(); return edges; } private static bool SplitPolygonEdge(Vertices polygon, EdgeAlignment edgeAlign, Vector2 coordInsideThePolygon, out int vertex1Index, out int vertex2Index) { List<CrossingEdgeInfo> edges; Vector2 slope; int nearestEdgeVertex1Index = 0; int nearestEdgeVertex2Index = 0; bool edgeFound = false; float shortestDistance = float.MaxValue; bool edgeCoordFound = false; Vector2 foundEdgeCoord = Vector2.Zero; vertex1Index = 0; vertex2Index = 0; switch (edgeAlign) { case EdgeAlignment.Vertical: edges = GetCrossingEdges(polygon, EdgeAlignment.Vertical, (int) coordInsideThePolygon.Y); foundEdgeCoord.Y = coordInsideThePolygon.Y; if (edges != null && edges.Count > 1 && edges.Count % 2 == 0) { float distance; for (int i = 0; i < edges.Count; i++) { if (edges[i].CrossingPoint.X < coordInsideThePolygon.X) { distance = coordInsideThePolygon.X - edges[i].CrossingPoint.X; if (distance < shortestDistance) { shortestDistance = distance; foundEdgeCoord.X = edges[i].CrossingPoint.X; edgeCoordFound = true; } } } if (edgeCoordFound) { shortestDistance = float.MaxValue; int edgeVertex2Index = polygon.Count - 1; int edgeVertex1Index; for (edgeVertex1Index = 0; edgeVertex1Index < polygon.Count; edgeVertex1Index++) { Vector2 tempVector1 = polygon[edgeVertex1Index]; Vector2 tempVector2 = polygon[edgeVertex2Index]; distance = LineTools.DistanceBetweenPointAndLineSegment(ref foundEdgeCoord, ref tempVector1, ref tempVector2); if (distance < shortestDistance) { shortestDistance = distance; nearestEdgeVertex1Index = edgeVertex1Index; nearestEdgeVertex2Index = edgeVertex2Index; edgeFound = true; } edgeVertex2Index = edgeVertex1Index; } if (edgeFound) { slope = polygon[nearestEdgeVertex2Index] - polygon[nearestEdgeVertex1Index]; slope.Normalize(); Vector2 tempVector = polygon[nearestEdgeVertex1Index]; distance = LineTools.DistanceBetweenPointAndPoint(ref tempVector, ref foundEdgeCoord); vertex1Index = nearestEdgeVertex1Index; vertex2Index = nearestEdgeVertex1Index + 1; polygon.Insert(nearestEdgeVertex1Index, distance * slope + polygon[vertex1Index]); polygon.Insert(nearestEdgeVertex1Index, distance * slope + polygon[vertex2Index]); return true; } } } break; case EdgeAlignment.Horizontal: throw new Exception("EdgeAlignment.Horizontal isn't implemented yet. Sorry."); } return false; } private static Vertices CreateSimplePolygon(PolygonCreationAssistance pca, Vector2 entrance, Vector2 last) { bool entranceFound = false; bool endOfHull = false; Vertices polygon = new Vertices(); Vertices hullArea = new Vertices(); Vertices endOfHullArea = new Vertices(); Vector2 current = Vector2.Zero; #region Entrance check // Get the entrance point. //todo: alle möglichkeiten testen if (entrance == Vector2.Zero || !pca.InBounds(entrance)) { entranceFound = GetHullEntrance(pca, out entrance); if (entranceFound) { current = new Vector2(entrance.X - 1f, entrance.Y); } } else { if (pca.IsSolid(entrance)) { if (IsNearPixel(pca, entrance, last)) { current = last; entranceFound = true; } else { Vector2 temp; if (SearchNearPixels(pca, false, entrance, out temp)) { current = temp; entranceFound = true; } else { entranceFound = false; } } } } #endregion if (entranceFound) { polygon.Add(entrance); hullArea.Add(entrance); Vector2 next = entrance; do { // Search in the pre vision list for an outstanding point. Vector2 outstanding; if (SearchForOutstandingVertex(hullArea, pca.HullTolerance, out outstanding)) { if (endOfHull) { // We have found the next pixel, but is it on the last bit of the hull? if (endOfHullArea.Contains(outstanding)) { // Indeed. polygon.Add(outstanding); } // That's enough, quit. break; } // Add it and remove all vertices that don't matter anymore // (all the vertices before the outstanding). polygon.Add(outstanding); hullArea.RemoveRange(0, hullArea.IndexOf(outstanding)); } // Last point gets current and current gets next. Our little spider is moving forward on the hull ;). last = current; current = next; // Get the next point on hull. if (GetNextHullPoint(pca, ref last, ref current, out next)) { // Add the vertex to a hull pre vision list. hullArea.Add(next); } else { // Quit break; } if (next == entrance && !endOfHull) { // It's the last bit of the hull, search on and exit at next found vertex. endOfHull = true; endOfHullArea.AddRange(hullArea); } } while (true); } return polygon; } private static bool SearchNearPixels(PolygonCreationAssistance pca, bool searchingForSolidPixel, Vector2 current, out Vector2 foundPixel) { int x; int y; for (int i = 0; i < 8; i++) { x = (int) current.X + ClosePixels[i, 0]; y = (int) current.Y + ClosePixels[i, 1]; if (!searchingForSolidPixel ^ pca.IsSolid(x, y)) { foundPixel = new Vector2(x, y); return true; } } // Nothing found. foundPixel = Vector2.Zero; return false; } private static bool IsNearPixel(PolygonCreationAssistance pca, Vector2 current, Vector2 near) { for (int i = 0; i < 8; i++) { int x = (int) current.X + ClosePixels[i, 0]; int y = (int) current.Y + ClosePixels[i, 1]; if (x >= 0 && x <= pca.Width && y >= 0 && y <= pca.Height) { if (x == (int) near.X && y == (int) near.Y) { return true; } } } return false; } private static bool GetHullEntrance(PolygonCreationAssistance pca, out Vector2 entrance) { // Search for first solid pixel. for (int y = 0; y <= pca.Height; y++) { for (int x = 0; x <= pca.Width; x++) { if (pca.IsSolid(x, y)) { entrance = new Vector2(x, y); return true; } } } // If there are no solid pixels. entrance = Vector2.Zero; return false; } private static bool GetNextHullEntrance(PolygonCreationAssistance pca, Vector2 start, out Vector2? entrance) { // Search for first solid pixel. int size = pca.Height * pca.Width; int x; bool foundTransparent = false; for (int i = (int) start.X + (int) start.Y * pca.Width; i <= size; i++) { if (pca.IsSolid(i)) { if (foundTransparent) { x = i % pca.Width; entrance = new Vector2(x, (i - x) / pca.Width); return true; } } else { foundTransparent = true; } } // If there are no solid pixels. entrance = null; return false; } private static bool GetNextHullPoint(PolygonCreationAssistance pca, ref Vector2 last, ref Vector2 current, out Vector2 next) { int x; int y; int indexOfFirstPixelToCheck = GetIndexOfFirstPixelToCheck(last, current); int indexOfPixelToCheck; const int pixelsToCheck = 8; // _closePixels.Length; for (int i = 0; i < pixelsToCheck; i++) { indexOfPixelToCheck = (indexOfFirstPixelToCheck + i) % pixelsToCheck; x = (int) current.X + ClosePixels[indexOfPixelToCheck, 0]; y = (int) current.Y + ClosePixels[indexOfPixelToCheck, 1]; if (x >= 0 && x < pca.Width && y >= 0 && y <= pca.Height) { if (pca.IsSolid(x, y)) //todo { next = new Vector2(x, y); return true; } } } next = Vector2.Zero; return false; } private static bool SearchForOutstandingVertex(Vertices hullArea, float hullTolerance, out Vector2 outstanding) { Vector2 outstandingResult = Vector2.Zero; bool found = false; if (hullArea.Count > 2) { int hullAreaLastPoint = hullArea.Count - 1; Vector2 tempVector1; Vector2 tempVector2 = hullArea[0]; Vector2 tempVector3 = hullArea[hullAreaLastPoint]; // Search between the first and last hull point. for (int i = 1; i < hullAreaLastPoint; i++) { tempVector1 = hullArea[i]; // Check if the distance is over the one that's tolerable. if ( LineTools.DistanceBetweenPointAndLineSegment(ref tempVector1, ref tempVector2, ref tempVector3) >= hullTolerance) { outstandingResult = hullArea[i]; found = true; break; } } } outstanding = outstandingResult; return found; } private static int GetIndexOfFirstPixelToCheck(Vector2 last, Vector2 current) { // .: pixel // l: last position // c: current position // f: first pixel for next search // f . . // l c . // . . . //Calculate in which direction the last move went and decide over the next first pixel. switch ((int) (current.X - last.X)) { case 1: switch ((int) (current.Y - last.Y)) { case 1: return 1; case 0: return 0; case -1: return 7; } break; case 0: switch ((int) (current.Y - last.Y)) { case 1: return 2; case -1: return 6; } break; case -1: switch ((int) (current.Y - last.Y)) { case 1: return 3; case 0: return 4; case -1: return 5; } break; } return 0; } } public enum EdgeAlignment { Vertical = 0, Horizontal = 1 } public sealed class CrossingEdgeInfo : IComparable { #region Attributes private EdgeAlignment _alignment; private Vector2 _crossingPoint; private Vector2 _edgeVertex2; private Vector2 _egdeVertex1; #endregion #region Properties public Vector2 EdgeVertex1 { get { return _egdeVertex1; } set { _egdeVertex1 = value; } } public Vector2 EdgeVertex2 { get { return _edgeVertex2; } set { _edgeVertex2 = value; } } public EdgeAlignment CheckLineAlignment { get { return _alignment; } set { _alignment = value; } } public Vector2 CrossingPoint { get { return _crossingPoint; } set { _crossingPoint = value; } } #endregion #region Constructor public CrossingEdgeInfo(Vector2 edgeVertex1, Vector2 edgeVertex2, Vector2 crossingPoint, EdgeAlignment checkLineAlignment) { _egdeVertex1 = edgeVertex1; _edgeVertex2 = edgeVertex2; _alignment = checkLineAlignment; _crossingPoint = crossingPoint; } #endregion #region IComparable Member public int CompareTo(object obj) { CrossingEdgeInfo cei = (CrossingEdgeInfo) obj; int result = 0; switch (_alignment) { case EdgeAlignment.Vertical: if (_crossingPoint.X < cei.CrossingPoint.X) { result = -1; } else if (_crossingPoint.X > cei.CrossingPoint.X) { result = 1; } break; case EdgeAlignment.Horizontal: if (_crossingPoint.Y < cei.CrossingPoint.Y) { result = -1; } else if (_crossingPoint.Y > cei.CrossingPoint.Y) { result = 1; } break; } return result; } #endregion } /// <summary> /// Class used as a data container and helper for the texture-to-vertices code. /// </summary> public sealed class PolygonCreationAssistance { private byte _alphaTolerance; private uint _alphaToleranceRealValue; private int _holeDetectionLineStepSize; private float _hullTolerance; public PolygonCreationAssistance(uint[] data, int width, int height) { Data = data; Width = width; Height = height; AlphaTolerance = 20; HullTolerance = 1.5f; HoleDetectionLineStepSize = 1; HoleDetection = false; MultipartDetection = false; } private uint[] Data { get; set; } public int Width { get; private set; } public int Height { get; private set; } public byte AlphaTolerance { get { return _alphaTolerance; } set { _alphaTolerance = value; _alphaToleranceRealValue = (uint) value << 24; } } public float HullTolerance { get { return _hullTolerance; } set { float hullTolerance = value; if (hullTolerance > 4f) hullTolerance = 4f; if (hullTolerance < 0.9f) hullTolerance = 0.9f; _hullTolerance = hullTolerance; } } public int HoleDetectionLineStepSize { get { return _holeDetectionLineStepSize; } private set { if (value < 1) { _holeDetectionLineStepSize = 1; } else { if (value > 10) { _holeDetectionLineStepSize = 10; } else { _holeDetectionLineStepSize = value; } } } } public bool HoleDetection { get; set; } public bool MultipartDetection { get; set; } public bool IsSolid(Vector2 pixel) { return IsSolid((int) pixel.X, (int) pixel.Y); } public bool IsSolid(int x, int y) { if (x >= 0 && x < Width && y >= 0 && y < Height) return ((Data[x + y * Width] & 0xFF000000) >= _alphaToleranceRealValue); return false; } public bool IsSolid(int index) { if (index >= 0 && index < Width * Height) return ((Data[index] & 0xFF000000) >= _alphaToleranceRealValue); return false; } public bool InBounds(Vector2 coord) { return (coord.X >= 0f && coord.X < Width && coord.Y >= 0f && coord.Y < Height); } public bool IsValid() { if (Data != null && Data.Length > 0) return Data.Length == Width * Height; return false; } } }
34.712835
124
0.39094
[ "MIT" ]
somethingnew2-0/Pinball
FarseerLibrary/Common/TextureConverter.cs
37,598
C#
using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using $ext_safeprojectname$.Core.Data; using $ext_safeprojectname$.Core.Service; namespace $safeprojectname$ { [TestClass] public class CustomerServiceTests { [TestMethod] public void ShouldGetAllCustomers() { var loggerMock = new Mock<ILogger<CustomerService>>(); var dataService = new DataService("Data Source=..\\..\\..\\..\\$ext_safeprojectname$.Web\\Data\\nwind.sqlite"); var cs = new CustomerService(loggerMock.Object, dataService); var result = cs.getAllCustomers(); Assert.IsTrue(result.Any()); } } }
28.384615
123
0.658537
[ "MIT" ]
miseeger/VisualStudio.Templates
Sources/AspDotNet Core WinAuth WebApi NgClient/NgWebApp.Test/CustomerServiceTests.cs
738
C#
using System; using System.Collections.Generic; using SkiaSharp; namespace Kaemika { public enum Platform { Windows, macOS, Android, iOS, NONE } public enum Noise { None = 0, SigmaRange = 1, Sigma = 2, CV = 3, SigmaSqRange = 4, SigmaSq = 5, Fano = 6 } public class Error : Exception { public Error(string message) : base(message) { } } public class ConstantEvaluation : Exception { public ConstantEvaluation(string message) : base(message) { } } public class ExecutionEnded : Exception { public ExecutionEnded(string message) : base(message) { } } public class Reject : Exception { public Reject() : base("Reject") { } } // ==== PLATFORM-NEUTRAL GRAPHICS ===== public interface Texter { string fontFamily { get; } string fixedFontFamily { get; } } public interface Colorer : Texter { // Colorer implementations hold fonts and paints but do not require a canvas SKTypeface font { get; } SKTypeface fixedFont { get; } SKPaint TextPaint(SKTypeface typeface, float textSize, SKColor color); SKPaint FillPaint(SKColor color); SKPaint LinePaint(float strokeWidth, SKColor color, SKStrokeCap cap = SKStrokeCap.Butt); SKRect MeasureText(string text, SKPaint paint); } public interface Painter : Colorer { // Painter implementations hold a private canvas on which to draw void Clear(SKColor background); void DrawLine(List<SKPoint> points, SKPaint paint); void DrawPolygon(List<SKPoint> points, SKPaint paint); void DrawSpline(List<SKPoint> points, SKPaint paint); void DrawRect(SKRect rect, SKPaint paint); void DrawRoundRect(SKRect rect, float corner, SKPaint paint); void DrawCircle(SKPoint p, float radius, SKPaint paint); void DrawText(string text, SKPoint point, SKPaint paint); } public class PlatformTexter : Texter { //kaemikaFont = new Font("Matura MT Script Capitals", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); //### Android/iOS: GraphLayout does not use a Colorer and does not seem to set a font at all in its text paints //### Android/iOS: for the legend, ChartPage.DataTemplate does not set a font for the Label used to display text //### Android/iOS: otherwise these font families may be used only on chart axes public /*interface Texter*/ string fontFamily { // NO LONGER USED only fixedFontFamily is used, to remove variability of Unicode support // (watch out for GetFont, which has a fixedFont boolean parameter, but only some UI buttons are non-fixedWidth) get { return (Gui.platform == Platform.macOS) ? "Helvetica" : // CGColorer on macOS defers to SKColorer for the fonts (Gui.platform == Platform.Windows) ? "Lucida Sans Unicode" : // "Lucida Sans Unicode" is missing the variant marker "ˬ" (Gui.platform == Platform.iOS) ? "Helvetica" : // Maybe it is never used and default fonts are used (Gui.platform == Platform.Android) ? "Helvetica" : // Maybe it is never used and default fonts are used "Helvetica"; } } public /*interface Texter*/ string fixedFontFamily { get { return (Gui.platform == Platform.macOS) ? "Menlo" : // CGColorer on macOS defers to SKColorer for the fonts (Gui.platform == Platform.Windows) ? "Consolas" : // "Consolas" has variant marker "ˬ"; "Lucida Sans Typewriter": unicode math symbols are too small; "Courier New" is too ugly (Gui.platform == Platform.iOS) ? "Menlo" : // Used by DisEditText. Menlo on iOS seems to lack "ˬ", but only in the Score species names (!?!) (Gui.platform == Platform.Android) ? "DroidSansMono.ttf" : // Used by DisEditText; this need to be placed in assets. Other option: "CutiveMono-Regular.ttf" "Courier"; } } } // ==== PLATFORM-NEUTRAL GUI INTERFACE ===== public class Gui { public static string KaemikaVersion = "1.0.28"; // copy to PreferencesInfoController.cs for macOS public static Platform platform = Platform.NONE; public static void Log(string s) { KGui.gui.GuiOutputAppendText(s + System.Environment.NewLine); if (Exec.lastExecution != null) Exec.lastExecution.netlist.Emit(new CommentEntry(s)); } public static Noise[] noise = (Noise[])Enum.GetValues(typeof(Noise)); private static readonly string[] noiseString = new string[] { " μ", " ±σ", " σ", " σ/μ", " ±σ²", " σ²", " σ²/μ" }; // match order of enum Noise private static readonly string[] longNoiseString = new string[] { " μ (mean)", " ±σ (μ ± standard deviation)", " σ (μ and standard deviation)", " σ/μ (μ and coeff of variation)", " ±σ² (μ ± variance)", " σ² (μ and variance)", " σ²/μ (μ and Fano factor)" }; public static Noise NoiseOfString(string selection) { for (int i = 0; i < noise.Length; i++) { if (selection == noiseString[i] || selection == longNoiseString[i]) return noise[i]; } return Noise.None; // if selection == null } public static string StringOfNoise(Noise noise) { return noiseString[(int)noise]; } public static string FormatUnit(double value, string spacer, string baseUnit, string numberFormat) { if (double.IsNaN(value)) return "NaN"; if (value == 0.0) return value.ToString(numberFormat) + spacer + baseUnit; else if (Math.Abs(value) * 1e12 < 1) return (value * 1e15) .ToString(numberFormat) + spacer + "f" + baseUnit; else if (Math.Abs(value) * 1e9 < 1) return (value * 1e12) .ToString(numberFormat) + spacer + "p" + baseUnit; else if (Math.Abs(value) * 1e6 < 1) return (value * 1e9) .ToString(numberFormat) + spacer + "n" + baseUnit; else if (Math.Abs(value) * 1e3 < 1) return (value * 1e6) .ToString(numberFormat) + spacer + "μ" + baseUnit; else if (Math.Abs(value) < 1) return (value * 1e3) .ToString(numberFormat) + spacer + "m" + baseUnit; else if (Math.Abs(value) * 1e-3 < 1) return (value ) .ToString(numberFormat) + spacer + baseUnit; else if (Math.Abs(value) * 1e-6 < 1) return (value * 1e-3) .ToString(numberFormat) + spacer + "k" + baseUnit; else if (Math.Abs(value) * 1e-9 < 1) return (value * 1e-6) .ToString(numberFormat) + spacer + "M" + baseUnit; else if (Math.Abs(value) * 1e-12 < 1) return (value * 1e-9) .ToString(numberFormat) + spacer + "G" + baseUnit; else if (Math.Abs(value) * 1e-15 < 1) return (value * 1e-12).ToString(numberFormat) + spacer + "T" + baseUnit; else return (value * 1e-15).ToString(numberFormat) + spacer + "P" + baseUnit; } public static string FormatUnit(float value, string spacer, string baseUnit, string numberFormat) { return FormatUnit((double)value, spacer, baseUnit, numberFormat); } public static string FormatUnit(decimal value, string spacer, string baseUnit, string numberFormat) { return FormatUnit((double)value, spacer, baseUnit, numberFormat); } } // Platform-dependent controls to which we attach Gui-thread-run callbacks // This is used only by Win and Mac, that have a common interface logic public interface GuiControls { KButton onOffStop { get; } KButton onOffEval { get; } KButton onOffDevice { get; } KButton onOffDeviceView { get; } KButton onOffFontSizePlus { get; } KButton onOffFontSizeMinus { get; } KButton onOffSave { get; } KButton onOffLoad { get; } KFlyoutMenu menuTutorial { get; } KFlyoutMenu menuNoise { get; } KFlyoutMenu menuOutput { get; } KFlyoutMenu menuExport { get; } KFlyoutMenu menuLegend { get; } KFlyoutMenu menuParameters { get; } KFlyoutMenu menuMath { get; } KFlyoutMenu menuSettings { get; } bool IsShiftDown(); bool IsMicrofluidicsVisible(); void MicrofluidicsVisible(bool on); void MicrofluidicsOn(); void MicrofluidicsOff(); void IncrementFont(float pointSize); void Save(); void Load(); void SetDirectory(); void PrivacyPolicyToClipboard(); void SplashOff(); void SavePreferences(); void SetSnapshotSize(); // set standard size for snapshots } }
54.802469
272
0.613539
[ "MIT" ]
luca-cardelli/KaemikaXM
Kaemika/GuiInterface.cs
8,920
C#
namespace Default_WindowsFormsBlazorApp { partial class Form1 { /// <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.blazorWebView1 = new Microsoft.AspNetCore.Components.WebView.WindowsForms.BlazorWebView(); this.SuspendLayout(); // // blazorWebView1 // this.blazorWebView1.Dock = System.Windows.Forms.DockStyle.Fill; this.blazorWebView1.Location = new System.Drawing.Point(0, 0); this.blazorWebView1.Name = "blazorWebView1"; this.blazorWebView1.Size = new System.Drawing.Size(800, 450); this.blazorWebView1.TabIndex = 0; this.blazorWebView1.Text = "blazorWebView1"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.blazorWebView1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion private Microsoft.AspNetCore.Components.WebView.WindowsForms.BlazorWebView blazorWebView1; } }
35.423729
107
0.57799
[ "Apache-2.0" ]
vincoss/blazor-samples
src/Tutorial_WindowsFormsBlazorApp/Form1.Designer.cs
2,092
C#
namespace BroadcastPlugin.ConfigObjects { public class ConfigChaos { public ushort Duration{ get; set; } public string Message { get; set; } public bool OnlyForCdpAndChi { get; set; } } public class ConfigNtf { public ushort Duration { get; set; } public string Message { get; set; } public string MessageNoscp { get; set; } } public class ConfigScp { public ushort Duration { get; set; } public string Cdp { get; set; } public string CdpMicrohid { get; set; } public string Rsc { get; set; } public string RscMicrohid { get; set; } public string Mtf { get; set; } public string MtfMicrohid { get; set; } public string Chi { get; set; } public string ChiMicrohid { get; set; } public string Tesla { get; set; } public string Nuke { get; set; } public string Decon { get; set; } public string Unknown { get; set; } public string Scp079 { get; set; } } public class ConfigWarhead { public ushort Duration { get; set; } public string Start { get; set; } public string Stop { get; set; } } public class ConfigDecon { public ushort Duration { get; set; } public string Msg_15m { get; set; } public string Msg_10m { get; set; } public string Msg_5m { get; set; } public string Msg_1m { get; set; } public string Msg_30s { get; set; } public string Msg_LockedDown { get; set; } public bool OnlyForLcz { get; set; } } public class ConfigGenerator { public ushort Duration { get; set; } public string Gen1 { get; set; } public string Gen2 { get; set; } public string Gen3 { get; set; } } public class ConfigPlayer { public ushort Duration { get; set; } public string Message { get; set; } } public class ConfigTranslation { public string Scp049 { get; set; } public string Scp079 { get; set; } public string Scp096 { get; set; } public string Scp106 { get; set; } public string Scp173 { get; set; } public string Scp93953 { get; set; } public string Scp93989 { get; set; } } }
33.605634
51
0.554065
[ "MIT" ]
terracorra/BroadcastPlugin
Broadcast/ConfigObjects/ConfigTypes.cs
2,388
C#
#pragma checksum "/app/dotnetapp/Views/Home/Privacy.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d8ddb6bffa5a9b264bf8f89038bf03c234083fd3" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Privacy), @"mvc.1.0.view", @"/Views/Home/Privacy.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Home/Privacy.cshtml", typeof(AspNetCore.Views_Home_Privacy))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "/app/dotnetapp/Views/_ViewImports.cshtml" using dotnetapp; #line default #line hidden #line 2 "/app/dotnetapp/Views/_ViewImports.cshtml" using dotnetapp.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d8ddb6bffa5a9b264bf8f89038bf03c234083fd3", @"/Views/Home/Privacy.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5f8d76102390a0daeb769f29824651608905273a", @"/Views/_ViewImports.cshtml")] public class Views_Home_Privacy : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 1 "/app/dotnetapp/Views/Home/Privacy.cshtml" ViewData["Title"] = "Privacy Policy"; #line default #line hidden BeginContext(50, 4, true); WriteLiteral("<h1>"); EndContext(); BeginContext(55, 17, false); #line 4 "/app/dotnetapp/Views/Home/Privacy.cshtml" Write(ViewData["Title"]); #line default #line hidden EndContext(); BeginContext(72, 69, true); WriteLiteral("</h1>\r\n\r\n<p>Use this page to detail your site\'s privacy policy.</p>\r\n"); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
46.597015
168
0.732543
[ "MIT" ]
speedsticko/project-starterkits
aspnetcore/dotnetapp/obj/Debug/netcoreapp2.2/Razor/Views/Home/Privacy.g.cshtml.cs
3,122
C#