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
using System; using Assets.Code.Bon.Socket; using UnityEngine; namespace Assets.Code.Bon.Nodes.Number { [Serializable] [GraphContextMenuItem("Number", "Mix")] public class MixNode : AbstractNumberNode { [NonSerialized] private Rect labelInput01; [NonSerialized] private Rect labelInput02; [NonSerialized] private Rect labelFactor; [NonSerialized] private InputSocket _inputSocket01; [NonSerialized] private InputSocket _inputSocket02; [NonSerialized] private InputSocket _factorSocket; public MixNode(int id, Graph parent) : base(id, parent) { labelInput01 = new Rect(3, 0, 100, 20); labelInput02 = new Rect(3, 20, 100, 20); labelFactor = new Rect(3, 40, 100, 20); _inputSocket01 = new InputSocket(this, typeof(AbstractNumberNode)); _inputSocket02 = new InputSocket(this, typeof(AbstractNumberNode)); _factorSocket = new InputSocket(this, typeof(AbstractNumberNode)); Sockets.Add(_inputSocket01); Sockets.Add(_inputSocket02); Sockets.Add(_factorSocket); Height = 80; Width = 80; } public override void OnGUI() { GUI.Label(labelInput01, "in 1"); GUI.Label(labelInput02, "in 2"); GUI.Label(labelFactor, "factor (0 - 1)"); } public override void Update() { } public static float Clamp(float value, float min, float max) { return value < min ? min : value > max ? max : value; } public override float GetNumber(OutputSocket outSocket, float x, float y, float z, float seed) { var factorValue = GetInputNumber(_factorSocket, x, y, z, seed); if (float.IsNaN(factorValue)) return float.NaN; // to avoid calc of obsolete values here.. if (factorValue <= 0) return GetInputNumber(_inputSocket01, x, y, z, seed); if (factorValue >= 1) return GetInputNumber(_inputSocket02, x, y, z, seed); float v1 = GetInputNumber(_inputSocket01, x, y, z, seed); float v2 = GetInputNumber(_inputSocket02, x, y, z, seed); v1 = Clamp(v1, 0, 1); v2 = Clamp(v2, 0, 1); if (float.IsNaN(v1) || float.IsNaN(v2)) return float.NaN; return v1 * (1 - factorValue) + v2 * factorValue; } } }
28.671233
96
0.69613
[ "MIT" ]
aphex-/BrotherhoodOfNode
Assets/Code/Bon/Nodes/Number/MixNode.cs
2,095
C#
using System; using System.Xml; using System.Xml.XPath; using FlaUI.Core.AutomationElements; #if NET35 using FlaUI.Core.Tools; #endif namespace FlaUI.Core { /// <summary> /// Custom implementation of a <see cref="XPathNavigator" /> which allows /// selecting items by xpath by using the <see cref="ITreeWalker" />. /// </summary> public class AutomationElementXPathNavigator : XPathNavigator { private const int NoAttributeValue = -1; private readonly AutomationElement _rootElement; private readonly ITreeWalker _treeWalker; private AutomationElement _currentElement; private int _attributeIndex = NoAttributeValue; public AutomationElementXPathNavigator(AutomationElement rootElement) { _treeWalker = rootElement.Automation.TreeWalkerFactory.GetControlViewWalker(); _rootElement = rootElement; _currentElement = rootElement; } private bool IsInAttribute => _attributeIndex != NoAttributeValue; /// <inheritdoc /> public override bool HasAttributes => !IsInAttribute; /// <inheritdoc /> public override string Value => IsInAttribute ? GetAttributeValue(_attributeIndex) : _currentElement.ToString(); /// <inheritdoc /> public override object UnderlyingObject => _currentElement; /// <inheritdoc /> public override XPathNodeType NodeType { get { if (IsInAttribute) { return XPathNodeType.Attribute; } if (_currentElement.Equals(_rootElement)) { return XPathNodeType.Root; } return XPathNodeType.Element; } } /// <inheritdoc /> public override string LocalName => IsInAttribute ? GetAttributeName(_attributeIndex) : _currentElement.Properties.ControlType.ValueOrDefault.ToString(); /// <inheritdoc /> public override string Name => LocalName; /// <inheritdoc /> public override XmlNameTable NameTable => throw new NotImplementedException(); /// <inheritdoc /> public override string NamespaceURI => String.Empty; /// <inheritdoc /> public override string Prefix => String.Empty; /// <inheritdoc /> public override string BaseURI => String.Empty; /// <inheritdoc /> public override bool IsEmptyElement => false; /// <inheritdoc /> public override XPathNavigator Clone() { var clonedObject = new AutomationElementXPathNavigator(_rootElement) { _currentElement = _currentElement, _attributeIndex = _attributeIndex }; return clonedObject; } /// <inheritdoc /> public override bool MoveToFirstAttribute() { if (IsInAttribute) { return false; } _attributeIndex = 0; return true; } /// <inheritdoc /> public override bool MoveToNextAttribute() { if (_attributeIndex >= Enum.GetNames(typeof(ElementAttributes)).Length - 1) { // No more attributes return false; } if (!IsInAttribute) { return false; } _attributeIndex++; return true; } /// <inheritdoc /> public override string GetAttribute(string localName, string namespaceUri) { if (IsInAttribute) { return String.Empty; } var attributeIndex = GetAttributeIndexFromName(localName); if (attributeIndex != NoAttributeValue) { return GetAttributeValue(attributeIndex); } return String.Empty; } /// <inheritdoc /> public override bool MoveToAttribute(string localName, string namespaceUri) { if (IsInAttribute) { return false; } var attributeIndex = GetAttributeIndexFromName(localName); if (attributeIndex != NoAttributeValue) { _attributeIndex = attributeIndex; return true; } return false; } /// <inheritdoc /> public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) => throw new NotImplementedException(); /// <inheritdoc /> public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) => throw new NotImplementedException(); /// <inheritdoc /> public override void MoveToRoot() { _attributeIndex = NoAttributeValue; _currentElement = _rootElement; } /// <inheritdoc /> public override bool MoveToNext() { if (IsInAttribute) { return false; } var nextElement = _treeWalker.GetNextSibling(_currentElement); if (nextElement == null) { return false; } _currentElement = nextElement; return true; } /// <inheritdoc /> public override bool MoveToPrevious() { if (IsInAttribute) { return false; } var previousElement = _treeWalker.GetPreviousSibling(_currentElement); if (previousElement == null) { return false; } _currentElement = previousElement; return true; } /// <inheritdoc /> public override bool MoveToFirstChild() { if (IsInAttribute) { return false; } var childElement = _treeWalker.GetFirstChild(_currentElement); if (childElement == null) { return false; } _currentElement = childElement; return true; } /// <inheritdoc /> public override bool MoveToParent() { if (IsInAttribute) { _attributeIndex = NoAttributeValue; return true; } if (_currentElement.Equals(_rootElement)) { return false; } _currentElement = _treeWalker.GetParent(_currentElement); return true; } /// <inheritdoc /> public override bool MoveTo(XPathNavigator other) { var specificNavigator = other as AutomationElementXPathNavigator; if (specificNavigator == null) { return false; } if (!_rootElement.Equals(specificNavigator._rootElement)) { return false; } _currentElement = specificNavigator._currentElement; _attributeIndex = specificNavigator._attributeIndex; return true; } /// <inheritdoc /> public override bool MoveToId(string id) { return false; } /// <inheritdoc /> public override bool IsSamePosition(XPathNavigator other) { var specificNavigator = other as AutomationElementXPathNavigator; if (specificNavigator == null) { return false; } if (!_rootElement.Equals(specificNavigator._rootElement)) { return false; } return _currentElement.Equals(specificNavigator._currentElement) && _attributeIndex == specificNavigator._attributeIndex; } private string GetAttributeValue(int attributeIndex) { switch ((ElementAttributes)attributeIndex) { case ElementAttributes.AutomationId: return _currentElement.Properties.AutomationId.ValueOrDefault; case ElementAttributes.Name: return _currentElement.Properties.Name.ValueOrDefault; case ElementAttributes.ClassName: return _currentElement.Properties.ClassName.ValueOrDefault; case ElementAttributes.HelpText: return _currentElement.Properties.HelpText.ValueOrDefault; default: throw new ArgumentOutOfRangeException(nameof(attributeIndex)); } } private string GetAttributeName(int attributeIndex) { var name = Enum.GetName(typeof(ElementAttributes), attributeIndex); if (name == null) { throw new ArgumentOutOfRangeException(nameof(attributeIndex)); } return name; } private int GetAttributeIndexFromName(string attributeName) { #if NET35 if (EnumExtensions.TryParse(attributeName, out ElementAttributes parsedValue)) #else if (Enum.TryParse(attributeName, out ElementAttributes parsedValue)) #endif { return (int)parsedValue; } return NoAttributeValue; } private enum ElementAttributes { AutomationId, Name, ClassName, HelpText } } }
31.259868
161
0.552668
[ "MIT" ]
dot4qu/FlaUI
src/FlaUI.Core/AutomationElementXPathNavigator.cs
9,505
C#
using System.Text.Json.Serialization; namespace NgrokSharp.DTO { public partial class TunnelErrorDTO { [JsonPropertyName("error_code")] public long? ErrorCode { get; set; } [JsonPropertyName("status_code")] public long? StatusCode { get; set; } [JsonPropertyName("msg")] public string Msg { get; set; } [JsonPropertyName("details")] public Details Details { get; set; } } public partial class Details { [JsonPropertyName("err")] public string Err { get; set; } } }
22.96
45
0.599303
[ "MIT" ]
entvex/NgrokSharp
NgrokSharp/DTO/TunnelErrorDTO.cs
576
C#
using System; namespace Titan.Blog.Model.DataModel { public partial class SysRoleModuleButton : AggregateRoot { public Guid SysRoleModuleButtonId { get; set; } public Guid? SysRoleId { get; set; } public Guid? SysModuleId { get; set; } public string AvailableButtonJson { get; set; } public int? ModuleType { get; set; } } }
27.071429
60
0.643799
[ "Apache-2.0" ]
HanJunJun/Titan.Blog.WebAPP
Titan.Blog.WebAPP/Titan.Blog.Model/DataModel/SysRoleModuleButton.cs
381
C#
using ModKit; using System.Linq; using UnityEngine; using UnityModManagerNet; using static SolastaCommunityExpansion.Viewers.Displays.ItemsAndCraftingDisplay; using static SolastaCommunityExpansion.Viewers.Displays.RulesDisplay; using static SolastaCommunityExpansion.Viewers.Displays.ToolsDisplay; namespace SolastaCommunityExpansion.Viewers { public class GameplayViewer : IMenuSelectablePage { public string Name => "Gameplay"; public int Priority => 20; private static int selectedPane; private static readonly NamedAction[] actions = { new NamedAction("Rules", DisplayRules), new NamedAction("Items, Crafting & Merchants", DisplayItemsAndCrafting), new NamedAction("Tools", DisplayTools), }; public void OnGUI(UnityModManager.ModEntry modEntry) { UI.Label("Welcome to Solasta Community Expansion".yellow().bold()); UI.Div(); if (Main.Enabled) { var titles = actions.Select((a, i) => i == selectedPane ? a.name.orange().bold() : a.name).ToArray(); UI.SelectionGrid(ref selectedPane, titles, titles.Length, UI.ExpandWidth(true)); GUILayout.BeginVertical("box"); actions[selectedPane].action(); GUILayout.EndVertical(); } } } }
32.534884
117
0.639743
[ "MIT" ]
Holic75/SolastaCommunityExpansion
SolastaCommunityExpansion/Viewers/GameplayViewer.cs
1,401
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. // </auto-generated> namespace Microsoft.Azure.Management.EventHub.Fluent.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Single Namespace item in List or Get Operation /// </summary> [Rest.Serialization.JsonTransformation] public partial class EHNamespaceInner : TrackedResourceInner { /// <summary> /// Initializes a new instance of the EHNamespaceInner class. /// </summary> public EHNamespaceInner() { CustomInit(); } /// <summary> /// Initializes a new instance of the EHNamespaceInner class. /// </summary> /// <param name="location">Resource location</param> /// <param name="tags">Resource tags</param> /// <param name="sku">Properties of sku resource</param> /// <param name="provisioningState">Provisioning state of the /// Namespace.</param> /// <param name="createdAt">The time the Namespace was created.</param> /// <param name="updatedAt">The time the Namespace was updated.</param> /// <param name="serviceBusEndpoint">Endpoint you can use to perform /// Service Bus operations.</param> /// <param name="metricId">Identifier for Azure Insights /// metrics.</param> /// <param name="isAutoInflateEnabled">Value that indicates whether /// AutoInflate is enabled for eventhub namespace.</param> /// <param name="maximumThroughputUnits">Upper limit of throughput /// units when AutoInflate is enabled, value should be within 0 to 20 /// throughput units. ( '0' if AutoInflateEnabled = true)</param> /// <param name="kafkaEnabled">Value that indicates whether Kafka is /// enabled for eventhub namespace.</param> public EHNamespaceInner(string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), Sku sku = default(Sku), string provisioningState = default(string), System.DateTime? createdAt = default(System.DateTime?), System.DateTime? updatedAt = default(System.DateTime?), string serviceBusEndpoint = default(string), string metricId = default(string), bool? isAutoInflateEnabled = default(bool?), int? maximumThroughputUnits = default(int?), bool? kafkaEnabled = default(bool?)) : base(id, name, type, location, tags) { Sku = sku; ProvisioningState = provisioningState; CreatedAt = createdAt; UpdatedAt = updatedAt; ServiceBusEndpoint = serviceBusEndpoint; MetricId = metricId; IsAutoInflateEnabled = isAutoInflateEnabled; MaximumThroughputUnits = maximumThroughputUnits; KafkaEnabled = kafkaEnabled; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets properties of sku resource /// </summary> [JsonProperty(PropertyName = "sku")] public Sku Sku { get; set; } /// <summary> /// Gets provisioning state of the Namespace. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; private set; } /// <summary> /// Gets the time the Namespace was created. /// </summary> [JsonProperty(PropertyName = "properties.createdAt")] public System.DateTime? CreatedAt { get; private set; } /// <summary> /// Gets the time the Namespace was updated. /// </summary> [JsonProperty(PropertyName = "properties.updatedAt")] public System.DateTime? UpdatedAt { get; private set; } /// <summary> /// Gets endpoint you can use to perform Service Bus operations. /// </summary> [JsonProperty(PropertyName = "properties.serviceBusEndpoint")] public string ServiceBusEndpoint { get; private set; } /// <summary> /// Gets identifier for Azure Insights metrics. /// </summary> [JsonProperty(PropertyName = "properties.metricId")] public string MetricId { get; private set; } /// <summary> /// Gets or sets value that indicates whether AutoInflate is enabled /// for eventhub namespace. /// </summary> [JsonProperty(PropertyName = "properties.isAutoInflateEnabled")] public bool? IsAutoInflateEnabled { get; set; } /// <summary> /// Gets or sets upper limit of throughput units when AutoInflate is /// enabled, value should be within 0 to 20 throughput units. ( '0' if /// AutoInflateEnabled = true) /// </summary> [JsonProperty(PropertyName = "properties.maximumThroughputUnits")] public int? MaximumThroughputUnits { get; set; } /// <summary> /// Gets or sets value that indicates whether Kafka is enabled for /// eventhub namespace. /// </summary> [JsonProperty(PropertyName = "properties.kafkaEnabled")] public bool? KafkaEnabled { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Sku != null) { Sku.Validate(); } if (MaximumThroughputUnits > 20) { throw new ValidationException(ValidationRules.InclusiveMaximum, "MaximumThroughputUnits", 20); } if (MaximumThroughputUnits < 0) { throw new ValidationException(ValidationRules.InclusiveMinimum, "MaximumThroughputUnits", 0); } } } }
41.779221
617
0.618433
[ "MIT" ]
Azure/azure-libraries-for-net
src/ResourceManagement/EventHub/Generated/Models/EHNamespaceInner.cs
6,434
C#
//------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ namespace SuperSpam_Html_Flooder.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.888889
151
0.585887
[ "MIT" ]
Marfjeh/SuperSpam
SuperSpam_HTMLFlooder/SuperSpam Html Flooder/Properties/Settings.Designer.cs
1,079
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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild.Build; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using static Microsoft.CodeAnalysis.CSharp.LanguageVersionFacts; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.MSBuild.UnitTests { public class MSBuildWorkspaceTests : MSBuildWorkspaceTestBase { [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestCreateMSBuildWorkspace() { using var workspace = CreateMSBuildWorkspace(); Assert.NotNull(workspace); Assert.NotNull(workspace.Services); Assert.NotNull(workspace.Services.Workspace); Assert.Equal(workspace, workspace.Services.Workspace); Assert.NotNull(workspace.Services.HostServices); Assert.NotNull(workspace.Services.PersistentStorage); Assert.NotNull(workspace.Services.TemporaryStorage); Assert.NotNull(workspace.Services.TextFactory); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SingleProjectSolution() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_MultiProjectSolution() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // verify the dependent project has the correct metadata references (and does not include the output for the project references) var references = vbProject.MetadataReferences.ToList(); Assert.Equal(4, references.Count); var fileNames = new HashSet<string>(references.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath))); Assert.Contains("System.Core.dll", fileNames); Assert.Contains("System.dll", fileNames); Assert.Contains("Microsoft.VisualBasic.dll", fileNames); Assert.Contains("mscorlib.dll", fileNames); // the compilation references should have the metadata reference to the csharp project skeleton assembly var compilation = await vbProject.GetCompilationAsync(); var compReferences = compilation.References.ToList(); Assert.Equal(5, compReferences.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/41456"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(2824, "https://github.com/dotnet/roslyn/issues/2824")] public async Task Test_OpenProjectReferencingPortableProject() { var files = new FileSet( (@"CSharpProject\ReferencesPortableProject.csproj", Resources.ProjectFiles.CSharp.ReferencesPortableProject), (@"CSharpProject\Program.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\PortableProject.csproj", Resources.ProjectFiles.CSharp.PortableProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\ReferencesPortableProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); AssertFailures(workspace); var hasFacades = project.MetadataReferences.OfType<PortableExecutableReference>().Any(r => r.FilePath.Contains("Facade")); Assert.True(hasFacades, userMessage: "Expected to find facades in the project references:" + Environment.NewLine + string.Join(Environment.NewLine, project.MetadataReferences.OfType<PortableExecutableReference>().Select(r => r.FilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_SharedMetadataReferences() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var p0 = solution.Projects.ElementAt(0); var p1 = solution.Projects.ElementAt(1); Assert.NotSame(p0, p1); var p0mscorlib = GetMetadataReference(p0, "mscorlib"); var p1mscorlib = GetMetadataReference(p1, "mscorlib"); Assert.NotNull(p0mscorlib); Assert.NotNull(p1mscorlib); // metadata references to mscorlib in both projects are the same Assert.Same(p0mscorlib, p1mscorlib); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task Test_SharedMetadataReferencesWithAliases() { var projPath1 = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var projPath2 = @"CSharpProject\CSharpProject_ExternAlias2.csproj"; var files = new FileSet( (projPath1, Resources.ProjectFiles.CSharp.ExternAlias), (projPath2, Resources.ProjectFiles.CSharp.ExternAlias2), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath1 = GetSolutionFileName(projPath1); var fullPath2 = GetSolutionFileName(projPath2); using var workspace = CreateMSBuildWorkspace(); var proj1 = await workspace.OpenProjectAsync(fullPath1); var proj2 = await workspace.OpenProjectAsync(fullPath2); var p1Sys1 = GetMetadataReferenceByAlias(proj1, "Sys1"); var p1Sys2 = GetMetadataReferenceByAlias(proj1, "Sys2"); var p2Sys1 = GetMetadataReferenceByAlias(proj2, "Sys1"); var p2Sys3 = GetMetadataReferenceByAlias(proj2, "Sys3"); Assert.NotNull(p1Sys1); Assert.NotNull(p1Sys2); Assert.NotNull(p2Sys1); Assert.NotNull(p2Sys3); // same filepath but different alias so they are not the same instance Assert.NotSame(p1Sys1, p1Sys2); Assert.NotSame(p2Sys1, p2Sys3); // same filepath and alias so they are the same instance Assert.Same(p1Sys1, p2Sys1); var mdp1Sys1 = GetMetadata(p1Sys1); var mdp1Sys2 = GetMetadata(p1Sys2); var mdp2Sys1 = GetMetadata(p2Sys1); var mdp2Sys3 = GetMetadata(p2Sys1); Assert.NotNull(mdp1Sys1); Assert.NotNull(mdp1Sys2); Assert.NotNull(mdp2Sys1); Assert.NotNull(mdp2Sys3); // all references to System.dll share the same metadata bytes Assert.Same(mdp1Sys1.Id, mdp1Sys2.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys1.Id); Assert.Same(mdp1Sys1.Id, mdp2Sys3.Id); } private static MetadataReference GetMetadataReference(Project project, string name) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => mr.FilePath.Contains(name)); private static MetadataReference GetMetadataReferenceByAlias(Project project, string aliasName) => project.MetadataReferences .OfType<PortableExecutableReference>() .SingleOrDefault(mr => !mr.Properties.Aliases.IsDefault && mr.Properties.Aliases.Contains(aliasName)); private static Metadata GetMetadata(MetadataReference metadataReference) => ((PortableExecutableReference)metadataReference).GetMetadata(); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(552981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552981")] public async Task TestOpenSolution_DuplicateProjectGuids() { CreateFiles(GetSolutionWithDuplicatedGuidFiles()); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(831379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/831379")] public async Task GetCompilationWithCircularProjectReferences() { CreateFiles(GetSolutionWithCircularProjectReferences()); var solutionFilePath = GetSolutionFileName("CircularSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Verify we can get compilations for both projects var projects = solution.Projects.ToArray(); // Exactly one of them should have a reference to the other. Which one it is, is unspecced Assert.True(projects[0].ProjectReferences.Any(r => r.ProjectId == projects[1].Id) || projects[1].ProjectReferences.Any(r => r.ProjectId == projects[0].Id)); var compilation1 = await projects[0].GetCompilationAsync(); var compilation2 = await projects[1].GetCompilationAsync(); // Exactly one of them should have a compilation to the other. Which one it is, is unspecced Assert.True(compilation1.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation2) || compilation2.References.OfType<CompilationReference>().Any(c => c.Compilation == compilation1)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOutputFilePaths() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOutputInfo() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.CompilationOutputInfo.AssemblyPath)); Assert.Equal("VisualBasicProject.dll", Path.GetFileName(p2.CompilationOutputInfo.AssemblyPath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesUsesInMemoryGeneratedMetadata() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); var p2 = sol.Projects.First(p => p.Language == LanguageNames.VisualBasic); // prove there is no existing metadata on disk for this project Assert.Equal("CSharpProject.dll", Path.GetFileName(p1.OutputFilePath)); Assert.False(File.Exists(p1.OutputFilePath)); // prove that vb project refers to csharp project via generated metadata (skeleton) assembly. // it should be a MetadataImageReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "CSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCrossLanguageReferencesWithOutOfDateMetadataOnDiskUsesInMemoryGeneratedMetadata() { await PrepareCrossLanguageProjectWithEmittedMetadataAsync(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); // recreate the solution so it will reload from disk using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var p1 = sol.Projects.First(p => p.Language == LanguageNames.CSharp); // update project with top level change that should now invalidate use of metadata from disk var d1 = p1.Documents.First(); var root = await d1.GetSyntaxRootAsync(); var decl = root.DescendantNodes().OfType<CS.Syntax.ClassDeclarationSyntax>().First(); var newDecl = decl.WithIdentifier(CS.SyntaxFactory.Identifier("Pogrom").WithLeadingTrivia(decl.Identifier.LeadingTrivia).WithTrailingTrivia(decl.Identifier.TrailingTrivia)); var newRoot = root.ReplaceNode(decl, newDecl); var newDoc = d1.WithSyntaxRoot(newRoot); p1 = newDoc.Project; var p2 = p1.Solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); // we should now find a MetadataImageReference that was generated instead of a MetadataFileReference var c2 = await p2.GetCompilationAsync(); var pref = c2.References.OfType<PortableExecutableReference>().FirstOrDefault(r => r.Display == "EmittedCSharpProject"); Assert.NotNull(pref); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestInternalsVisibleToSigned() { var solution = await SolutionAsync( Project( ProjectName("Project1"), Sign, Document(string.Format( @"using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(""Project2, PublicKey={0}"")] class C1 {{ }}", PublicKey))), Project( ProjectName("Project2"), Sign, ProjectReference("Project1"), Document(@"class C2 : C1 { }"))); var project2 = solution.GetProjectsByName("Project2").First(); var compilation = await project2.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning) .ToArray(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestVersions() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var sversion = solution.Version; var latestPV = solution.GetLatestProjectVersion(); var project = solution.Projects.First(); var pversion = project.Version; var document = project.Documents.First(); var dversion = await document.GetTextVersionAsync(); var latestDV = await project.GetLatestDocumentVersionAsync(); // update document var solution1 = solution.WithDocumentText(document.Id, SourceText.From("using test;")); var document1 = solution1.GetDocument(document.Id); var dversion1 = await document1.GetTextVersionAsync(); Assert.NotEqual(dversion, dversion1); // new document version Assert.True(dversion1.GetTestAccessor().IsNewerThan(dversion)); Assert.Equal(solution.Version, solution1.Version); // updating document should not have changed solution version Assert.Equal(project.Version, document1.Project.Version); // updating doc should not have changed project version var latestDV1 = await document1.Project.GetLatestDocumentVersionAsync(); Assert.NotEqual(latestDV, latestDV1); Assert.True(latestDV1.GetTestAccessor().IsNewerThan(latestDV)); Assert.Equal(latestDV1, await document1.GetTextVersionAsync()); // projects latest doc version should be this doc's version // update project var solution2 = solution1.WithProjectCompilationOptions(project.Id, project.CompilationOptions.WithOutputKind(OutputKind.NetModule)); var document2 = solution2.GetDocument(document.Id); var dversion2 = await document2.GetTextVersionAsync(); Assert.Equal(dversion1, dversion2); // document didn't change, so version should be the same. Assert.NotEqual(document1.Project.Version, document2.Project.Version); // project did change, so project versions should be different Assert.True(document2.Project.Version.GetTestAccessor().IsNewerThan(document1.Project.Version)); Assert.Equal(solution1.Version, solution2.Version); // solution didn't change, just individual project. // update solution var pid2 = ProjectId.CreateNewId(); var solution3 = solution2.AddProject(pid2, "foo", "foo", LanguageNames.CSharp); Assert.NotEqual(solution2.Version, solution3.Version); // solution changed, added project. Assert.True(solution3.Version.GetTestAccessor().IsNewerThan(solution2.Version)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_LoadMetadataForReferencedProjects() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformDefault() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(33047, "https://github.com/dotnet/roslyn/issues/33047")] public async Task TestOpenProject_CSharp_GlobalPropertyShouldUnsetParentConfigurationAndPlatformTrue() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.ShouldUnsetParentConfigurationAndPlatform) .WithFile(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs", Resources.SourceFiles.CSharp.CSharpClass)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(("ShouldUnsetParentConfigurationAndPlatform", bool.TrueString)); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var expectedFileName = GetSolutionFileName(@"CSharpProject\ShouldUnsetParentConfigurationAndPlatformConditional.cs"); Assert.Equal(expectedFileName, tree.FilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithoutPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndLibrary() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_CSharp_WithPrefer32BitAndWinMDObj() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithPrefer32Bit) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutOutputPath() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithoutAssemblyName() { CreateFiles(GetSimpleCSharpSolutionFiles() .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_CSharp_WithoutCSharpTargetsImported_DocumentsArePickedUp() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithoutCSharpTargetsImported)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutVBTargetsImported_DocumentsArePickedUp() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutVBTargetsImported)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.Documents); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithoutPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithoutPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndConsoleApplication() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu32BitPreferred, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndLibrary() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "Library")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(739043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739043")] public async Task TestOpenProject_VisualBasic_WithPrefer32BitAndWinMDObj() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputType", "winmdobj")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); Assert.Equal(Platform.AnyCpu, compilation.Options.Platform); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutOutputPath() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "OutputPath", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLanguageVersion15_3() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "15.3")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersion.VisualBasic15_3, ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithLatestLanguageVersion() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "LangVersion", "Latest")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Equal(VB.LanguageVersionFacts.MapSpecifiedToEffectiveVersion(VB.LanguageVersion.Latest), ((VB.VisualBasicParseOptions)project.ParseOptions).LanguageVersion); Assert.Equal(VB.LanguageVersion.Latest, ((VB.VisualBasicParseOptions)project.ParseOptions).SpecifiedLanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_WithoutAssemblyName() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.WithPrefer32Bit) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "AssemblyName", "")); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(workspace.Diagnostics); Assert.NotEmpty(project.OutputFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_Respect_ReferenceOutputassembly_Flag() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"VisualBasicProject_Circular_Top.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Top) .WithFile(@"VisualBasicProject_Circular_Target.vbproj", Resources.ProjectFiles.VisualBasic.Circular_Target)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject_Circular_Top.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Empty(project.ProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithXaml() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithXaml) .WithFile(@"CSharpProject\App.xaml", Resources.SourceFiles.Xaml.App) .WithFile(@"CSharpProject\App.xaml.cs", Resources.SourceFiles.CSharp.App) .WithFile(@"CSharpProject\MainWindow.xaml", Resources.SourceFiles.Xaml.MainWindow) .WithFile(@"CSharpProject\MainWindow.xaml.cs", Resources.SourceFiles.CSharp.MainWindow)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // Ensure the Xaml compiler does not run in a separate appdomain. It appears that this won't work within xUnit. using var workspace = CreateMSBuildWorkspace(("AlwaysCompileMarkupFilesInSeparateDomain", "false")); var project = await workspace.OpenProjectAsync(projectFilePath); var documents = project.Documents.ToList(); // AssemblyInfo.cs, App.xaml.cs, MainWindow.xaml.cs, App.g.cs, MainWindow.g.cs, + unusual AssemblyAttributes.cs Assert.Equal(6, documents.Count); // both xaml code behind files are documents Assert.Contains(documents, d => d.Name == "App.xaml.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.xaml.cs"); // prove no xaml files are documents Assert.DoesNotContain(documents, d => d.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase)); // prove that generated source files for xaml files are included in documents list Assert.Contains(documents, d => d.Name == "App.g.cs"); Assert.Contains(documents, d => d.Name == "MainWindow.g.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestMetadataReferenceHasBadHintPath() { // prove that even with bad hint path for metadata reference the workspace can succeed at finding the correct metadata reference. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadHintPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var refs = project.MetadataReferences.ToList(); var csharpLib = refs.OfType<PortableExecutableReference>().FirstOrDefault(r => r.FilePath.Contains("Microsoft.CSharp")); Assert.NotNull(csharpLib); } [ConditionalFact(typeof(VisualStudio16_9_Preview3OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath() { // prove that even if assembly name is specified as a path instead of just a name, workspace still succeeds at opening project. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.GetDirectoryName(project.FilePath); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(project.OutputFilePath)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531631")] public async Task TestOpenProject_AssemblyNameIsPath2() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.AssemblyNameIsPath2)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); Assert.Equal("ReproApp", comp.AssemblyName); var expectedOutputPath = Path.Combine(Path.GetDirectoryName(project.FilePath), @"bin"); Assert.Equal(expectedOutputPath, Path.GetDirectoryName(Path.GetFullPath(project.OutputFilePath))); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithDuplicateFile() { // Verify that we don't throw in this case CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.DuplicateFile)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var documents = project.Documents.Where(d => d.Name == "CSharpClass.cs").ToList(); Assert.Equal(2, documents.Count); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_WithInvalidFileExtension() { // make sure the file does in fact exist, but with an unrecognized extension const string ProjFileName = @"CSharpProject\CSharpProject.csproj.nyi"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(ProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); AssertEx.Throws<InvalidOperationException>(delegate { MSBuildWorkspace.Create().OpenProjectAsync(GetSolutionFileName(ProjFileName)).Wait(); }, (e) => { var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, GetSolutionFileName(ProjFileName), ".nyi"); Assert.Equal(expected, e.Message); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_ProjectFileExtensionAssociatedWithUnknownLanguage() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var language = "lingo"; AssertEx.Throws<InvalidOperationException>(delegate { var ws = MSBuildWorkspace.Create(); ws.AssociateFileExtensionWithLanguage("csproj", language); // non-existent language ws.OpenProjectAsync(projFileName).Wait(); }, (e) => { // the exception should tell us something about the language being unrecognized. var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projFileName, language); Assert.Equal(expected, e.Message); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension1() { // make a CSharp solution with a project file having the incorrect extension 'vbproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.vbproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); workspace.AssociateFileExtensionWithLanguage("vbproj", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithAssociatedLanguageExtension2_IgnoreCase() { // make a CSharp solution with a project file having the incorrect extension 'anyproj', and then load it using the overload the lets us // specify the language directly, instead of inferring from the extension CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.anyproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.anyproj"); using var workspace = CreateMSBuildWorkspace(); // prove that the association works even if the case is different workspace.AssociateFileExtensionWithLanguage("ANYPROJ", LanguageNames.CSharp); var project = await workspace.OpenProjectAsync(projectFilePath); var document = project.Documents.First(); var tree = await document.GetSyntaxTreeAsync(); var diagnostics = tree.GetDiagnostics(); Assert.Empty(diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenSolution_WithNonExistentSolutionFile_Fails() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("NonExistentSolution.sln"); AssertEx.Throws<FileNotFoundException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.OpenSolutionAsync(solutionFilePath).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenSolution_WithInvalidSolutionFile_Fails() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidSolution.sln"); AssertEx.Throws<InvalidOperationException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.OpenSolutionAsync(solutionFilePath).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithTemporaryLockedFile_SucceedsWithoutFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); using var ws = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await ws.OpenSolutionAsync(GetSolutionFileName(@"TestSolution.sln")); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); // start reading text var getTextTask = doc.GetTextAsync(); // wait 1 unit of retry delay then close file var delay = TextLoader.RetryDelay; await Task.Delay(delay).ContinueWith(t => file.Close(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // finish reading text var text = await getTextTask; Assert.NotEmpty(text.ToString()); } finally { file.Close(); } Assert.Empty(ws.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithLockedFile_FailsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); // open source file so it cannot be read by workspace; var sourceFile = GetSolutionFileName(@"CSharpProject\CSharpClass.cs"); var file = File.Open(sourceFile, FileMode.Open, FileAccess.Write, FileShare.None); try { var solution = await workspace.OpenSolutionAsync(solutionFilePath); var doc = solution.Projects.First().Documents.First(d => d.FilePath == sourceFile); var text = await doc.GetTextAsync(); Assert.Empty(text.ToString()); } finally { file.Close(); } Assert.Equal(WorkspaceDiagnosticKind.Failure, workspace.Diagnostics.Single().Kind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithInvalidProjectPath_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [WorkItem(985906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/985906")] [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task HandleSolutionProjectTypeSolutionFolder() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.SolutionFolder)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenSolution_WithInvalidProjectPath_SkipFalse_Fails() { // when not skipped we should get an exception for the invalid project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.InvalidProjectPath)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; AssertEx.Throws<InvalidOperationException>(() => workspace.OpenSolutionAsync(solutionFilePath).Wait()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithNonExistentProject_SkipTrue_SucceedsWithFailureEvent() { // when skipped we should see a diagnostic for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenSolution_WithNonExistentProject_SkipFalse_Fails() { // when skipped we should see an exception for the non-existent project CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.NonExistentProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; AssertEx.Throws<FileNotFoundException>(() => workspace.OpenSolutionAsync(solutionFilePath).Wait()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectFileExtension_Fails() { // proves that for solution open, project type guid and extension are both necessary CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidButRecognizedExtension_Succeeds() { // proves that if project type guid is not recognized, a known project file extension is all we need. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuid)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipTrue_SucceedsWithFailureEvent() { // proves that if both project type guid and file extension are unrecognized, then project is skipped. CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Single(workspace.Diagnostics); Assert.Empty(solution.ProjectIds); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenSolution_WithUnrecognizedProjectTypeGuidAndUnrecognizedExtension_WithSkipFalse_Fails() { // proves that if both project type guid and file extension are unrecognized, then open project fails. const string NoProjFileName = @"CSharpProject\CSharpProject.noproj"; CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"TestSolution.sln", Resources.SolutionFiles.CSharp_UnknownProjectTypeGuidAndUnknownExtension) .WithFile(NoProjFileName, Resources.ProjectFiles.CSharp.CSharpProject)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); AssertEx.Throws<InvalidOperationException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; workspace.OpenSolutionAsync(solutionFilePath).Wait(); }, e => { var noProjFullFileName = GetSolutionFileName(NoProjFileName); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, noProjFullFileName, ".noproj"); Assert.Equal(expected, e.Message); }); } private readonly IEnumerable<Assembly> _defaultAssembliesWithoutCSharp = MefHostServices.DefaultAssemblies.Where(a => !a.FullName.Contains("CSharp")); [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public void TestOpenSolution_WithMissingLanguageLibraries_WithSkipFalse_Throws() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); AssertEx.Throws<InvalidOperationException>(() => { using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = false; workspace.OpenSolutionAsync(solutionFilePath).Wait(); }, e => { var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, e.Message); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public async Task TestOpenSolution_WithMissingLanguageLibraries_WithSkipTrue_SucceedsWithDiagnostic() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); workspace.SkipUnrecognizedProjects = true; var solution = await workspace.OpenSolutionAsync(solutionFilePath); var projFileName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projFileName, ".csproj"); Assert.Equal(expected, workspace.Diagnostics.Single().Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(3931, "https://github.com/dotnet/roslyn/issues/3931")] public void TestOpenProject_WithMissingLanguageLibraries_Throws() { // proves that if the language libraries are missing then the appropriate error occurs CreateFiles(GetSimpleCSharpSolutionFiles()); var projectName = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = MSBuildWorkspace.Create(MefHostServices.Create(_defaultAssembliesWithoutCSharp)); AssertEx.Throws<InvalidOperationException>(() => { var project = workspace.OpenProjectAsync(projectName).Result; }, e => { var expected = string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectName, ".csproj"); Assert.Equal(expected, e.Message); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_WithInvalidFilePath_Fails() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"http://localhost/Invalid/InvalidProject.csproj"); AssertEx.Throws<InvalidOperationException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.OpenProjectAsync(projectFilePath).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_WithNonExistentProjectFile_Fails() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projectFilePath = GetSolutionFileName(@"CSharpProject\NonExistentProject.csproj"); AssertEx.Throws<FileNotFoundException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.OpenProjectAsync(projectFilePath).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithInvalidProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_WithInvalidProjectReference_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.InvalidProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); AssertEx.Throws<InvalidOperationException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; workspace.OpenProjectAsync(projectFilePath).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithNonExistentProjectReference_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to invalid file path. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_WithNonExistentProjectReference_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.NonExistentProjectReference)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); AssertEx.Throws<FileNotFoundException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; workspace.OpenProjectAsync(projectFilePath).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipTrue_SucceedsWithEvent() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); // didn't really open referenced project due to unrecognized extension. Assert.Empty(project.ProjectReferences); // no resolved project references Assert.Single(project.AllProjectReferences); // dangling project reference Assert.NotEmpty(workspace.Diagnostics); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_SkipFalse_Fails() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); AssertEx.Throws<InvalidOperationException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; workspace.OpenProjectAsync(projectFilePath).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipTrue_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); var metaRefs = project.MetadataReferences.ToList(); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_WithMetadata_SkipFalse_SucceedsByLoadingMetadata() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.ProjectFiles.CSharp.CSharpProject) .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = false; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Empty(project.AllProjectReferences); Assert.Contains(project.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithUnrecognizedProjectReferenceFileExtension_BadMsbuildProject_SkipTrue_SucceedsWithDanglingProjectReference() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.UnknownProjectExtension) .WithFile(@"CSharpProject\CSharpProject.noproj", Resources.Dlls.CSharpProject)); // use metadata file as stand-in for bad project file var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.SkipUnrecognizedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); Assert.Single(project.Solution.ProjectIds); Assert.Empty(project.ProjectReferences); Assert.Single(project.AllProjectReferences); Assert.InRange(workspace.Diagnostics.Count, 2, 3); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_ExistingMetadata_Succeeds() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project got converted to a metadata reference var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Empty(projRefs); Assert.Contains(metaRefs, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WithReferencedProject_LoadMetadata_NonExistentMetadata_LoadsProjectInstead() { CreateFiles(GetMultiProjectSolutionFiles()); var projectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var project = await workspace.OpenProjectAsync(projectFilePath); // referenced project is still a project ref, did not get converted to metadata ref var projRefs = project.ProjectReferences.ToList(); var metaRefs = project.MetadataReferences.ToList(); Assert.Single(projRefs); Assert.DoesNotContain(metaRefs, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_UpdateExistingReferences() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\bin\Debug\CSharpProject.dll", Resources.Dlls.CSharpProject)); var vbProjectFilePath = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var csProjectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; // first open vb project that references c# project, but only reference the c# project's built metadata using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); // prove vb project references c# project as a metadata reference Assert.Empty(vbProject.ProjectReferences); Assert.Contains(vbProject.MetadataReferences, r => r is PortableExecutableReference reference && reference.Display.Contains("CSharpProject.dll")); // now explicitly open the c# project that got referenced as metadata var csProject = await workspace.OpenProjectAsync(csProjectFilePath); // show that the vb project now references the c# project directly (not as metadata) vbProject = workspace.CurrentSolution.GetProject(vbProject.Id); Assert.Single(vbProject.ProjectReferences); Assert.DoesNotContain(vbProject.MetadataReferences, r => r.Properties.Aliases.Contains("CSharpProject")); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(Framework35Installed))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(528984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528984")] public async Task TestOpenProject_AddVBDefaultReferences() { var files = new FileSet( ("VisualBasicProject_3_5.vbproj", Resources.ProjectFiles.VisualBasic.VisualBasicProject_3_5), ("VisualBasicProject_VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass)); CreateFiles(files); var projectFilePath = GetSolutionFileName("VisualBasicProject_3_5.vbproj"); // keep metadata reference from holding files open Workspace.TestHookStandaloneProjectsDoNotHoldReferences = true; using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); var compilation = await project.GetCompilationAsync(); var diagnostics = compilation.GetDiagnostics(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Full() { CreateCSharpFilesWith("DebugType", "full"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_None() { CreateCSharpFilesWith("DebugType", "none"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_PDBOnly() { CreateCSharpFilesWith("DebugType", "pdbonly"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Portable() { CreateCSharpFilesWith("DebugType", "portable"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_DebugType_Embedded() { CreateCSharpFilesWith("DebugType", "embedded"); await AssertCSParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_DynamicallyLinkedLibrary() { CreateCSharpFilesWith("OutputType", "Library"); await AssertCSCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_ConsoleApplication() { CreateCSharpFilesWith("OutputType", "Exe"); await AssertCSCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_WindowsApplication() { CreateCSharpFilesWith("OutputType", "WinExe"); await AssertCSCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OutputKind_NetModule() { CreateCSharpFilesWith("OutputType", "Module"); await AssertCSCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Release() { CreateCSharpFilesWith("Optimize", "True"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Release, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_OptimizationLevel_Debug() { CreateCSharpFilesWith("Optimize", "False"); await AssertCSCompilationOptionsAsync(OptimizationLevel.Debug, options => options.OptimizationLevel); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_MainFileName() { CreateCSharpFilesWith("StartupObject", "Foo"); await AssertCSCompilationOptionsAsync("Foo", options => options.MainTypeName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_Missing() { CreateCSharpFiles(); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_False() { CreateCSharpFilesWith("SignAssembly", "false"); await AssertCSCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_SignAssembly_True() { CreateCSharpFilesWith("SignAssembly", "true"); await AssertCSCompilationOptionsAsync("snKey.snk", options => Path.GetFileName(options.CryptoKeyFile)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_False() { CreateCSharpFilesWith("DelaySign", "false"); await AssertCSCompilationOptionsAsync(null, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_AssemblyOriginatorKeyFile_DelaySign_True() { CreateCSharpFilesWith("DelaySign", "true"); await AssertCSCompilationOptionsAsync(true, options => options.DelaySign); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_True() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "true"); await AssertCSCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_CSharp_CheckOverflow_False() { CreateCSharpFilesWith("CheckForOverflowUnderflow", "false"); await AssertCSCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA1() { CreateCSharpFilesWith("LangVersion", "ISO-1"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp1, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_ECMA2() { CreateCSharpFilesWith("LangVersion", "ISO-2"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp2, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_Compatibility_None() { CreateCSharpFilesWith("LangVersion", "3"); await AssertCSParseOptionsAsync(CS.LanguageVersion.CSharp3, options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_LanguageVersion_Default() { CreateCSharpFiles(); await AssertCSParseOptionsAsync(CS.LanguageVersion.Default.MapSpecifiedToEffectiveVersion(), options => options.LanguageVersion); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_CSharp_PreprocessorSymbols() { CreateCSharpFilesWith("DefineConstants", "DEBUG;TRACE;X;Y"); await AssertCSParseOptionsAsync("DEBUG,TRACE,X,Y", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationDebug() { CreateCSharpFiles(); await AssertCSParseOptionsAsync("DEBUG,TRACE", options => string.Join(",", options.PreprocessorSymbolNames)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestConfigurationRelease() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(("Configuration", "Release")); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.Projects.First(); var options = project.ParseOptions; Assert.DoesNotContain(options.PreprocessorSymbolNames, name => name == "DEBUG"); Assert.Contains(options.PreprocessorSymbolNames, name => name == "TRACE"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Full() { CreateVBFilesWith("DebugType", "full"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_None() { CreateVBFilesWith("DebugType", "none"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_PDBOnly() { CreateVBFilesWith("DebugType", "pdbonly"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Portable() { CreateVBFilesWith("DebugType", "portable"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_DebugType_Embedded() { CreateVBFilesWith("DebugType", "embedded"); await AssertVBParseOptionsAsync(0, options => options.Errors.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_VBRuntime_Embed() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicProject.vbproj", Resources.ProjectFiles.VisualBasic.Embed)); await AssertVBCompilationOptionsAsync(true, options => options.EmbedVbCoreRuntime); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_DynamicallyLinkedLibrary() { CreateVBFilesWith("OutputType", "Library"); await AssertVBCompilationOptionsAsync(OutputKind.DynamicallyLinkedLibrary, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_ConsoleApplication() { CreateVBFilesWith("OutputType", "Exe"); await AssertVBCompilationOptionsAsync(OutputKind.ConsoleApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_WindowsApplication() { CreateVBFilesWith("OutputType", "WinExe"); await AssertVBCompilationOptionsAsync(OutputKind.WindowsApplication, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OutputKind_NetModule() { CreateVBFilesWith("OutputType", "Module"); await AssertVBCompilationOptionsAsync(OutputKind.NetModule, options => options.OutputKind); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_RootNamespace() { CreateVBFilesWith("RootNamespace", "Foo.Bar"); await AssertVBCompilationOptionsAsync("Foo.Bar", options => options.RootNamespace); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_On() { CreateVBFilesWith("OptionStrict", "On"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.On, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Off() { CreateVBFilesWith("OptionStrict", "Off"); // The VBC MSBuild task specifies '/optionstrict:custom' rather than '/optionstrict-' // See https://github.com/dotnet/roslyn/blob/58f44c39048032c6b823ddeedddd20fa589912f5/src/Compilers/Core/MSBuildTask/Vbc.cs#L390-L418 for details. await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionStrict_Custom() { CreateVBFilesWith("OptionStrictType", "Custom"); await AssertVBCompilationOptionsAsync(VB.OptionStrict.Custom, options => options.OptionStrict); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_True() { CreateVBFilesWith("OptionInfer", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionInfer_False() { CreateVBFilesWith("OptionInfer", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionInfer); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_True() { CreateVBFilesWith("OptionExplicit", "On"); await AssertVBCompilationOptionsAsync(true, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionExplicit_False() { CreateVBFilesWith("OptionExplicit", "Off"); await AssertVBCompilationOptionsAsync(false, options => options.OptionExplicit); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_True() { CreateVBFilesWith("OptionCompare", "Text"); await AssertVBCompilationOptionsAsync(true, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionCompareText_False() { CreateVBFilesWith("OptionCompare", "Binary"); await AssertVBCompilationOptionsAsync(false, options => options.OptionCompareText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_True() { CreateVBFilesWith("RemoveIntegerChecks", "true"); await AssertVBCompilationOptionsAsync(false, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionRemoveIntegerOverflowChecks_False() { CreateVBFilesWith("RemoveIntegerChecks", "false"); await AssertVBCompilationOptionsAsync(true, options => options.CheckOverflow); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_OptionAssemblyOriginatorKeyFile_SignAssemblyFalse() { CreateVBFilesWith("SignAssembly", "false"); await AssertVBCompilationOptionsAsync(null, options => options.CryptoKeyFile); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestCompilationOptions_VisualBasic_GlobalImports() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicCompilationOptions)project.CompilationOptions; var imports = options.GlobalImports; AssertEx.Equal( expected: new[] { "Microsoft.VisualBasic", "System", "System.Collections", "System.Collections.Generic", "System.Diagnostics", "System.Linq", }, actual: imports.Select(i => i.Name)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestParseOptions_VisualBasic_PreprocessorSymbols() { CreateFiles(GetMultiProjectSolutionFiles() .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "X=1,Y=2,Z,T=-1,VBC_VER=123,F=false")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; var defines = new List<KeyValuePair<string, object>>(options.PreprocessorSymbols); defines.Sort((x, y) => x.Key.CompareTo(y.Key)); AssertEx.Equal( expected: new[] { new KeyValuePair<string, object>("_MyType", "Windows"), new KeyValuePair<string, object>("CONFIG", "Debug"), new KeyValuePair<string, object>("DEBUG", -1), new KeyValuePair<string, object>("F", false), new KeyValuePair<string, object>("PLATFORM", "AnyCPU"), new KeyValuePair<string, object>("T", -1), new KeyValuePair<string, object>("TARGET", "library"), new KeyValuePair<string, object>("TRACE", -1), new KeyValuePair<string, object>("VBC_VER", 123), new KeyValuePair<string, object>("X", 1), new KeyValuePair<string, object>("Y", 2), new KeyValuePair<string, object>("Z", true), }, actual: defines); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes) .ReplaceFileElement(@"VisualBasicProject\VisualBasicProject.vbproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.True(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_VisualBasic_ConditionalAttributeNotEmitted() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"VisualBasicProject\VisualBasicClass.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("VisualBasicProject").FirstOrDefault(); var options = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.False(options.PreprocessorSymbolNames.Contains("EnableMyAttribute")); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttribute"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DefineConstants", "EnableMyAttribute")); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.Contains("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.Contains(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task Test_CSharp_ConditionalAttributeNotEmitted() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass_WithConditionalAttributes)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(solutionFilePath); var project = sol.GetProjectsByName("CSharpProject").FirstOrDefault(); var options = project.ParseOptions; Assert.DoesNotContain("EnableMyAttribute", options.PreprocessorSymbolNames); var compilation = await project.GetCompilationAsync(); var metadataBytes = compilation.EmitToArray(); var mtref = MetadataReference.CreateFromImage(metadataBytes); var mtcomp = CS.CSharpCompilation.Create("MT", references: new MetadataReference[] { mtref }); var sym = (IAssemblySymbol)mtcomp.GetAssemblyOrModuleSymbol(mtref); var attrs = sym.GetAttributes(); Assert.DoesNotContain(attrs, ad => ad.AttributeClass.Name == "MyAttr"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithLinkedDocument() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithLink) .WithFile(@"OtherStuff\Foo.cs", Resources.SourceFiles.CSharp.OtherStuff_Foo)); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project.Documents.ToList(); var fooDoc = documents.Single(d => d.Name == "Foo.cs"); var folder = Assert.Single(fooDoc.Folders); Assert.Equal("Blah", folder); // prove that the file path is the correct full path to the actual file Assert.Contains("OtherStuff", fooDoc.FilePath); Assert.True(File.Exists(fooDoc.FilePath)); var text = File.ReadAllText(fooDoc.FilePath); Assert.Equal(Resources.SourceFiles.CSharp.OtherStuff_Foo, text); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newText = SourceText.From("public class Bar { }"); workspace.AddDocument(project.Id, new string[] { "NewFolder" }, "Bar.cs", newText); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(4, documents.Count); var document2 = documents.Single(d => d.Name == "Bar.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); Assert.Single(document2.Folders); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check project file on disk var projectFileText = File.ReadAllText(project2.FilePath); Assert.Contains(@"NewFolder\Bar.cs", projectFileText); // reload project & solution to prove project file change was good using var workspaceB = CreateMSBuildWorkspace(); var solutionB = await workspaceB.OpenSolutionAsync(solutionFilePath); var projectB = workspaceB.CurrentSolution.GetProjectsByName("CSharpProject").FirstOrDefault(); var documentsB = projectB.Documents.ToList(); Assert.Equal(4, documentsB.Count); var documentB = documentsB.Single(d => d.Name == "Bar.cs"); Assert.Single(documentB.Folders); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestUpdateDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); var newText = SourceText.From("public class Bar { }"); workspace.TryApplyChanges(solution.WithDocumentText(document.Id, newText, PreservationMode.PreserveIdentity)); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); var documents = project2.Documents.ToList(); Assert.Equal(3, documents.Count); var document2 = documents.Single(d => d.Name == "CSharpClass.cs"); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestRemoveDocumentAsync() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var document = project.Documents.Single(d => d.Name == "CSharpClass.cs"); var originalText = await document.GetTextAsync(); workspace.RemoveDocument(document.Id); // check workspace current solution var solution2 = workspace.CurrentSolution; var project2 = solution2.GetProjectsByName("CSharpProject").FirstOrDefault(); Assert.DoesNotContain(project2.Documents, d => d.Name == "CSharpClass.cs"); // check actual file on disk... Assert.False(File.Exists(document.FilePath)); // check original text in original solution did not change var text = await document.GetTextAsync(); Assert.Equal(originalText.ToString(), text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_UpdateDocumentText() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var documents = solution.GetProjectsByName("CSharpProject").FirstOrDefault().Documents.ToList(); var document = documents.Single(d => d.Name.Contains("CSharpClass")); var text = await document.GetTextAsync(); var newText = SourceText.From("using System.Diagnostics;\r\n" + text.ToString()); var newSolution = solution.WithDocumentText(document.Id, newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(document.Id); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_AddDocument() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.GetProjectsByName("CSharpProject").FirstOrDefault(); var newDocId = DocumentId.CreateNewId(project.Id); var newText = SourceText.From("public class Bar { }"); var newSolution = solution.AddDocument(newDocId, "Bar.cs", newText); workspace.TryApplyChanges(newSolution); // check workspace current solution var solution2 = workspace.CurrentSolution; var document2 = solution2.GetDocument(newDocId); var text2 = await document2.GetTextAsync(); Assert.Equal(newText.ToString(), text2.ToString()); // check actual file on disk... var textOnDisk = File.ReadAllText(document2.FilePath); Assert.Equal(newText.ToString(), textOnDisk); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestApplyChanges_NotSupportedChangesFail() { var csharpProjPath = @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"; var vbProjPath = @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj"; CreateFiles(GetAnalyzerReferenceSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var csProjectFilePath = GetSolutionFileName(csharpProjPath); var csProject = await workspace.OpenProjectAsync(csProjectFilePath); var csProjectId = csProject.Id; var vbProjectFilePath = GetSolutionFileName(vbProjPath); var vbProject = await workspace.OpenProjectAsync(vbProjectFilePath); var vbProjectId = vbProject.Id; // adding additional documents not supported. Assert.False(workspace.CanApplyChange(ApplyChangesKind.AddAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.AddAdditionalDocument(DocumentId.CreateNewId(csProjectId), "foo.xaml", SourceText.From("<foo></foo>"))); }); var xaml = workspace.CurrentSolution.GetProject(csProjectId).AdditionalDocuments.FirstOrDefault(d => d.Name == "XamlFile.xaml"); Assert.NotNull(xaml); // removing additional documents not supported Assert.False(workspace.CanApplyChange(ApplyChangesKind.RemoveAdditionalDocument)); Assert.Throws<NotSupportedException>(delegate { workspace.TryApplyChanges(workspace.CurrentSolution.RemoveAdditionalDocument(xaml.Id)); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWaiter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWaiter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestWorkspaceChangedWeakEvent() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); var expectedEventKind = WorkspaceChangeKind.DocumentChanged; var originalSolution = workspace.CurrentSolution; using var eventWanter = workspace.VerifyWorkspaceChangedEvent(args => { Assert.Equal(expectedEventKind, args.Kind); Assert.NotNull(args.NewSolution); Assert.NotSame(originalSolution, args.NewSolution); }); // change document text (should fire SolutionChanged event) var doc = workspace.CurrentSolution.Projects.First().Documents.First(); var text = await doc.GetTextAsync(); var newText = "/* new text */\r\n" + text.ToString(); workspace.TryApplyChanges( workspace .CurrentSolution .WithDocumentText( doc.Id, SourceText.From(newText), PreservationMode.PreserveIdentity)); Assert.True(eventWanter.WaitForEventToFire(AsyncEventTimeout), string.Format("event {0} was not fired within {1}", Enum.GetName(typeof(WorkspaceChangeKind), expectedEventKind), AsyncEventTimeout)); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(529276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529276"), WorkItem(12086, "DevDiv_Projects/Roslyn")] public async Task TestOpenProject_LoadMetadataForReferenceProjects_NoMetadata() { var projPath = @"CSharpProject\CSharpProject_ProjectReference.csproj"; var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var projectFullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); workspace.LoadMetadataForReferencedProjects = true; var proj = await workspace.OpenProjectAsync(projectFullPath); // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); // and all is well var comp = await proj.GetCompilationAsync(); var errs = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error); Assert.Empty(errs); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(918072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918072")] public async Task TestAnalyzerReferenceLoadStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); Assert.Equal(1, proj.AnalyzerReferences.Count); var analyzerReference = proj.AnalyzerReferences[0] as AnalyzerFileReference; Assert.NotNull(analyzerReference); Assert.True(analyzerReference.FullPath.EndsWith("CSharpProject.dll", StringComparison.OrdinalIgnoreCase)); } // prove that project gets opened instead. Assert.Equal(2, workspace.CurrentSolution.Projects.Count()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAdditionalFilesStandalone() { var projPaths = new[] { @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj", @"AnalyzerSolution\VisualBasicProject_AnalyzerReference.vbproj" }; var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); foreach (var projectPath in projPaths) { var projectFullPath = GetSolutionFileName(projectPath); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = Assert.Single(proj.AdditionalDocuments); Assert.Equal("XamlFile.xaml", doc.Name); var text = await doc.GetTextAsync(); Assert.Contains("Window", text.ToString(), StringComparison.Ordinal); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestLoadTextSync() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = new AdhocWorkspace(MSBuildMefHostServices.DefaultServices, WorkspaceKind.MSBuild); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var loader = new MSBuildProjectLoader(workspace); var infos = await loader.LoadProjectInfoAsync(projectFullPath); var doc = infos[0].Documents[0]; var tav = doc.TextLoader.LoadTextAndVersionSynchronously(workspace, doc.Id, CancellationToken.None); var adoc = infos[0].AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atav = adoc.TextLoader.LoadTextAndVersionSynchronously(workspace, adoc.Id, CancellationToken.None); Assert.Contains("Window", atav.Text.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestGetTextSynchronously() { var files = GetAnalyzerReferenceSolutionFiles(); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj"); var proj = await workspace.OpenProjectAsync(projectFullPath); var doc = proj.Documents.First(); var text = doc.State.GetTextSynchronously(CancellationToken.None); var adoc = proj.AdditionalDocuments.First(a => a.Name == "XamlFile.xaml"); var atext = adoc.State.GetTextSynchronously(CancellationToken.None); Assert.Contains("Window", atext.ToString(), StringComparison.Ordinal); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(546171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546171")] public async Task TestCSharpExternAlias() { var projPath = @"CSharpProject\CSharpProject_ExternAlias.csproj"; var files = new FileSet( (projPath, Resources.ProjectFiles.CSharp.ExternAlias), (@"CSharpProject\CSharpExternAlias.cs", Resources.SourceFiles.CSharp.CSharpExternAlias)); CreateFiles(files); var fullPath = GetSolutionFileName(projPath); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(fullPath); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(530337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530337")] public async Task TestProjectReferenceWithExternAlias() { var files = GetProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); var proj = sol.Projects.First(); var comp = await proj.GetCompilationAsync(); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithReferenceOutputAssemblyFalse() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Add(new XElement(XName.Get("ReferenceOutputAssembly", MSBuildNamespace), "false"))); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.Empty(project.ProjectReferences); } } private static FileSet VisitProjectReferences(FileSet files, Action<XElement> visitProjectReference) { var result = new List<(string, object)>(); foreach (var (fileName, fileContent) in files) { var text = fileContent.ToString(); if (fileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase)) { text = VisitProjectReferences(text, visitProjectReference); } result.Add((fileName, text)); } return new FileSet(result.ToArray()); } private static string VisitProjectReferences(string projectFileText, Action<XElement> visitProjectReference) { var document = XDocument.Parse(projectFileText); var projectReferenceItems = document.Descendants(XName.Get("ProjectReference", MSBuildNamespace)); foreach (var projectReferenceItem in projectReferenceItems) { visitProjectReference(projectReferenceItem); } return document.ToString(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestProjectReferenceWithNoGuid() { var files = GetProjectReferenceSolutionFiles(); files = VisitProjectReferences( files, r => r.Elements(XName.Get("Project", MSBuildNamespace)).Remove()); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var sol = await workspace.OpenSolutionAsync(fullPath); foreach (var project in sol.Projects) { Assert.InRange(project.ProjectReferences.Count(), 0, 1); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/23685"), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(5668, "https://github.com/dotnet/roslyn/issues/5668")] public async Task TestOpenProject_MetadataReferenceHasDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("System.Console"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_HasSourceDocComments() { CreateFiles(GetSimpleCSharpSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var parseOptions = (CS.CSharpParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Parse, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_VisualBasic_HasSourceDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var parseOptions = (VB.VisualBasicParseOptions)project.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, parseOptions.DocumentationMode); var comp = await project.GetCompilationAsync(); var symbol = comp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var docComment = symbol.GetDocumentationCommentXml(); Assert.NotNull(docComment); Assert.NotEmpty(docComment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CrossLanguageSkeletonReferenceHasDocComments() { CreateFiles(GetMultiProjectSolutionFiles()); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var csproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.CSharp); var csoptions = (CS.CSharpParseOptions)csproject.ParseOptions; Assert.Equal(DocumentationMode.Parse, csoptions.DocumentationMode); var cscomp = await csproject.GetCompilationAsync(); var cssymbol = cscomp.GetTypeByMetadataName("CSharpProject.CSharpClass"); var cscomment = cssymbol.GetDocumentationCommentXml(); Assert.NotNull(cscomment); var vbproject = workspace.CurrentSolution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var vboptions = (VB.VisualBasicParseOptions)vbproject.ParseOptions; Assert.Equal(DocumentationMode.Diagnose, vboptions.DocumentationMode); var vbcomp = await vbproject.GetCompilationAsync(); var vbsymbol = vbcomp.GetTypeByMetadataName("VisualBasicProject.VisualBasicClass"); var parent = vbsymbol.BaseType; // this is the vb imported version of the csharp symbol var vbcomment = parent.GetDocumentationCommentXml(); Assert.Equal(cscomment, vbcomment); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_WithProjectFileLocked() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using (File.Open(projectFile, FileMode.Open, FileAccess.ReadWrite)) { AssertEx.Throws<IOException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.OpenProjectAsync(projectFile).Wait(); }); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenProject_WithNonExistentProjectFile() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var projectFile = GetSolutionFileName(@"CSharpProject\NoProject.csproj"); AssertEx.Throws<FileNotFoundException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.OpenProjectAsync(projectFile).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public void TestOpenSolution_WithNonExistentSolutionFile() { CreateFiles(GetSimpleCSharpSolutionFiles()); // open for read-write so no-one else can read var solutionFile = GetSolutionFileName(@"NoSolution.sln"); AssertEx.Throws<FileNotFoundException>(() => { using var workspace = CreateMSBuildWorkspace(); workspace.OpenSolutionAsync(solutionFile).Wait(); }); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_SolutionFileHasEmptyLinesAndWhitespaceOnlyLines() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.CSharp_EmptyLines), (@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.CSharpProject), (@"CSharpProject\CSharpClass.cs", Resources.SourceFiles.CSharp.CSharpClass), (@"CSharpProject\Properties\AssemblyInfo.cs", Resources.SourceFiles.CSharp.AssemblyInfo)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531543")] public async Task TestOpenSolution_SolutionFileHasEmptyLineBetweenProjectBlock() { var files = new FileSet( (@"TestSolution.sln", Resources.SolutionFiles.EmptyLineBetweenProjectBlock)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled), AlwaysSkip = "MSBuild parsing API throws InvalidProjectFileException")] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(531283, "DevDiv")] public async Task TestOpenSolution_SolutionFileHasMissingEndProject() { var files = new FileSet( (@"TestSolution1.sln", Resources.SolutionFiles.MissingEndProject1), (@"TestSolution2.sln", Resources.SolutionFiles.MissingEndProject2), (@"TestSolution3.sln", Resources.SolutionFiles.MissingEndProject3)); CreateFiles(files); using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution1.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution2.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } using (var workspace = CreateMSBuildWorkspace()) { var solutionFilePath = GetSolutionFileName("TestSolution3.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeSelfReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeSelfReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeSelfReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary1)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(2, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var libraryProject = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(libraryProject); Assert.Empty(libraryProject.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(792912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792912")] public async Task TestOpenSolution_WithDuplicatedGuidsBecomeCircularReferential() { var files = new FileSet( (@"DuplicatedGuids.sln", Resources.SolutionFiles.DuplicatedGuidsBecomeCircularReferential), (@"ReferenceTest\ReferenceTest.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidsBecomeCircularReferential), (@"Library1\Library1.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary3), (@"Library2\Library2.csproj", Resources.ProjectFiles.CSharp.DuplicatedGuidLibrary4)); CreateFiles(files); var solutionFilePath = GetSolutionFileName("DuplicatedGuids.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); Assert.Equal(3, solution.ProjectIds.Count); var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest"); Assert.NotNull(testProject); Assert.Single(testProject.AllProjectReferences); var library1Project = solution.Projects.FirstOrDefault(p => p.Name == "Library1"); Assert.NotNull(library1Project); Assert.Single(library1Project.AllProjectReferences); var library2Project = solution.Projects.FirstOrDefault(p => p.Name == "Library2"); Assert.NotNull(library2Project); Assert.Empty(library2Project.AllProjectReferences); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CSharp_WithMissingDebugType() { CreateFiles(new FileSet( (@"ProjectLoadErrorOnMissingDebugType.sln", Resources.SolutionFiles.ProjectLoadErrorOnMissingDebugType), (@"ProjectLoadErrorOnMissingDebugType\ProjectLoadErrorOnMissingDebugType.csproj", Resources.ProjectFiles.CSharp.ProjectLoadErrorOnMissingDebugType))); var solutionFilePath = GetSolutionFileName(@"ProjectLoadErrorOnMissingDebugType.sln"); using var workspace = CreateMSBuildWorkspace(); await workspace.OpenSolutionAsync(solutionFilePath); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>1254</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(Encoding.GetEncoding(1254), text.Encoding); // The smart quote (“) in class1.cs shows up as "“" in codepage 1254. Do a sanity // check here to make sure this file hasn't been corrupted in a way that would // impact subsequent asserts. Assert.Equal(5, "//\u00E2\u20AC\u0153".Length); Assert.Equal("//\u00E2\u20AC\u0153".Length, text.Length); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>-1</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleInvalidCodePageProperty2() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>Broken</CodePage>")), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(991528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991528")] public async Task MSBuildProjectShouldHandleDefaultCodePageProperty() { var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", "//\u201C")); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); var text = await document.GetTextAsync(); Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding); Assert.Equal("//\u201C", text.ToString()); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(981208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981208")] [WorkItem(28639, "https://github.com/dotnet/roslyn/issues/28639")] public void DisposeMSBuildWorkspaceAndServicesCollected() { CreateFiles(GetSimpleCSharpSolutionFiles()); var sol = ObjectReference.CreateFromFactory(() => MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")).Result); var workspace = sol.GetObjectReference(static s => s.Workspace); var project = sol.GetObjectReference(static s => s.Projects.First()); var document = project.GetObjectReference(static p => p.Documents.First()); var tree = document.UseReference(static d => d.GetSyntaxTreeAsync().Result); var type = tree.GetRoot().DescendantTokens().First(t => t.ToString() == "class").Parent; Assert.NotNull(type); Assert.StartsWith("public class CSharpClass", type.ToString(), StringComparison.Ordinal); var compilation = document.GetObjectReference(static d => d.GetSemanticModelAsync(CancellationToken.None).Result); Assert.NotNull(compilation); // MSBuildWorkspace doesn't have a cache service Assert.Null(workspace.UseReference(static w => w.CurrentSolution.Services.CacheService)); document.ReleaseStrongReference(); project.ReleaseStrongReference(); workspace.UseReference(static w => w.Dispose()); compilation.AssertReleased(); sol.AssertReleased(); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] public async Task MSBuildWorkspacePreservesEncoding() { var encoding = Encoding.BigEndianUnicode; var fileContent = @"//“ class C { }"; var files = new FileSet( ("Encoding.csproj", Resources.ProjectFiles.CSharp.Encoding.Replace("<CodePage>ReplaceMe</CodePage>", string.Empty)), ("class1.cs", encoding.GetBytesWithPreamble(fileContent))); CreateFiles(files); var projPath = GetSolutionFileName("Encoding.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projPath); var document = project.Documents.First(d => d.Name == "class1.cs"); // update root without first looking at text (no encoding is known) var gen = Editing.SyntaxGenerator.GetGenerator(document); var doc2 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc2text = await doc2.GetTextAsync(); Assert.Null(doc2text.Encoding); var doc2tree = await doc2.GetSyntaxTreeAsync(); Assert.Null(doc2tree.Encoding); Assert.Null(doc2tree.GetText().Encoding); // observe original text to discover encoding var text = await document.GetTextAsync(); Assert.Equal(encoding.EncodingName, text.Encoding.EncodingName); Assert.Equal(fileContent, text.ToString()); // update root blindly again, after observing encoding, see that now encoding is known var doc3 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU var doc3text = await doc3.GetTextAsync(); Assert.NotNull(doc3text.Encoding); Assert.Equal(encoding.EncodingName, doc3text.Encoding.EncodingName); var doc3tree = await doc3.GetSyntaxTreeAsync(); Assert.Equal(doc3text.Encoding, doc3tree.GetText().Encoding); Assert.Equal(doc3text.Encoding, doc3tree.Encoding); // change doc to have no encoding, still succeeds at writing to disk with old encoding var root = await document.GetSyntaxRootAsync(); var noEncodingDoc = document.WithText(SourceText.From(text.ToString(), encoding: null)); var noEncodingDocText = await noEncodingDoc.GetTextAsync(); Assert.Null(noEncodingDocText.Encoding); // apply changes (this writes the changed document) var noEncodingSolution = noEncodingDoc.Project.Solution; Assert.True(noEncodingSolution.Workspace.TryApplyChanges(noEncodingSolution)); // prove the written document still has the same encoding var filePath = GetSolutionFileName("Class1.cs"); using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var reloadedText = EncodedStringText.Create(stream); Assert.Equal(encoding.EncodingName, reloadedText.Encoding.EncodingName); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_GAC() { CreateFiles(GetSimpleCSharpSolutionFiles()); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"System.Xaml")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var mref = MetadataReference.CreateFromFile(typeof(System.Xaml.XamlObjectReader).Assembly.Location); // add reference to System.Xaml workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""System.Xaml,", projFileText); // remove reference to System.Xaml workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""System.Xaml,", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled))] [Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_ReferenceAssembly() { CreateFiles(GetMultiProjectSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithSystemNumerics)); var csProjFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var csProjFileText = File.ReadAllText(csProjFile); Assert.True(csProjFileText.Contains(@"<Reference Include=""System.Numerics""")); var vbProjFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var vbProjFileText = File.ReadAllText(vbProjFile); Assert.False(vbProjFileText.Contains(@"System.Numerics")); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")); var csProject = solution.Projects.First(p => p.Language == LanguageNames.CSharp); var vbProject = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var numericsMetadata = csProject.MetadataReferences.Single(m => m.Display.Contains("System.Numerics")); // add reference to System.Xaml workspace.TryApplyChanges(vbProject.AddMetadataReference(numericsMetadata).Solution); var newVbProjFileText = File.ReadAllText(vbProjFile); Assert.Contains(@"<Reference Include=""System.Numerics""", newVbProjFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(vbProject.Id).RemoveMetadataReference(numericsMetadata).Solution); var newVbProjFileText2 = File.ReadAllText(vbProjFile); Assert.DoesNotContain(@"<Reference Include=""System.Numerics""", newVbProjFileText2); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveMetadataReference_NonGACorRefAssembly() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"References\MyAssembly.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"MyAssembly")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAssemblyPath = GetSolutionFileName(@"References\MyAssembly.dll"); var mref = MetadataReference.CreateFromFile(myAssemblyPath); // add reference to MyAssembly.dll workspace.TryApplyChanges(project.AddMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Reference Include=""MyAssembly""", projFileText); Assert.Contains(@"<HintPath>..\References\MyAssembly.dll", projFileText); // remove reference MyAssembly.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveMetadataReference(mref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Reference Include=""MyAssembly""", projFileText); Assert.DoesNotContain(@"<HintPath>..\References\MyAssembly.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveAnalyzerReference() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"Analyzers\MyAnalyzer.dll", Resources.Dlls.EmptyLibrary)); var projFile = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var projFileText = File.ReadAllText(projFile); Assert.False(projFileText.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(); var myAnalyzerPath = GetSolutionFileName(@"Analyzers\MyAnalyzer.dll"); var aref = new AnalyzerFileReference(myAnalyzerPath, new InMemoryAssemblyLoader()); // add reference to MyAnalyzer.dll workspace.TryApplyChanges(project.AddAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); // remove reference MyAnalyzer.dll workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveAnalyzerReference(aref).Solution); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<Analyzer Include=""..\Analyzers\MyAnalyzer.dll", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestAddRemoveProjectReference() { CreateFiles(GetMultiProjectSolutionFiles()); var projFile = GetSolutionFileName(@"VisualBasicProject\VisualBasicProject.vbproj"); var projFileText = File.ReadAllText(projFile); Assert.True(projFileText.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">")); using var workspace = CreateMSBuildWorkspace(); var solutionFilePath = GetSolutionFileName("TestSolution.sln"); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var project = solution.Projects.First(p => p.Language == LanguageNames.VisualBasic); var pref = project.ProjectReferences.First(); // remove project reference workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).RemoveProjectReference(pref).Solution); Assert.Empty(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.DoesNotContain(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); // add it back workspace.TryApplyChanges(workspace.CurrentSolution.GetProject(project.Id).AddProjectReference(pref).Solution); Assert.Single(workspace.CurrentSolution.GetProject(project.Id).ProjectReferences); projFileText = File.ReadAllText(projFile); Assert.Contains(@"<ProjectReference Include=""..\CSharpProject\CSharpProject.csproj"">", projFileText); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(1101040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1101040")] public async Task TestOpenProject_BadLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadLink)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var docs = proj.Documents.ToList(); Assert.Equal(3, docs.Count); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadElement() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadElement)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); Assert.Empty(proj.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenSolution_BadTaskImport() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.BadTasks)); var solutionFilePath = GetSolutionFileName(@"TestSolution.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); var project = Assert.Single(solution.Projects); Assert.Empty(project.DocumentIds); } [ConditionalFact(typeof(IsEnglishLocal), typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_MsbuildError() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MsbuildError)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); var diagnostic = Assert.Single(workspace.Diagnostics); Assert.StartsWith("Msbuild failed", diagnostic.Message); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_WildcardsWithLink() { CreateFiles(GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.Wildcards)); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var proj = await workspace.OpenProjectAsync(projectFilePath); // prove that the file identified with a wildcard and remapped to a computed link is named correctly. Assert.Contains(proj.Documents, d => d.Name == "AssemblyInfo.cs"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestOpenProject_CommandLineArgsHaveNoErrors() { CreateFiles(GetSimpleCSharpSolutionFiles()); using var workspace = CreateMSBuildWorkspace(); var loader = workspace.Services .GetLanguageServices(LanguageNames.CSharp) .GetRequiredService<IProjectFileLoader>(); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var buildManager = new ProjectBuildManager(ImmutableDictionary<string, string>.Empty); buildManager.StartBatchBuild(); var projectFile = await loader.LoadProjectFileAsync(projectFilePath, buildManager, CancellationToken.None); var projectFileInfo = (await projectFile.GetProjectFileInfosAsync(CancellationToken.None)).Single(); buildManager.EndBatchBuild(); var commandLineParser = workspace.Services .GetLanguageServices(loader.Language) .GetRequiredService<ICommandLineParserService>(); var projectDirectory = Path.GetDirectoryName(projectFilePath); var commandLineArgs = commandLineParser.Parse( arguments: projectFileInfo.CommandLineArgs, baseDirectory: projectDirectory, isInteractive: false, sdkDirectory: System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()); Assert.Empty(commandLineArgs.Errors); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29122, "https://github.com/dotnet/roslyn/issues/29122")] public async Task TestOpenSolution_ProjectReferencesWithUnconventionalOutputPaths() { CreateFiles(GetBaseFiles() .WithFile(@"TestVB2.sln", Resources.SolutionFiles.Issue29122_Solution) .WithFile(@"Proj1\ClassLibrary1.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary1) .WithFile(@"Proj1\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj1\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj1\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj1\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj1\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj1\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj1\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj1\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings) .WithFile(@"Proj2\ClassLibrary2.vbproj", Resources.ProjectFiles.VisualBasic.Issue29122_ClassLibrary2) .WithFile(@"Proj2\Class1.vb", Resources.SourceFiles.VisualBasic.VisualBasicClass) .WithFile(@"Proj2\My Project\Application.Designer.vb", Resources.SourceFiles.VisualBasic.Application_Designer) .WithFile(@"Proj2\My Project\Application.myapp", Resources.SourceFiles.VisualBasic.Application) .WithFile(@"Proj2\My Project\AssemblyInfo.vb", Resources.SourceFiles.VisualBasic.AssemblyInfo) .WithFile(@"Proj2\My Project\Resources.Designer.vb", Resources.SourceFiles.VisualBasic.Resources_Designer) .WithFile(@"Proj2\My Project\Resources.resx", Resources.SourceFiles.VisualBasic.Resources) .WithFile(@"Proj2\My Project\Settings.Designer.vb", Resources.SourceFiles.VisualBasic.Settings_Designer) .WithFile(@"Proj2\My Project\Settings.settings", Resources.SourceFiles.VisualBasic.Settings)); var solutionFilePath = GetSolutionFileName(@"TestVB2.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(solutionFilePath); // Neither project should contain any unresolved metadata references foreach (var project in solution.Projects) { Assert.DoesNotContain(project.MetadataReferences, mr => mr is UnresolvedMetadataReference); } } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(29494, "https://github.com/dotnet/roslyn/issues/29494")] public async Task TestOpenProjectAsync_MalformedAdditionalFilePath() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.MallformedAdditionalFilePath) .WithFile(@"CSharpProject\ValidAdditionalFile.txt", Resources.SourceFiles.Text.ValidAdditionalFile); CreateFiles(files); var projectFilePath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); using var workspace = CreateMSBuildWorkspace(); var project = await workspace.OpenProjectAsync(projectFilePath); // Project should open without an exception being thrown. Assert.NotNull(project); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "COM1"); Assert.Contains(project.AdditionalDocuments, doc => doc.Name == "TEST::"); } [ConditionalFact(typeof(VisualStudioMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] [WorkItem(31390, "https://github.com/dotnet/roslyn/issues/31390")] public async Task TestDuplicateProjectAndMetadataReferences() { var files = GetDuplicateProjectReferenceSolutionFiles(); CreateFiles(files); var fullPath = GetSolutionFileName(@"CSharpProjectReference.sln"); using var workspace = CreateMSBuildWorkspace(); var solution = await workspace.OpenSolutionAsync(fullPath); var project = solution.Projects.Single(p => p.FilePath.EndsWith("CSharpProject_ProjectReference.csproj")); Assert.Single(project.ProjectReferences); AssertEx.Equal( new[] { "EmptyLibrary.dll", "System.Core.dll", "mscorlib.dll" }, project.MetadataReferences.Select(r => Path.GetFileName(((PortableExecutableReference)r).FilePath)).OrderBy(StringComparer.Ordinal)); var compilation = await project.GetCompilationAsync(); Assert.Single(compilation.References.OfType<CompilationReference>()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscovery() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .WithFile(".editorconfig", "root = true"); CreateFiles(files); var expectedEditorConfigPath = SolutionDirectory.CreateOrOpenFile(".editorconfig").Path; using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); // We should have exactly one .editorconfig corresponding to the file we had. We may also // have other files if there is a .editorconfig floating around somewhere higher on the disk. var analyzerConfigDocument = Assert.Single(project.AnalyzerConfigDocuments.Where(d => d.FilePath == expectedEditorConfigPath)); Assert.Equal(".editorconfig", analyzerConfigDocument.Name); var text = await analyzerConfigDocument.GetTextAsync(); Assert.Equal("root = true", text.ToString()); } [ConditionalFact(typeof(VisualStudio16_2OrHigherMSBuildInstalled)), Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)] public async Task TestEditorConfigDiscoveryDisabled() { var files = GetSimpleCSharpSolutionFiles() .WithFile(@"CSharpProject\CSharpProject.csproj", Resources.ProjectFiles.CSharp.WithDiscoverEditorConfigFiles) .ReplaceFileElement(@"CSharpProject\CSharpProject.csproj", "DiscoverEditorConfigFiles", "false") .WithFile(".editorconfig", "root = true"); CreateFiles(files); using var workspace = CreateMSBuildWorkspace(); var projectFullPath = GetSolutionFileName(@"CSharpProject\CSharpProject.csproj"); var project = await workspace.OpenProjectAsync(projectFullPath); Assert.Empty(project.AnalyzerConfigDocuments); } private class InMemoryAssemblyLoader : IAnalyzerAssemblyLoader { public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { var bytes = File.ReadAllBytes(fullPath); return Assembly.Load(bytes); } } } }
54.993045
194
0.685525
[ "MIT" ]
C-xC-c/roslyn
src/Workspaces/MSBuildTest/MSBuildWorkspaceTests.cs
181,872
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("01. Parking Lot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01. Parking Lot")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("c7c94084-ecf7-49cb-8dfc-4eb63ea0ae4d")] // 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")]
37.783784
84
0.744635
[ "MIT" ]
Shtereva/CSharp-Advanced
Sets and Dictionaries/01. Parking Lot/Properties/AssemblyInfo.cs
1,401
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System.Collections.Generic; using EnsureThat; using MediatR; using Microsoft.Health.Fhir.Core.Features.Conformance; using Microsoft.Health.Fhir.Core.Features.Persistence; namespace Microsoft.Health.Fhir.Core.Messages.Delete { public class DeleteResourceRequest : IRequest<DeleteResourceResponse>, IRequireCapability { public DeleteResourceRequest(ResourceKey resourceKey, DeleteOperation deleteOperation) { EnsureArg.IsNotNull(resourceKey, nameof(resourceKey)); ResourceKey = resourceKey; DeleteOperation = deleteOperation; } public DeleteResourceRequest(string type, string id, DeleteOperation deleteOperation) { EnsureArg.IsNotNull(type, nameof(type)); EnsureArg.IsNotNull(id, nameof(id)); ResourceKey = new ResourceKey(type, id); DeleteOperation = deleteOperation; } public ResourceKey ResourceKey { get; } public DeleteOperation DeleteOperation { get; } public IEnumerable<CapabilityQuery> RequiredCapabilities() { yield return new CapabilityQuery($"CapabilityStatement.rest.resource.where(type = '{ResourceKey.ResourceType}').interaction.where(code = 'delete').exists()"); } } }
38.44186
170
0.614035
[ "MIT" ]
BearerPipelineTest/fhir-server
src/Microsoft.Health.Fhir.Core/Messages/Delete/DeleteResourceRequest.cs
1,655
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Controls; namespace TransactionRegister { public class TollbarViewModel { public Brush Background_Color { get; set; } public Brush Font_Color { get; set; } public Button Navigation_btn { get; set; } public Label Title_lbl { get; set; } public List<Button> ItemModifers { get; set; } public TollbarViewModel() { Background_Color = Brushes.White; Font_Color = Brushes.White; Navigation_btn = new Button(); Title_lbl = new Label(); ItemModifers = new List<Button>(); } } }
26.8
55
0.606965
[ "MIT" ]
Isrelo/Tutorials
WPF-GUI/Lesson11/TransactionRegister/ViewModels/TollbarViewModel.cs
806
C#
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects.GuiControls { public unsafe class GuiInspectorTypeColorI : GuiInspectorTypeColor { public GuiInspectorTypeColorI() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiInspectorTypeColorICreateInstance()); } public GuiInspectorTypeColorI(uint pId) : base(pId) { } public GuiInspectorTypeColorI(string pName) : base(pName) { } public GuiInspectorTypeColorI(IntPtr pObjPtr) : base(pObjPtr) { } public GuiInspectorTypeColorI(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public GuiInspectorTypeColorI(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiInspectorTypeColorICreateInstance(); private static _GuiInspectorTypeColorICreateInstance _GuiInspectorTypeColorICreateInstanceFunc; internal static IntPtr GuiInspectorTypeColorICreateInstance() { if (_GuiInspectorTypeColorICreateInstanceFunc == null) { _GuiInspectorTypeColorICreateInstanceFunc = (_GuiInspectorTypeColorICreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiInspectorTypeColorICreateInstance"), typeof(_GuiInspectorTypeColorICreateInstance)); } return _GuiInspectorTypeColorICreateInstanceFunc(); } } #endregion #region Properties #endregion #region Methods #endregion } }
26.693333
172
0.677323
[ "MIT" ]
lukaspj/Torque6-Embedded-C-
Torque6/Engine/SimObjects/GuiControls/GuiInspectorTypeColorI.cs
2,002
C#
using UnityEngine; using UnityEditor; namespace vubbiscript { /// <summary> /// BASED ON: https://forum.unity3d.com/threads/editor-modal-window.222018/ /// The rename popup is a generic popup that allow the user to input a name or to rename an existing one. /// You can pass a delegate to valide the currently input string. /// /// => Changed to simple filename popup /// </summary> public class VisualBlockFileNameWindow : ModalWindow { public const float BUTTONS_HEIGHT = 30; public const float FIELD_HEIGHT = 20; public const float HEIGHT = 56; public const float WIDTH = 250; private string[] labels; private string[] texts; public string[] Texts { get { return texts; } } public static VisualBlockFileNameWindow Create(IModal owner, string title, string[] labels, string[] texts, Vector2 position) { VisualBlockFileNameWindow rename = VisualBlockFileNameWindow.CreateInstance<VisualBlockFileNameWindow>(); rename.owner = owner; rename.titleContent = new GUIContent(title); rename.labels = labels; rename.texts = texts; float halfWidth = WIDTH / 2; float x = position.x - halfWidth; float y = position.y; float height = HEIGHT + (labels.Length * FIELD_HEIGHT); Rect rect = new Rect(x, y, 0, 0); rename.position = rect; rename.ShowAsDropDown(rect, new Vector2(WIDTH, height)); return rename; } protected override void Draw(Rect region) { int state = -1; if (Event.current.type == EventType.KeyDown) { if (Event.current.keyCode == KeyCode.Return) state = 1; if (Event.current.keyCode == KeyCode.Escape) state = 0; } GUILayout.BeginArea(region); GUILayout.Space(5); for (int i = 0; i < texts.Length; i++) { GUILayout.BeginHorizontal(); GUI.color = Color.white; texts[i] = EditorGUILayout.TextField(texts[i]); GUILayout.EndHorizontal(); } GUILayout.Space(5); GUILayout.BeginHorizontal(); //GUI.enabled = valid; if (GUILayout.Button("Ok")) state = 1; GUI.enabled = true; if (GUILayout.Button ("Cancel")) state = 0; GUILayout.EndHorizontal(); GUILayout.EndArea(); if (state > -1) { if (state == 0) { Cancel (); } else { Ok (); } } } } }
22
128
0.627104
[ "MIT" ]
VubbiScript/VubbiScript
src/unity-project/Assets/Editor Default Resources/Editor/VubbiScriptSource/FileLogic/VisualBlockFileNameWindow.cs
2,376
C#
namespace Security { public class SecurityUserRoleViewModel { public string UserId { get; set; } public string RoleId { get; set; } // ??? public string UserName { get; set; } public bool IsSelected { get; set; } } }
19.538462
46
0.602362
[ "MIT" ]
pragmatic-applications/AspNet_Host_Service
Lib_Host_Service/Security/SecurityUserRoleViewModel.cs
256
C#
/* * <auto-generated> * Connect API * * Pelion Device Management Connect API allows web applications to communicate with devices. You can subscribe to device resources and read/write values to them. Device Management Connect allows connectivity to devices by queueing requests and caching resource values. * * OpenAPI spec version: 2 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * </auto-generated> */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using mds.Client; using mds.Model; using System.Threading; namespace mds.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface INotificationsApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Open the websocket. /// </summary> /// <remarks> /// A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed.&lt;br/&gt; Once the socket has been opened, it may be closed with one of the following status codes&lt;br/&gt; **1000**: Socket closed by the client. **1001**: Going away. set when another socket was opened on the used channel, or if the channel was deleted with a REST call, or if the server is shutting down. **1006**: Abnormal loss of connection. This code is never set by the service. **1008**: Policy violation. Set when the API key is missing or invalid. **1011**: Unexpected condition. Socket will be closed with this status at an attempt to open a socket to an unexisting channel (without a prior REST PUT). This code is also used to indicate closing socket for any other unexpected condition in the server. /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="connection"></param> /// <param name="upgrade"></param> /// <param name="secWebSocketProtocol">ApiKey must be present in the &#x60;Sec-WebSocket-Protocol&#x60; header &#x60;\&quot;Sec-WebSocket-Protocol\&quot;:\&quot;wss,pelion_ak_{api_key}\&quot;&#x60; Refer to the notification service documentation for examples of usage. </param> /// <returns></returns> void ConnectWebsocket (string connection, string upgrade, string secWebSocketProtocol); /// <summary> /// Open the websocket. /// </summary> /// <remarks> /// A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed.&lt;br/&gt; Once the socket has been opened, it may be closed with one of the following status codes&lt;br/&gt; **1000**: Socket closed by the client. **1001**: Going away. set when another socket was opened on the used channel, or if the channel was deleted with a REST call, or if the server is shutting down. **1006**: Abnormal loss of connection. This code is never set by the service. **1008**: Policy violation. Set when the API key is missing or invalid. **1011**: Unexpected condition. Socket will be closed with this status at an attempt to open a socket to an unexisting channel (without a prior REST PUT). This code is also used to indicate closing socket for any other unexpected condition in the server. /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="connection"></param> /// <param name="upgrade"></param> /// <param name="secWebSocketProtocol">ApiKey must be present in the &#x60;Sec-WebSocket-Protocol&#x60; header &#x60;\&quot;Sec-WebSocket-Protocol\&quot;:\&quot;wss,pelion_ak_{api_key}\&quot;&#x60; Refer to the notification service documentation for examples of usage. </param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> ConnectWebsocketWithHttpInfo (string connection, string upgrade, string secWebSocketProtocol); /// <summary> /// Delete notification Long Poll channel /// </summary> /// <remarks> /// To delete a notification Long Poll channel. This is required to change the channel from Long Poll to another type. You should not make a GET &#x60;/v2/notification/pull&#x60; call for 2 minutes after channel was deleted, because it can implicitly recreate the pull channel. You can also have some random responses with payload or 410 GONE with \&quot;CHANNEL_DELETED\&quot; as a payload or 200/204 until the old channel is purged. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns></returns> void DeleteLongPollChannel (); /// <summary> /// Delete notification Long Poll channel /// </summary> /// <remarks> /// To delete a notification Long Poll channel. This is required to change the channel from Long Poll to another type. You should not make a GET &#x60;/v2/notification/pull&#x60; call for 2 minutes after channel was deleted, because it can implicitly recreate the pull channel. You can also have some random responses with payload or 410 GONE with \&quot;CHANNEL_DELETED\&quot; as a payload or 200/204 until the old channel is purged. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> DeleteLongPollChannelWithHttpInfo (); /// <summary> /// Delete websocket channel. /// </summary> /// <remarks> /// To delete a notification websocket channel bound to the API key. This is required to change the channel from websocket to another type. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns></returns> void DeleteWebsocket (); /// <summary> /// Delete websocket channel. /// </summary> /// <remarks> /// To delete a notification websocket channel bound to the API key. This is required to change the channel from websocket to another type. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> DeleteWebsocketWithHttpInfo (); /// <summary> /// Delete callback URL /// </summary> /// <remarks> /// Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns></returns> void DeregisterWebhook (); /// <summary> /// Delete callback URL /// </summary> /// <remarks> /// Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> DeregisterWebhookWithHttpInfo (); /// <summary> /// Check callback URL /// </summary> /// <remarks> /// Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Webhook</returns> Webhook GetWebhook (); /// <summary> /// Check callback URL /// </summary> /// <remarks> /// Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of Webhook</returns> ApiResponse<Webhook> GetWebhookWithHttpInfo (); /// <summary> /// Get websocket channel information. /// </summary> /// <remarks> /// Returns 200 with websocket connection status if websocket channel exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>WebsocketChannel</returns> WebsocketChannel GetWebsocket (); /// <summary> /// Get websocket channel information. /// </summary> /// <remarks> /// Returns 200 with websocket connection status if websocket channel exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of WebsocketChannel</returns> ApiResponse<WebsocketChannel> GetWebsocketWithHttpInfo (); /// <summary> /// Get notifications using Long Poll /// </summary> /// <remarks> /// In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client or the request times out (response code 204). In both cases, the client should open a new polling connection after the previous one closes. Only a single long polling connection per API key can be ongoing at any given time. You must have a persistent connection (Connection keep-alive header in the request) to avoid excess TLS handshakes. The pull channel is implicitly created by the first GET call to &#x60;/v2/notification/pull&#x60;. It is refreshed on each GET call. If the channel is not polled for a long time (10 minutes) - it expires and will be deleted. This means that no notifications will stay in the queue between polls. A channel can be also deleted explicitly by a DELETE call. **Note:** If you cannot have a public facing callback URL, for example when developing on your local machine, you can use long polling to check for new messages. However, **long polling is deprecated** and will likely be replaced in future. It is meant only for experimentation and not for commercial usage. The proper method to receive notifications is a **notification callback**. There can only be one notification channel per API key at a time in Device Management Connect. If a notification channel of other type already exists for the API key, you need to delete it before creating a long poll notification channel. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>NotificationMessage</returns> NotificationMessage LongPollNotifications (); /// <summary> /// Get notifications using Long Poll /// </summary> /// <remarks> /// In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client or the request times out (response code 204). In both cases, the client should open a new polling connection after the previous one closes. Only a single long polling connection per API key can be ongoing at any given time. You must have a persistent connection (Connection keep-alive header in the request) to avoid excess TLS handshakes. The pull channel is implicitly created by the first GET call to &#x60;/v2/notification/pull&#x60;. It is refreshed on each GET call. If the channel is not polled for a long time (10 minutes) - it expires and will be deleted. This means that no notifications will stay in the queue between polls. A channel can be also deleted explicitly by a DELETE call. **Note:** If you cannot have a public facing callback URL, for example when developing on your local machine, you can use long polling to check for new messages. However, **long polling is deprecated** and will likely be replaced in future. It is meant only for experimentation and not for commercial usage. The proper method to receive notifications is a **notification callback**. There can only be one notification channel per API key at a time in Device Management Connect. If a notification channel of other type already exists for the API key, you need to delete it before creating a long poll notification channel. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of NotificationMessage</returns> ApiResponse<NotificationMessage> LongPollNotificationsWithHttpInfo (); /// <summary> /// Register a callback URL /// </summary> /// <remarks> /// Register a URL to which the server should deliver notifications of the subscribed resource changes. To get notifications pushed, you also need to place the subscriptions. The maximum length of the URL, header keys and values, all combined, is 400 characters. Notifications are delivered as PUT messages to the HTTP server defined by the client with a subscription server message. The given URL should be accessible and respond to the PUT request with response code of 200 or 204. Device Management Connect tests the callback URL with an empty payload when the URL is registered. For more information on notification messages, see [NotificationMessage](#NotificationMessage). **Optional headers in a callback message:** You can set optional headers to a callback in a **Webhook** object. Device Management Connect will include the header and key pairs to the notification messages send them to callback URL. As the callback URL&#39;s are API key specific also the headers are. One possible use for the additional headers is to check the origin of a PUT request and also distinguish the application (API key) to which the notification belongs to. **Note**: Only one callback URL per an API key can be active. If you register a new URL while another one is already active, it replaces the active one. There can be only one notification channel at a time. If another type of channel is already present, you need to delete it before setting the callback URL. **Expiration of a callback URL:** A callback can expire when Device Management cannot deliver a notification due to a connection timeout or an error response (4xx or 5xx). After each delivery failure, Device Management sets an exponential back off time and makes a retry attempt after that. The first retry delay is 1 second, then 2s, 4s, 8s, ..., 2min, 2min. The maximum retry delay is 2 minutes. The callback URL will be removed if all retries fail within 24 hours. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Supported callback URL protocols:** Currently, only HTTP and HTTPS protocols are supported. **HTTPS callback URLs:** When delivering a notification to an HTTPS based callback URL, Device Management Connect will present a valid client certificate to identify itself. The certificate is signed by a trusted certificate authorithy (GlobalSign) with a Common Name (CN) set to notifications.mbedcloud.com. **Example usage:** This example command shows how to set your callback URL and API key. It also sets an optional header authorization. When Device Management Connect calls your callback URL, the call contains the authorization header with the defined value. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/notification/callback \\ -H &#39;authorization: Bearer {api-key}&#39; \\ -H &#39;content-type: application/json&#39; \\ -d &#39;{ \&quot;url\&quot;: \&quot;{callback-url}\&quot;, \&quot;headers\&quot;: {\&quot;authorization\&quot; : \&quot;f4b93d6e-4652-4874-82e4-41a3ced0cd56\&quot;} }&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="webhook">A json object that contains the optional headers and the URL to which the notifications need to be sent. </param> /// <returns></returns> void RegisterWebhook (Webhook webhook); /// <summary> /// Register a callback URL /// </summary> /// <remarks> /// Register a URL to which the server should deliver notifications of the subscribed resource changes. To get notifications pushed, you also need to place the subscriptions. The maximum length of the URL, header keys and values, all combined, is 400 characters. Notifications are delivered as PUT messages to the HTTP server defined by the client with a subscription server message. The given URL should be accessible and respond to the PUT request with response code of 200 or 204. Device Management Connect tests the callback URL with an empty payload when the URL is registered. For more information on notification messages, see [NotificationMessage](#NotificationMessage). **Optional headers in a callback message:** You can set optional headers to a callback in a **Webhook** object. Device Management Connect will include the header and key pairs to the notification messages send them to callback URL. As the callback URL&#39;s are API key specific also the headers are. One possible use for the additional headers is to check the origin of a PUT request and also distinguish the application (API key) to which the notification belongs to. **Note**: Only one callback URL per an API key can be active. If you register a new URL while another one is already active, it replaces the active one. There can be only one notification channel at a time. If another type of channel is already present, you need to delete it before setting the callback URL. **Expiration of a callback URL:** A callback can expire when Device Management cannot deliver a notification due to a connection timeout or an error response (4xx or 5xx). After each delivery failure, Device Management sets an exponential back off time and makes a retry attempt after that. The first retry delay is 1 second, then 2s, 4s, 8s, ..., 2min, 2min. The maximum retry delay is 2 minutes. The callback URL will be removed if all retries fail within 24 hours. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Supported callback URL protocols:** Currently, only HTTP and HTTPS protocols are supported. **HTTPS callback URLs:** When delivering a notification to an HTTPS based callback URL, Device Management Connect will present a valid client certificate to identify itself. The certificate is signed by a trusted certificate authorithy (GlobalSign) with a Common Name (CN) set to notifications.mbedcloud.com. **Example usage:** This example command shows how to set your callback URL and API key. It also sets an optional header authorization. When Device Management Connect calls your callback URL, the call contains the authorization header with the defined value. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/notification/callback \\ -H &#39;authorization: Bearer {api-key}&#39; \\ -H &#39;content-type: application/json&#39; \\ -d &#39;{ \&quot;url\&quot;: \&quot;{callback-url}\&quot;, \&quot;headers\&quot;: {\&quot;authorization\&quot; : \&quot;f4b93d6e-4652-4874-82e4-41a3ced0cd56\&quot;} }&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="webhook">A json object that contains the optional headers and the URL to which the notifications need to be sent. </param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> RegisterWebhookWithHttpInfo (Webhook webhook); /// <summary> /// Register a websocket channel /// </summary> /// <remarks> /// Register (or update) a channel which will use websocket connection to deliver notifications. The websocket channel should be opened by client using &#x60;/v2/notification/websocket-connect&#x60; endpoint. To get notifications pushed, you also need to place the subscriptions. For more information on notification messages, see [NotificationMessage](#NotificationMessage). A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed. **Expiration of a websocket:** A websocket channel will be expired if the channel does not have an opened websocket connection for 24 hour period. Channel expiration means the channel will be deleted and any undelivered notifications stored in its internal queue will be removed. As long as the channel has an opened websocket connection or time between successive websocket connections is less than 24 hours, the channel is considered active, notifications are stored in its internal queue and delivered when a websocket connection is active. A channel can be also deleted explicitly by a DELETE call. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Example usage:** curl -X PUT https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>WebsocketChannel</returns> WebsocketChannel RegisterWebsocket (); /// <summary> /// Register a websocket channel /// </summary> /// <remarks> /// Register (or update) a channel which will use websocket connection to deliver notifications. The websocket channel should be opened by client using &#x60;/v2/notification/websocket-connect&#x60; endpoint. To get notifications pushed, you also need to place the subscriptions. For more information on notification messages, see [NotificationMessage](#NotificationMessage). A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed. **Expiration of a websocket:** A websocket channel will be expired if the channel does not have an opened websocket connection for 24 hour period. Channel expiration means the channel will be deleted and any undelivered notifications stored in its internal queue will be removed. As long as the channel has an opened websocket connection or time between successive websocket connections is less than 24 hours, the channel is considered active, notifications are stored in its internal queue and delivered when a websocket connection is active. A channel can be also deleted explicitly by a DELETE call. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Example usage:** curl -X PUT https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of WebsocketChannel</returns> ApiResponse<WebsocketChannel> RegisterWebsocketWithHttpInfo (); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Open the websocket. /// </summary> /// <remarks> /// A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed.&lt;br/&gt; Once the socket has been opened, it may be closed with one of the following status codes&lt;br/&gt; **1000**: Socket closed by the client. **1001**: Going away. set when another socket was opened on the used channel, or if the channel was deleted with a REST call, or if the server is shutting down. **1006**: Abnormal loss of connection. This code is never set by the service. **1008**: Policy violation. Set when the API key is missing or invalid. **1011**: Unexpected condition. Socket will be closed with this status at an attempt to open a socket to an unexisting channel (without a prior REST PUT). This code is also used to indicate closing socket for any other unexpected condition in the server. /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="connection"></param> /// <param name="upgrade"></param> /// <param name="secWebSocketProtocol">ApiKey must be present in the &#x60;Sec-WebSocket-Protocol&#x60; header &#x60;\&quot;Sec-WebSocket-Protocol\&quot;:\&quot;wss,pelion_ak_{api_key}\&quot;&#x60; Refer to the notification service documentation for examples of usage. </param> /// <returns>Task of void</returns> System.Threading.Tasks.Task ConnectWebsocketAsync (string connection, string upgrade, string secWebSocketProtocol); /// <summary> /// Open the websocket. /// </summary> /// <remarks> /// A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed.&lt;br/&gt; Once the socket has been opened, it may be closed with one of the following status codes&lt;br/&gt; **1000**: Socket closed by the client. **1001**: Going away. set when another socket was opened on the used channel, or if the channel was deleted with a REST call, or if the server is shutting down. **1006**: Abnormal loss of connection. This code is never set by the service. **1008**: Policy violation. Set when the API key is missing or invalid. **1011**: Unexpected condition. Socket will be closed with this status at an attempt to open a socket to an unexisting channel (without a prior REST PUT). This code is also used to indicate closing socket for any other unexpected condition in the server. /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="connection"></param> /// <param name="upgrade"></param> /// <param name="secWebSocketProtocol">ApiKey must be present in the &#x60;Sec-WebSocket-Protocol&#x60; header &#x60;\&quot;Sec-WebSocket-Protocol\&quot;:\&quot;wss,pelion_ak_{api_key}\&quot;&#x60; Refer to the notification service documentation for examples of usage. </param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> ConnectWebsocketAsyncWithHttpInfo (string connection, string upgrade, string secWebSocketProtocol); /// <summary> /// Delete notification Long Poll channel /// </summary> /// <remarks> /// To delete a notification Long Poll channel. This is required to change the channel from Long Poll to another type. You should not make a GET &#x60;/v2/notification/pull&#x60; call for 2 minutes after channel was deleted, because it can implicitly recreate the pull channel. You can also have some random responses with payload or 410 GONE with \&quot;CHANNEL_DELETED\&quot; as a payload or 200/204 until the old channel is purged. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of void</returns> System.Threading.Tasks.Task DeleteLongPollChannelAsync (); /// <summary> /// Delete notification Long Poll channel /// </summary> /// <remarks> /// To delete a notification Long Poll channel. This is required to change the channel from Long Poll to another type. You should not make a GET &#x60;/v2/notification/pull&#x60; call for 2 minutes after channel was deleted, because it can implicitly recreate the pull channel. You can also have some random responses with payload or 410 GONE with \&quot;CHANNEL_DELETED\&quot; as a payload or 200/204 until the old channel is purged. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> DeleteLongPollChannelAsyncWithHttpInfo (); /// <summary> /// Delete websocket channel. /// </summary> /// <remarks> /// To delete a notification websocket channel bound to the API key. This is required to change the channel from websocket to another type. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of void</returns> System.Threading.Tasks.Task DeleteWebsocketAsync (); /// <summary> /// Delete websocket channel. /// </summary> /// <remarks> /// To delete a notification websocket channel bound to the API key. This is required to change the channel from websocket to another type. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> DeleteWebsocketAsyncWithHttpInfo (); /// <summary> /// Delete callback URL /// </summary> /// <remarks> /// Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of void</returns> System.Threading.Tasks.Task DeregisterWebhookAsync (); /// <summary> /// Delete callback URL /// </summary> /// <remarks> /// Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> DeregisterWebhookAsyncWithHttpInfo (); /// <summary> /// Check callback URL /// </summary> /// <remarks> /// Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of Webhook</returns> System.Threading.Tasks.Task<Webhook> GetWebhookAsync (); /// <summary> /// Check callback URL /// </summary> /// <remarks> /// Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (Webhook)</returns> System.Threading.Tasks.Task<ApiResponse<Webhook>> GetWebhookAsyncWithHttpInfo (); /// <summary> /// Get websocket channel information. /// </summary> /// <remarks> /// Returns 200 with websocket connection status if websocket channel exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of WebsocketChannel</returns> System.Threading.Tasks.Task<WebsocketChannel> GetWebsocketAsync (); /// <summary> /// Get websocket channel information. /// </summary> /// <remarks> /// Returns 200 with websocket connection status if websocket channel exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (WebsocketChannel)</returns> System.Threading.Tasks.Task<ApiResponse<WebsocketChannel>> GetWebsocketAsyncWithHttpInfo (); /// <summary> /// Get notifications using Long Poll /// </summary> /// <remarks> /// In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client or the request times out (response code 204). In both cases, the client should open a new polling connection after the previous one closes. Only a single long polling connection per API key can be ongoing at any given time. You must have a persistent connection (Connection keep-alive header in the request) to avoid excess TLS handshakes. The pull channel is implicitly created by the first GET call to &#x60;/v2/notification/pull&#x60;. It is refreshed on each GET call. If the channel is not polled for a long time (10 minutes) - it expires and will be deleted. This means that no notifications will stay in the queue between polls. A channel can be also deleted explicitly by a DELETE call. **Note:** If you cannot have a public facing callback URL, for example when developing on your local machine, you can use long polling to check for new messages. However, **long polling is deprecated** and will likely be replaced in future. It is meant only for experimentation and not for commercial usage. The proper method to receive notifications is a **notification callback**. There can only be one notification channel per API key at a time in Device Management Connect. If a notification channel of other type already exists for the API key, you need to delete it before creating a long poll notification channel. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of NotificationMessage</returns> System.Threading.Tasks.Task<NotificationMessage> LongPollNotificationsAsync (CancellationToken token); /// <summary> /// Get notifications using Long Poll /// </summary> /// <remarks> /// In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client or the request times out (response code 204). In both cases, the client should open a new polling connection after the previous one closes. Only a single long polling connection per API key can be ongoing at any given time. You must have a persistent connection (Connection keep-alive header in the request) to avoid excess TLS handshakes. The pull channel is implicitly created by the first GET call to &#x60;/v2/notification/pull&#x60;. It is refreshed on each GET call. If the channel is not polled for a long time (10 minutes) - it expires and will be deleted. This means that no notifications will stay in the queue between polls. A channel can be also deleted explicitly by a DELETE call. **Note:** If you cannot have a public facing callback URL, for example when developing on your local machine, you can use long polling to check for new messages. However, **long polling is deprecated** and will likely be replaced in future. It is meant only for experimentation and not for commercial usage. The proper method to receive notifications is a **notification callback**. There can only be one notification channel per API key at a time in Device Management Connect. If a notification channel of other type already exists for the API key, you need to delete it before creating a long poll notification channel. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (NotificationMessage)</returns> System.Threading.Tasks.Task<ApiResponse<NotificationMessage>> LongPollNotificationsAsyncWithHttpInfo (CancellationToken token); /// <summary> /// Register a callback URL /// </summary> /// <remarks> /// Register a URL to which the server should deliver notifications of the subscribed resource changes. To get notifications pushed, you also need to place the subscriptions. The maximum length of the URL, header keys and values, all combined, is 400 characters. Notifications are delivered as PUT messages to the HTTP server defined by the client with a subscription server message. The given URL should be accessible and respond to the PUT request with response code of 200 or 204. Device Management Connect tests the callback URL with an empty payload when the URL is registered. For more information on notification messages, see [NotificationMessage](#NotificationMessage). **Optional headers in a callback message:** You can set optional headers to a callback in a **Webhook** object. Device Management Connect will include the header and key pairs to the notification messages send them to callback URL. As the callback URL&#39;s are API key specific also the headers are. One possible use for the additional headers is to check the origin of a PUT request and also distinguish the application (API key) to which the notification belongs to. **Note**: Only one callback URL per an API key can be active. If you register a new URL while another one is already active, it replaces the active one. There can be only one notification channel at a time. If another type of channel is already present, you need to delete it before setting the callback URL. **Expiration of a callback URL:** A callback can expire when Device Management cannot deliver a notification due to a connection timeout or an error response (4xx or 5xx). After each delivery failure, Device Management sets an exponential back off time and makes a retry attempt after that. The first retry delay is 1 second, then 2s, 4s, 8s, ..., 2min, 2min. The maximum retry delay is 2 minutes. The callback URL will be removed if all retries fail within 24 hours. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Supported callback URL protocols:** Currently, only HTTP and HTTPS protocols are supported. **HTTPS callback URLs:** When delivering a notification to an HTTPS based callback URL, Device Management Connect will present a valid client certificate to identify itself. The certificate is signed by a trusted certificate authorithy (GlobalSign) with a Common Name (CN) set to notifications.mbedcloud.com. **Example usage:** This example command shows how to set your callback URL and API key. It also sets an optional header authorization. When Device Management Connect calls your callback URL, the call contains the authorization header with the defined value. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/notification/callback \\ -H &#39;authorization: Bearer {api-key}&#39; \\ -H &#39;content-type: application/json&#39; \\ -d &#39;{ \&quot;url\&quot;: \&quot;{callback-url}\&quot;, \&quot;headers\&quot;: {\&quot;authorization\&quot; : \&quot;f4b93d6e-4652-4874-82e4-41a3ced0cd56\&quot;} }&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="webhook">A json object that contains the optional headers and the URL to which the notifications need to be sent. </param> /// <returns>Task of void</returns> System.Threading.Tasks.Task RegisterWebhookAsync (Webhook webhook); /// <summary> /// Register a callback URL /// </summary> /// <remarks> /// Register a URL to which the server should deliver notifications of the subscribed resource changes. To get notifications pushed, you also need to place the subscriptions. The maximum length of the URL, header keys and values, all combined, is 400 characters. Notifications are delivered as PUT messages to the HTTP server defined by the client with a subscription server message. The given URL should be accessible and respond to the PUT request with response code of 200 or 204. Device Management Connect tests the callback URL with an empty payload when the URL is registered. For more information on notification messages, see [NotificationMessage](#NotificationMessage). **Optional headers in a callback message:** You can set optional headers to a callback in a **Webhook** object. Device Management Connect will include the header and key pairs to the notification messages send them to callback URL. As the callback URL&#39;s are API key specific also the headers are. One possible use for the additional headers is to check the origin of a PUT request and also distinguish the application (API key) to which the notification belongs to. **Note**: Only one callback URL per an API key can be active. If you register a new URL while another one is already active, it replaces the active one. There can be only one notification channel at a time. If another type of channel is already present, you need to delete it before setting the callback URL. **Expiration of a callback URL:** A callback can expire when Device Management cannot deliver a notification due to a connection timeout or an error response (4xx or 5xx). After each delivery failure, Device Management sets an exponential back off time and makes a retry attempt after that. The first retry delay is 1 second, then 2s, 4s, 8s, ..., 2min, 2min. The maximum retry delay is 2 minutes. The callback URL will be removed if all retries fail within 24 hours. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Supported callback URL protocols:** Currently, only HTTP and HTTPS protocols are supported. **HTTPS callback URLs:** When delivering a notification to an HTTPS based callback URL, Device Management Connect will present a valid client certificate to identify itself. The certificate is signed by a trusted certificate authorithy (GlobalSign) with a Common Name (CN) set to notifications.mbedcloud.com. **Example usage:** This example command shows how to set your callback URL and API key. It also sets an optional header authorization. When Device Management Connect calls your callback URL, the call contains the authorization header with the defined value. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/notification/callback \\ -H &#39;authorization: Bearer {api-key}&#39; \\ -H &#39;content-type: application/json&#39; \\ -d &#39;{ \&quot;url\&quot;: \&quot;{callback-url}\&quot;, \&quot;headers\&quot;: {\&quot;authorization\&quot; : \&quot;f4b93d6e-4652-4874-82e4-41a3ced0cd56\&quot;} }&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="webhook">A json object that contains the optional headers and the URL to which the notifications need to be sent. </param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> RegisterWebhookAsyncWithHttpInfo (Webhook webhook); /// <summary> /// Register a websocket channel /// </summary> /// <remarks> /// Register (or update) a channel which will use websocket connection to deliver notifications. The websocket channel should be opened by client using &#x60;/v2/notification/websocket-connect&#x60; endpoint. To get notifications pushed, you also need to place the subscriptions. For more information on notification messages, see [NotificationMessage](#NotificationMessage). A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed. **Expiration of a websocket:** A websocket channel will be expired if the channel does not have an opened websocket connection for 24 hour period. Channel expiration means the channel will be deleted and any undelivered notifications stored in its internal queue will be removed. As long as the channel has an opened websocket connection or time between successive websocket connections is less than 24 hours, the channel is considered active, notifications are stored in its internal queue and delivered when a websocket connection is active. A channel can be also deleted explicitly by a DELETE call. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Example usage:** curl -X PUT https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of WebsocketChannel</returns> System.Threading.Tasks.Task<WebsocketChannel> RegisterWebsocketAsync (); /// <summary> /// Register a websocket channel /// </summary> /// <remarks> /// Register (or update) a channel which will use websocket connection to deliver notifications. The websocket channel should be opened by client using &#x60;/v2/notification/websocket-connect&#x60; endpoint. To get notifications pushed, you also need to place the subscriptions. For more information on notification messages, see [NotificationMessage](#NotificationMessage). A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed. **Expiration of a websocket:** A websocket channel will be expired if the channel does not have an opened websocket connection for 24 hour period. Channel expiration means the channel will be deleted and any undelivered notifications stored in its internal queue will be removed. As long as the channel has an opened websocket connection or time between successive websocket connections is less than 24 hours, the channel is considered active, notifications are stored in its internal queue and delivered when a websocket connection is active. A channel can be also deleted explicitly by a DELETE call. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Example usage:** curl -X PUT https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </remarks> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (WebsocketChannel)</returns> System.Threading.Tasks.Task<ApiResponse<WebsocketChannel>> RegisterWebsocketAsyncWithHttpInfo (); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class NotificationsApi : INotificationsApi { private mds.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="NotificationsApi"/> class. /// </summary> /// <returns></returns> public NotificationsApi(String basePath) { this.Configuration = new Configuration { BasePath = basePath }; ExceptionFactory = mds.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="NotificationsApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public NotificationsApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = mds.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public mds.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public IDictionary<String, String> DefaultHeader() { return new ReadOnlyDictionary<string, string>(this.Configuration.DefaultHeader); } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Open the websocket. A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed.&lt;br/&gt; Once the socket has been opened, it may be closed with one of the following status codes&lt;br/&gt; **1000**: Socket closed by the client. **1001**: Going away. set when another socket was opened on the used channel, or if the channel was deleted with a REST call, or if the server is shutting down. **1006**: Abnormal loss of connection. This code is never set by the service. **1008**: Policy violation. Set when the API key is missing or invalid. **1011**: Unexpected condition. Socket will be closed with this status at an attempt to open a socket to an unexisting channel (without a prior REST PUT). This code is also used to indicate closing socket for any other unexpected condition in the server. /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="connection"></param> /// <param name="upgrade"></param> /// <param name="secWebSocketProtocol">ApiKey must be present in the &#x60;Sec-WebSocket-Protocol&#x60; header &#x60;\&quot;Sec-WebSocket-Protocol\&quot;:\&quot;wss,pelion_ak_{api_key}\&quot;&#x60; Refer to the notification service documentation for examples of usage. </param> /// <returns></returns> public void ConnectWebsocket (string connection, string upgrade, string secWebSocketProtocol) { ConnectWebsocketWithHttpInfo(connection, upgrade, secWebSocketProtocol); } /// <summary> /// Open the websocket. A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed.&lt;br/&gt; Once the socket has been opened, it may be closed with one of the following status codes&lt;br/&gt; **1000**: Socket closed by the client. **1001**: Going away. set when another socket was opened on the used channel, or if the channel was deleted with a REST call, or if the server is shutting down. **1006**: Abnormal loss of connection. This code is never set by the service. **1008**: Policy violation. Set when the API key is missing or invalid. **1011**: Unexpected condition. Socket will be closed with this status at an attempt to open a socket to an unexisting channel (without a prior REST PUT). This code is also used to indicate closing socket for any other unexpected condition in the server. /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="connection"></param> /// <param name="upgrade"></param> /// <param name="secWebSocketProtocol">ApiKey must be present in the &#x60;Sec-WebSocket-Protocol&#x60; header &#x60;\&quot;Sec-WebSocket-Protocol\&quot;:\&quot;wss,pelion_ak_{api_key}\&quot;&#x60; Refer to the notification service documentation for examples of usage. </param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> ConnectWebsocketWithHttpInfo (string connection, string upgrade, string secWebSocketProtocol) { // verify the required parameter 'connection' is set if (connection == null) throw new ApiException(400, "Missing required parameter 'connection' when calling NotificationsApi->ConnectWebsocket"); // verify the required parameter 'upgrade' is set if (upgrade == null) throw new ApiException(400, "Missing required parameter 'upgrade' when calling NotificationsApi->ConnectWebsocket"); // verify the required parameter 'secWebSocketProtocol' is set if (secWebSocketProtocol == null) throw new ApiException(400, "Missing required parameter 'secWebSocketProtocol' when calling NotificationsApi->ConnectWebsocket"); var localVarPath = "/v2/notification/websocket-connect"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (connection != null) localVarHeaderParams.Add("Connection", Configuration.ApiClient.ParameterToString(connection)); // header parameter if (upgrade != null) localVarHeaderParams.Add("Upgrade", Configuration.ApiClient.ParameterToString(upgrade)); // header parameter if (secWebSocketProtocol != null) localVarHeaderParams.Add("Sec-WebSocket-Protocol", Configuration.ApiClient.ParameterToString(secWebSocketProtocol)); // header parameter // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ConnectWebsocket", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Open the websocket. A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed.&lt;br/&gt; Once the socket has been opened, it may be closed with one of the following status codes&lt;br/&gt; **1000**: Socket closed by the client. **1001**: Going away. set when another socket was opened on the used channel, or if the channel was deleted with a REST call, or if the server is shutting down. **1006**: Abnormal loss of connection. This code is never set by the service. **1008**: Policy violation. Set when the API key is missing or invalid. **1011**: Unexpected condition. Socket will be closed with this status at an attempt to open a socket to an unexisting channel (without a prior REST PUT). This code is also used to indicate closing socket for any other unexpected condition in the server. /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="connection"></param> /// <param name="upgrade"></param> /// <param name="secWebSocketProtocol">ApiKey must be present in the &#x60;Sec-WebSocket-Protocol&#x60; header &#x60;\&quot;Sec-WebSocket-Protocol\&quot;:\&quot;wss,pelion_ak_{api_key}\&quot;&#x60; Refer to the notification service documentation for examples of usage. </param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task ConnectWebsocketAsync (string connection, string upgrade, string secWebSocketProtocol) { await ConnectWebsocketAsyncWithHttpInfo(connection, upgrade, secWebSocketProtocol); } /// <summary> /// Open the websocket. A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed.&lt;br/&gt; Once the socket has been opened, it may be closed with one of the following status codes&lt;br/&gt; **1000**: Socket closed by the client. **1001**: Going away. set when another socket was opened on the used channel, or if the channel was deleted with a REST call, or if the server is shutting down. **1006**: Abnormal loss of connection. This code is never set by the service. **1008**: Policy violation. Set when the API key is missing or invalid. **1011**: Unexpected condition. Socket will be closed with this status at an attempt to open a socket to an unexisting channel (without a prior REST PUT). This code is also used to indicate closing socket for any other unexpected condition in the server. /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="connection"></param> /// <param name="upgrade"></param> /// <param name="secWebSocketProtocol">ApiKey must be present in the &#x60;Sec-WebSocket-Protocol&#x60; header &#x60;\&quot;Sec-WebSocket-Protocol\&quot;:\&quot;wss,pelion_ak_{api_key}\&quot;&#x60; Refer to the notification service documentation for examples of usage. </param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> ConnectWebsocketAsyncWithHttpInfo (string connection, string upgrade, string secWebSocketProtocol) { // verify the required parameter 'connection' is set if (connection == null) throw new ApiException(400, "Missing required parameter 'connection' when calling NotificationsApi->ConnectWebsocket"); // verify the required parameter 'upgrade' is set if (upgrade == null) throw new ApiException(400, "Missing required parameter 'upgrade' when calling NotificationsApi->ConnectWebsocket"); // verify the required parameter 'secWebSocketProtocol' is set if (secWebSocketProtocol == null) throw new ApiException(400, "Missing required parameter 'secWebSocketProtocol' when calling NotificationsApi->ConnectWebsocket"); var localVarPath = "/v2/notification/websocket-connect"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (connection != null) localVarHeaderParams.Add("Connection", Configuration.ApiClient.ParameterToString(connection)); // header parameter if (upgrade != null) localVarHeaderParams.Add("Upgrade", Configuration.ApiClient.ParameterToString(upgrade)); // header parameter if (secWebSocketProtocol != null) localVarHeaderParams.Add("Sec-WebSocket-Protocol", Configuration.ApiClient.ParameterToString(secWebSocketProtocol)); // header parameter // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ConnectWebsocket", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete notification Long Poll channel To delete a notification Long Poll channel. This is required to change the channel from Long Poll to another type. You should not make a GET &#x60;/v2/notification/pull&#x60; call for 2 minutes after channel was deleted, because it can implicitly recreate the pull channel. You can also have some random responses with payload or 410 GONE with \&quot;CHANNEL_DELETED\&quot; as a payload or 200/204 until the old channel is purged. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns></returns> public void DeleteLongPollChannel () { DeleteLongPollChannelWithHttpInfo(); } /// <summary> /// Delete notification Long Poll channel To delete a notification Long Poll channel. This is required to change the channel from Long Poll to another type. You should not make a GET &#x60;/v2/notification/pull&#x60; call for 2 minutes after channel was deleted, because it can implicitly recreate the pull channel. You can also have some random responses with payload or 410 GONE with \&quot;CHANNEL_DELETED\&quot; as a payload or 200/204 until the old channel is purged. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> DeleteLongPollChannelWithHttpInfo () { var localVarPath = "/v2/notification/pull"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteLongPollChannel", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete notification Long Poll channel To delete a notification Long Poll channel. This is required to change the channel from Long Poll to another type. You should not make a GET &#x60;/v2/notification/pull&#x60; call for 2 minutes after channel was deleted, because it can implicitly recreate the pull channel. You can also have some random responses with payload or 410 GONE with \&quot;CHANNEL_DELETED\&quot; as a payload or 200/204 until the old channel is purged. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task DeleteLongPollChannelAsync () { await DeleteLongPollChannelAsyncWithHttpInfo(); } /// <summary> /// Delete notification Long Poll channel To delete a notification Long Poll channel. This is required to change the channel from Long Poll to another type. You should not make a GET &#x60;/v2/notification/pull&#x60; call for 2 minutes after channel was deleted, because it can implicitly recreate the pull channel. You can also have some random responses with payload or 410 GONE with \&quot;CHANNEL_DELETED\&quot; as a payload or 200/204 until the old channel is purged. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteLongPollChannelAsyncWithHttpInfo () { var localVarPath = "/v2/notification/pull"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteLongPollChannel", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete websocket channel. To delete a notification websocket channel bound to the API key. This is required to change the channel from websocket to another type. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns></returns> public void DeleteWebsocket () { DeleteWebsocketWithHttpInfo(); } /// <summary> /// Delete websocket channel. To delete a notification websocket channel bound to the API key. This is required to change the channel from websocket to another type. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> DeleteWebsocketWithHttpInfo () { var localVarPath = "/v2/notification/websocket"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteWebsocket", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete websocket channel. To delete a notification websocket channel bound to the API key. This is required to change the channel from websocket to another type. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task DeleteWebsocketAsync () { await DeleteWebsocketAsyncWithHttpInfo(); } /// <summary> /// Delete websocket channel. To delete a notification websocket channel bound to the API key. This is required to change the channel from websocket to another type. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteWebsocketAsyncWithHttpInfo () { var localVarPath = "/v2/notification/websocket"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteWebsocket", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete callback URL Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns></returns> public void DeregisterWebhook () { DeregisterWebhookWithHttpInfo(); } /// <summary> /// Delete callback URL Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> DeregisterWebhookWithHttpInfo () { var localVarPath = "/v2/notification/callback"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeregisterWebhook", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete callback URL Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task DeregisterWebhookAsync () { await DeregisterWebhookAsyncWithHttpInfo(); } /// <summary> /// Delete callback URL Deletes the callback URL. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> DeregisterWebhookAsyncWithHttpInfo () { var localVarPath = "/v2/notification/callback"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeregisterWebhook", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Check callback URL Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Webhook</returns> public Webhook GetWebhook () { ApiResponse<Webhook> localVarResponse = GetWebhookWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Check callback URL Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of Webhook</returns> public ApiResponse< Webhook > GetWebhookWithHttpInfo () { var localVarPath = "/v2/notification/callback"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWebhook", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Webhook>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Webhook) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Webhook))); } /// <summary> /// Check callback URL Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of Webhook</returns> public async System.Threading.Tasks.Task<Webhook> GetWebhookAsync () { ApiResponse<Webhook> localVarResponse = await GetWebhookAsyncWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Check callback URL Shows the current callback URL if it exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/callback -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (Webhook)</returns> public async System.Threading.Tasks.Task<ApiResponse<Webhook>> GetWebhookAsyncWithHttpInfo () { var localVarPath = "/v2/notification/callback"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWebhook", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Webhook>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Webhook) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Webhook))); } /// <summary> /// Get websocket channel information. Returns 200 with websocket connection status if websocket channel exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>WebsocketChannel</returns> public WebsocketChannel GetWebsocket () { ApiResponse<WebsocketChannel> localVarResponse = GetWebsocketWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Get websocket channel information. Returns 200 with websocket connection status if websocket channel exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of WebsocketChannel</returns> public ApiResponse< WebsocketChannel > GetWebsocketWithHttpInfo () { var localVarPath = "/v2/notification/websocket"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWebsocket", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<WebsocketChannel>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (WebsocketChannel) Configuration.ApiClient.Deserialize(localVarResponse, typeof(WebsocketChannel))); } /// <summary> /// Get websocket channel information. Returns 200 with websocket connection status if websocket channel exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of WebsocketChannel</returns> public async System.Threading.Tasks.Task<WebsocketChannel> GetWebsocketAsync () { ApiResponse<WebsocketChannel> localVarResponse = await GetWebsocketAsyncWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Get websocket channel information. Returns 200 with websocket connection status if websocket channel exists. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (WebsocketChannel)</returns> public async System.Threading.Tasks.Task<ApiResponse<WebsocketChannel>> GetWebsocketAsyncWithHttpInfo () { var localVarPath = "/v2/notification/websocket"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWebsocket", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<WebsocketChannel>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (WebsocketChannel) Configuration.ApiClient.Deserialize(localVarResponse, typeof(WebsocketChannel))); } /// <summary> /// Get notifications using Long Poll In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client or the request times out (response code 204). In both cases, the client should open a new polling connection after the previous one closes. Only a single long polling connection per API key can be ongoing at any given time. You must have a persistent connection (Connection keep-alive header in the request) to avoid excess TLS handshakes. The pull channel is implicitly created by the first GET call to &#x60;/v2/notification/pull&#x60;. It is refreshed on each GET call. If the channel is not polled for a long time (10 minutes) - it expires and will be deleted. This means that no notifications will stay in the queue between polls. A channel can be also deleted explicitly by a DELETE call. **Note:** If you cannot have a public facing callback URL, for example when developing on your local machine, you can use long polling to check for new messages. However, **long polling is deprecated** and will likely be replaced in future. It is meant only for experimentation and not for commercial usage. The proper method to receive notifications is a **notification callback**. There can only be one notification channel per API key at a time in Device Management Connect. If a notification channel of other type already exists for the API key, you need to delete it before creating a long poll notification channel. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>NotificationMessage</returns> public NotificationMessage LongPollNotifications () { ApiResponse<NotificationMessage> localVarResponse = LongPollNotificationsWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Get notifications using Long Poll In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client or the request times out (response code 204). In both cases, the client should open a new polling connection after the previous one closes. Only a single long polling connection per API key can be ongoing at any given time. You must have a persistent connection (Connection keep-alive header in the request) to avoid excess TLS handshakes. The pull channel is implicitly created by the first GET call to &#x60;/v2/notification/pull&#x60;. It is refreshed on each GET call. If the channel is not polled for a long time (10 minutes) - it expires and will be deleted. This means that no notifications will stay in the queue between polls. A channel can be also deleted explicitly by a DELETE call. **Note:** If you cannot have a public facing callback URL, for example when developing on your local machine, you can use long polling to check for new messages. However, **long polling is deprecated** and will likely be replaced in future. It is meant only for experimentation and not for commercial usage. The proper method to receive notifications is a **notification callback**. There can only be one notification channel per API key at a time in Device Management Connect. If a notification channel of other type already exists for the API key, you need to delete it before creating a long poll notification channel. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of NotificationMessage</returns> public ApiResponse< NotificationMessage > LongPollNotificationsWithHttpInfo () { var localVarPath = "/v2/notification/pull"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("LongPollNotifications", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<NotificationMessage>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NotificationMessage) Configuration.ApiClient.Deserialize(localVarResponse, typeof(NotificationMessage))); } /// <summary> /// Get notifications using Long Poll In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client or the request times out (response code 204). In both cases, the client should open a new polling connection after the previous one closes. Only a single long polling connection per API key can be ongoing at any given time. You must have a persistent connection (Connection keep-alive header in the request) to avoid excess TLS handshakes. The pull channel is implicitly created by the first GET call to &#x60;/v2/notification/pull&#x60;. It is refreshed on each GET call. If the channel is not polled for a long time (10 minutes) - it expires and will be deleted. This means that no notifications will stay in the queue between polls. A channel can be also deleted explicitly by a DELETE call. **Note:** If you cannot have a public facing callback URL, for example when developing on your local machine, you can use long polling to check for new messages. However, **long polling is deprecated** and will likely be replaced in future. It is meant only for experimentation and not for commercial usage. The proper method to receive notifications is a **notification callback**. There can only be one notification channel per API key at a time in Device Management Connect. If a notification channel of other type already exists for the API key, you need to delete it before creating a long poll notification channel. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of NotificationMessage</returns> public async System.Threading.Tasks.Task<NotificationMessage> LongPollNotificationsAsync (CancellationToken token) { ApiResponse<NotificationMessage> localVarResponse = await LongPollNotificationsAsyncWithHttpInfo(token); return localVarResponse.Data; } /// <summary> /// Get notifications using Long Poll In this case, notifications are delivered through HTTP long poll requests. The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client or the request times out (response code 204). In both cases, the client should open a new polling connection after the previous one closes. Only a single long polling connection per API key can be ongoing at any given time. You must have a persistent connection (Connection keep-alive header in the request) to avoid excess TLS handshakes. The pull channel is implicitly created by the first GET call to &#x60;/v2/notification/pull&#x60;. It is refreshed on each GET call. If the channel is not polled for a long time (10 minutes) - it expires and will be deleted. This means that no notifications will stay in the queue between polls. A channel can be also deleted explicitly by a DELETE call. **Note:** If you cannot have a public facing callback URL, for example when developing on your local machine, you can use long polling to check for new messages. However, **long polling is deprecated** and will likely be replaced in future. It is meant only for experimentation and not for commercial usage. The proper method to receive notifications is a **notification callback**. There can only be one notification channel per API key at a time in Device Management Connect. If a notification channel of other type already exists for the API key, you need to delete it before creating a long poll notification channel. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/notification/pull -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (NotificationMessage)</returns> public async System.Threading.Tasks.Task<ApiResponse<NotificationMessage>> LongPollNotificationsAsyncWithHttpInfo (CancellationToken token = default) { var localVarPath = "/v2/notification/pull"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType, token); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("LongPollNotifications", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<NotificationMessage>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (NotificationMessage) Configuration.ApiClient.Deserialize(localVarResponse, typeof(NotificationMessage))); } /// <summary> /// Register a callback URL Register a URL to which the server should deliver notifications of the subscribed resource changes. To get notifications pushed, you also need to place the subscriptions. The maximum length of the URL, header keys and values, all combined, is 400 characters. Notifications are delivered as PUT messages to the HTTP server defined by the client with a subscription server message. The given URL should be accessible and respond to the PUT request with response code of 200 or 204. Device Management Connect tests the callback URL with an empty payload when the URL is registered. For more information on notification messages, see [NotificationMessage](#NotificationMessage). **Optional headers in a callback message:** You can set optional headers to a callback in a **Webhook** object. Device Management Connect will include the header and key pairs to the notification messages send them to callback URL. As the callback URL&#39;s are API key specific also the headers are. One possible use for the additional headers is to check the origin of a PUT request and also distinguish the application (API key) to which the notification belongs to. **Note**: Only one callback URL per an API key can be active. If you register a new URL while another one is already active, it replaces the active one. There can be only one notification channel at a time. If another type of channel is already present, you need to delete it before setting the callback URL. **Expiration of a callback URL:** A callback can expire when Device Management cannot deliver a notification due to a connection timeout or an error response (4xx or 5xx). After each delivery failure, Device Management sets an exponential back off time and makes a retry attempt after that. The first retry delay is 1 second, then 2s, 4s, 8s, ..., 2min, 2min. The maximum retry delay is 2 minutes. The callback URL will be removed if all retries fail within 24 hours. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Supported callback URL protocols:** Currently, only HTTP and HTTPS protocols are supported. **HTTPS callback URLs:** When delivering a notification to an HTTPS based callback URL, Device Management Connect will present a valid client certificate to identify itself. The certificate is signed by a trusted certificate authorithy (GlobalSign) with a Common Name (CN) set to notifications.mbedcloud.com. **Example usage:** This example command shows how to set your callback URL and API key. It also sets an optional header authorization. When Device Management Connect calls your callback URL, the call contains the authorization header with the defined value. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/notification/callback \\ -H &#39;authorization: Bearer {api-key}&#39; \\ -H &#39;content-type: application/json&#39; \\ -d &#39;{ \&quot;url\&quot;: \&quot;{callback-url}\&quot;, \&quot;headers\&quot;: {\&quot;authorization\&quot; : \&quot;f4b93d6e-4652-4874-82e4-41a3ced0cd56\&quot;} }&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="webhook">A json object that contains the optional headers and the URL to which the notifications need to be sent. </param> /// <returns></returns> public void RegisterWebhook (Webhook webhook) { RegisterWebhookWithHttpInfo(webhook); } /// <summary> /// Register a callback URL Register a URL to which the server should deliver notifications of the subscribed resource changes. To get notifications pushed, you also need to place the subscriptions. The maximum length of the URL, header keys and values, all combined, is 400 characters. Notifications are delivered as PUT messages to the HTTP server defined by the client with a subscription server message. The given URL should be accessible and respond to the PUT request with response code of 200 or 204. Device Management Connect tests the callback URL with an empty payload when the URL is registered. For more information on notification messages, see [NotificationMessage](#NotificationMessage). **Optional headers in a callback message:** You can set optional headers to a callback in a **Webhook** object. Device Management Connect will include the header and key pairs to the notification messages send them to callback URL. As the callback URL&#39;s are API key specific also the headers are. One possible use for the additional headers is to check the origin of a PUT request and also distinguish the application (API key) to which the notification belongs to. **Note**: Only one callback URL per an API key can be active. If you register a new URL while another one is already active, it replaces the active one. There can be only one notification channel at a time. If another type of channel is already present, you need to delete it before setting the callback URL. **Expiration of a callback URL:** A callback can expire when Device Management cannot deliver a notification due to a connection timeout or an error response (4xx or 5xx). After each delivery failure, Device Management sets an exponential back off time and makes a retry attempt after that. The first retry delay is 1 second, then 2s, 4s, 8s, ..., 2min, 2min. The maximum retry delay is 2 minutes. The callback URL will be removed if all retries fail within 24 hours. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Supported callback URL protocols:** Currently, only HTTP and HTTPS protocols are supported. **HTTPS callback URLs:** When delivering a notification to an HTTPS based callback URL, Device Management Connect will present a valid client certificate to identify itself. The certificate is signed by a trusted certificate authorithy (GlobalSign) with a Common Name (CN) set to notifications.mbedcloud.com. **Example usage:** This example command shows how to set your callback URL and API key. It also sets an optional header authorization. When Device Management Connect calls your callback URL, the call contains the authorization header with the defined value. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/notification/callback \\ -H &#39;authorization: Bearer {api-key}&#39; \\ -H &#39;content-type: application/json&#39; \\ -d &#39;{ \&quot;url\&quot;: \&quot;{callback-url}\&quot;, \&quot;headers\&quot;: {\&quot;authorization\&quot; : \&quot;f4b93d6e-4652-4874-82e4-41a3ced0cd56\&quot;} }&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="webhook">A json object that contains the optional headers and the URL to which the notifications need to be sent. </param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> RegisterWebhookWithHttpInfo (Webhook webhook) { // verify the required parameter 'webhook' is set if (webhook == null) throw new ApiException(400, "Missing required parameter 'webhook' when calling NotificationsApi->RegisterWebhook"); var localVarPath = "/v2/notification/callback"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (webhook != null && webhook.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(webhook); // http body (model) parameter } else { localVarPostBody = webhook; // byte array } // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("RegisterWebhook", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Register a callback URL Register a URL to which the server should deliver notifications of the subscribed resource changes. To get notifications pushed, you also need to place the subscriptions. The maximum length of the URL, header keys and values, all combined, is 400 characters. Notifications are delivered as PUT messages to the HTTP server defined by the client with a subscription server message. The given URL should be accessible and respond to the PUT request with response code of 200 or 204. Device Management Connect tests the callback URL with an empty payload when the URL is registered. For more information on notification messages, see [NotificationMessage](#NotificationMessage). **Optional headers in a callback message:** You can set optional headers to a callback in a **Webhook** object. Device Management Connect will include the header and key pairs to the notification messages send them to callback URL. As the callback URL&#39;s are API key specific also the headers are. One possible use for the additional headers is to check the origin of a PUT request and also distinguish the application (API key) to which the notification belongs to. **Note**: Only one callback URL per an API key can be active. If you register a new URL while another one is already active, it replaces the active one. There can be only one notification channel at a time. If another type of channel is already present, you need to delete it before setting the callback URL. **Expiration of a callback URL:** A callback can expire when Device Management cannot deliver a notification due to a connection timeout or an error response (4xx or 5xx). After each delivery failure, Device Management sets an exponential back off time and makes a retry attempt after that. The first retry delay is 1 second, then 2s, 4s, 8s, ..., 2min, 2min. The maximum retry delay is 2 minutes. The callback URL will be removed if all retries fail within 24 hours. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Supported callback URL protocols:** Currently, only HTTP and HTTPS protocols are supported. **HTTPS callback URLs:** When delivering a notification to an HTTPS based callback URL, Device Management Connect will present a valid client certificate to identify itself. The certificate is signed by a trusted certificate authorithy (GlobalSign) with a Common Name (CN) set to notifications.mbedcloud.com. **Example usage:** This example command shows how to set your callback URL and API key. It also sets an optional header authorization. When Device Management Connect calls your callback URL, the call contains the authorization header with the defined value. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/notification/callback \\ -H &#39;authorization: Bearer {api-key}&#39; \\ -H &#39;content-type: application/json&#39; \\ -d &#39;{ \&quot;url\&quot;: \&quot;{callback-url}\&quot;, \&quot;headers\&quot;: {\&quot;authorization\&quot; : \&quot;f4b93d6e-4652-4874-82e4-41a3ced0cd56\&quot;} }&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="webhook">A json object that contains the optional headers and the URL to which the notifications need to be sent. </param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task RegisterWebhookAsync (Webhook webhook) { await RegisterWebhookAsyncWithHttpInfo(webhook); } /// <summary> /// Register a callback URL Register a URL to which the server should deliver notifications of the subscribed resource changes. To get notifications pushed, you also need to place the subscriptions. The maximum length of the URL, header keys and values, all combined, is 400 characters. Notifications are delivered as PUT messages to the HTTP server defined by the client with a subscription server message. The given URL should be accessible and respond to the PUT request with response code of 200 or 204. Device Management Connect tests the callback URL with an empty payload when the URL is registered. For more information on notification messages, see [NotificationMessage](#NotificationMessage). **Optional headers in a callback message:** You can set optional headers to a callback in a **Webhook** object. Device Management Connect will include the header and key pairs to the notification messages send them to callback URL. As the callback URL&#39;s are API key specific also the headers are. One possible use for the additional headers is to check the origin of a PUT request and also distinguish the application (API key) to which the notification belongs to. **Note**: Only one callback URL per an API key can be active. If you register a new URL while another one is already active, it replaces the active one. There can be only one notification channel at a time. If another type of channel is already present, you need to delete it before setting the callback URL. **Expiration of a callback URL:** A callback can expire when Device Management cannot deliver a notification due to a connection timeout or an error response (4xx or 5xx). After each delivery failure, Device Management sets an exponential back off time and makes a retry attempt after that. The first retry delay is 1 second, then 2s, 4s, 8s, ..., 2min, 2min. The maximum retry delay is 2 minutes. The callback URL will be removed if all retries fail within 24 hours. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Supported callback URL protocols:** Currently, only HTTP and HTTPS protocols are supported. **HTTPS callback URLs:** When delivering a notification to an HTTPS based callback URL, Device Management Connect will present a valid client certificate to identify itself. The certificate is signed by a trusted certificate authorithy (GlobalSign) with a Common Name (CN) set to notifications.mbedcloud.com. **Example usage:** This example command shows how to set your callback URL and API key. It also sets an optional header authorization. When Device Management Connect calls your callback URL, the call contains the authorization header with the defined value. curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/notification/callback \\ -H &#39;authorization: Bearer {api-key}&#39; \\ -H &#39;content-type: application/json&#39; \\ -d &#39;{ \&quot;url\&quot;: \&quot;{callback-url}\&quot;, \&quot;headers\&quot;: {\&quot;authorization\&quot; : \&quot;f4b93d6e-4652-4874-82e4-41a3ced0cd56\&quot;} }&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="webhook">A json object that contains the optional headers and the URL to which the notifications need to be sent. </param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> RegisterWebhookAsyncWithHttpInfo (Webhook webhook) { // verify the required parameter 'webhook' is set if (webhook == null) throw new ApiException(400, "Missing required parameter 'webhook' when calling NotificationsApi->RegisterWebhook"); var localVarPath = "/v2/notification/callback"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (webhook != null && webhook.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(webhook); // http body (model) parameter } else { localVarPostBody = webhook; // byte array } // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("RegisterWebhook", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Register a websocket channel Register (or update) a channel which will use websocket connection to deliver notifications. The websocket channel should be opened by client using &#x60;/v2/notification/websocket-connect&#x60; endpoint. To get notifications pushed, you also need to place the subscriptions. For more information on notification messages, see [NotificationMessage](#NotificationMessage). A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed. **Expiration of a websocket:** A websocket channel will be expired if the channel does not have an opened websocket connection for 24 hour period. Channel expiration means the channel will be deleted and any undelivered notifications stored in its internal queue will be removed. As long as the channel has an opened websocket connection or time between successive websocket connections is less than 24 hours, the channel is considered active, notifications are stored in its internal queue and delivered when a websocket connection is active. A channel can be also deleted explicitly by a DELETE call. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Example usage:** curl -X PUT https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>WebsocketChannel</returns> public WebsocketChannel RegisterWebsocket () { ApiResponse<WebsocketChannel> localVarResponse = RegisterWebsocketWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Register a websocket channel Register (or update) a channel which will use websocket connection to deliver notifications. The websocket channel should be opened by client using &#x60;/v2/notification/websocket-connect&#x60; endpoint. To get notifications pushed, you also need to place the subscriptions. For more information on notification messages, see [NotificationMessage](#NotificationMessage). A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed. **Expiration of a websocket:** A websocket channel will be expired if the channel does not have an opened websocket connection for 24 hour period. Channel expiration means the channel will be deleted and any undelivered notifications stored in its internal queue will be removed. As long as the channel has an opened websocket connection or time between successive websocket connections is less than 24 hours, the channel is considered active, notifications are stored in its internal queue and delivered when a websocket connection is active. A channel can be also deleted explicitly by a DELETE call. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Example usage:** curl -X PUT https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>ApiResponse of WebsocketChannel</returns> public ApiResponse< WebsocketChannel > RegisterWebsocketWithHttpInfo () { var localVarPath = "/v2/notification/websocket"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("RegisterWebsocket", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<WebsocketChannel>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (WebsocketChannel) Configuration.ApiClient.Deserialize(localVarResponse, typeof(WebsocketChannel))); } /// <summary> /// Register a websocket channel Register (or update) a channel which will use websocket connection to deliver notifications. The websocket channel should be opened by client using &#x60;/v2/notification/websocket-connect&#x60; endpoint. To get notifications pushed, you also need to place the subscriptions. For more information on notification messages, see [NotificationMessage](#NotificationMessage). A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed. **Expiration of a websocket:** A websocket channel will be expired if the channel does not have an opened websocket connection for 24 hour period. Channel expiration means the channel will be deleted and any undelivered notifications stored in its internal queue will be removed. As long as the channel has an opened websocket connection or time between successive websocket connections is less than 24 hours, the channel is considered active, notifications are stored in its internal queue and delivered when a websocket connection is active. A channel can be also deleted explicitly by a DELETE call. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Example usage:** curl -X PUT https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of WebsocketChannel</returns> public async System.Threading.Tasks.Task<WebsocketChannel> RegisterWebsocketAsync () { ApiResponse<WebsocketChannel> localVarResponse = await RegisterWebsocketAsyncWithHttpInfo(); return localVarResponse.Data; } /// <summary> /// Register a websocket channel Register (or update) a channel which will use websocket connection to deliver notifications. The websocket channel should be opened by client using &#x60;/v2/notification/websocket-connect&#x60; endpoint. To get notifications pushed, you also need to place the subscriptions. For more information on notification messages, see [NotificationMessage](#NotificationMessage). A websocket channel can have only one active websocket connection at a time. If a websocket connection for a channel exists and a new connection to the same channel is made the connection is accepted and the older connection will be closed. **Expiration of a websocket:** A websocket channel will be expired if the channel does not have an opened websocket connection for 24 hour period. Channel expiration means the channel will be deleted and any undelivered notifications stored in its internal queue will be removed. As long as the channel has an opened websocket connection or time between successive websocket connections is less than 24 hours, the channel is considered active, notifications are stored in its internal queue and delivered when a websocket connection is active. A channel can be also deleted explicitly by a DELETE call. More about [notification sending logic](/docs/current/integrate-web-app/event-notification.html#notification-sending-logic). **Example usage:** curl -X PUT https://api.us-east-1.mbedcloud.com/v2/notification/websocket -H &#39;authorization: Bearer {api-key}&#39; /// </summary> /// <exception cref="mds.Client.ApiException">Thrown when fails to make API call</exception> /// <returns>Task of ApiResponse (WebsocketChannel)</returns> public async System.Threading.Tasks.Task<ApiResponse<WebsocketChannel>> RegisterWebsocketAsyncWithHttpInfo () { var localVarPath = "/v2/notification/websocket"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("RegisterWebsocket", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<WebsocketChannel>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (WebsocketChannel) Configuration.ApiClient.Deserialize(localVarResponse, typeof(WebsocketChannel))); } } }
88.607935
3,149
0.691264
[ "Apache-2.0" ]
ARMmbed/mbed-cloud-sdk-dotnet
src/Legacy/Backends/Mds/Api/NotificationsApi.cs
151,874
C#
using System.Runtime.Serialization; namespace PlaywrightSharp { /// <summary> /// Options for <see cref="IPage.EmulateMediaAsync(MediaType?, ColorScheme?)"/>. /// </summary> public enum ColorScheme { /// <summary> /// Light /// </summary> [EnumMember(Value = "light")] Light, /// <summary> /// Dark /// </summary> [EnumMember(Value = "dark")] Dark, /// <summary> /// No preference /// </summary> [EnumMember(Value = "no-preference")] NoPreference, } }
20.655172
84
0.499165
[ "MIT" ]
Magicianred/playwright-sharp
src/PlaywrightSharp/ColorScheme.cs
599
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IMethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookFilterApplyRequest. /// </summary> public partial interface IWorkbookFilterApplyRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> WorkbookFilterApplyRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task PostAsync( CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWorkbookFilterApplyRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookFilterApplyRequest Select(string value); } }
32.031746
153
0.576809
[ "MIT" ]
andrueastman/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IWorkbookFilterApplyRequest.cs
2,018
C#
// Copyright Bastian Eicher // Licensed under the MIT License using System.Globalization; using System.Xml.Serialization; namespace NanoByte.Common.Values.Design; /// <summary> /// Type converter for <see cref="Enum"/>s annotated with <see cref="XmlEnumAttribute"/>s. /// </summary> /// <typeparam name="T">The type the converter is used for.</typeparam> /// <example> /// Add this attribute to the <see cref="Enum"/>: /// <code>[TypeConverter(typeof(XmlEnumConverter&lt;NameOfEnum&gt;))]</code> /// </example> /// <remarks><see cref="XmlEnumAttribute.Name"/> is used as the case-insensitive string representation (falls back to element name).</remarks> public class EnumXmlConverter<T> : TypeConverter where T : struct { private static object GetEnumFromString(string stringValue) { foreach (var field in typeof(T).GetFields()) { var attributes = (XmlEnumAttribute[])field.GetCustomAttributes(typeof(XmlEnumAttribute), inherit: false); if (attributes.Length > 0 && StringUtils.EqualsIgnoreCase(attributes[0].Name, stringValue)) return field.GetValue(field.Name)!; } return Enum.Parse(typeof(T), stringValue, ignoreCase: true); } /// <inheritdoc/> public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); /// <inheritdoc/> public override object ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) => value is string stringValue ? GetEnumFromString(stringValue) : base.ConvertFrom(context!, culture!, value)!; /// <inheritdoc/> public override object ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) => value is Enum enumValue && destinationType == typeof(string) ? enumValue.GetEnumAttribute<XmlEnumAttribute>()?.Name ?? enumValue.ToString()! : base.ConvertTo(context, culture, value, destinationType)!; public override bool GetStandardValuesSupported(ITypeDescriptorContext? context) => true; public override bool GetStandardValuesExclusive(ITypeDescriptorContext? context) => true; private static readonly string[] _values = (from T value in Enum.GetValues(typeof(T)) select value.ConvertToString()).ToArray(); public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext? context) => new(_values); }
46.909091
143
0.695736
[ "MIT" ]
nano-byte/common
src/Common/Values/Design/EnumXmlConverter.cs
2,580
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("Linear2(stack)")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Linear2(stack)")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("55939bf7-9c17-41f0-80fc-e79181fcf990")] // 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")]
37.72973
84
0.745702
[ "MIT" ]
cheficha/TelerikAcademyAlpha
Linear2(stack)/Linear2(stack)/Properties/AssemblyInfo.cs
1,399
C#
using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; using Attribute = Android.Resource.Attribute; using AndroidX.ConstraintLayout.Widget; using Yang.Maui.Helper.Devices.Screen; using Android.Content.Res; using Android.Graphics.Drawables; using System.Linq; namespace Yang.Maui.Helper.Platforms.Android.UI { /// <summary> /// 辅助View实现轮廓为圆角. /// 使用方法: /// view.ClipToOutline = true; /// view.OutlineProvider = new ViewOutlineProviderHelper(); /// 参考 <see cref="https://www.jianshu.com/p/ab42f2198776"/> /// </summary> /// <seealso cref="Android.Views.ViewOutlineProvider" /> public class ViewBorderHelper : ViewOutlineProvider { //默认为10 public int RoundRectRadius = 2.Dp2Px(); public override void GetOutline(View view, Outline outline) { // 设置按钮圆角率 outline.SetRoundRect(0, 0, view.Width, view.Height, RoundRectRadius); // 设置按钮为圆形 //outline.SetOval(0, 0, view.Width, view.Height); } } public static class ViewBoundsHelper { /// <summary> /// 边框样式:圆角与阴影 /// </summary> /// <param name="view"></param> /// <param name="radius"></param> /// <param name="elevation"></param> public static void SetBoundsStyle(this View view, int radius = 10, int elevation = 20) { view.OutlineProvider = new ViewBorderHelper() { RoundRectRadius = radius.Dp2Px() };//设置圆角 view.ClipToOutline = true; view.Elevation = elevation.Dp2Px(); } } public class ViewStateHelper { /// <summary> /// <see href="https://stackoverflow.com/questions/32226232/android-create-selector-programmatically">Android create selector programmatically?</see><br/> /// At Android, usually use xml to create Selector to according to state set icon, this method let you can easily use code to set. /// </summary> /// <param name="color"></param> /// <returns></returns> public static StateListDrawable CreateStateListDrawable((State[], Drawable)[] stateListDrawables) { StateListDrawable res = new StateListDrawable(); res.SetExitFadeDuration(400); res.SetAlpha(45); foreach (var statelist in stateListDrawables) { res.AddState(statelist.Item1.Select(e => (int)e).ToArray(), statelist.Item2); } //res.AddState(new int[] { }, new Android.Graphics.Drawables.ColorDrawable(Color.Transparent)); return res; } /// <summary> /// Some View State For StateListDrawable And ColorStateList. /// https://developer.android.com/reference/android/graphics/drawable/StateListDrawable /// </summary> public enum State { //AboveAnchor = Android.Resource.Attribute.StateAboveAnchor, //Accelerated = Android.Resource.Attribute.StateAccelerated, /// <summary> /// State value for StateListDrawable, set when a view or its parent has been "activated" meaning the user has currently marked it as being of interest. /// </summary> Activated = Attribute.StateActivated, /// <summary> /// State value for StateListDrawable, set when a view or drawable is considered "active" by its host. /// </summary> Active = Attribute.StateActive, /// <summary> /// State identifier indicating that the object may display a check mark. /// </summary> Checkable = Attribute.StateCheckable, /// <summary> /// State identifier indicating that the object is currently checked. /// </summary> Checked = Attribute.StateChecked, //DragCanAccept = Android.Resource.Attribute.StateDragCanAccept, //DragHovered = Android.Resource.Attribute.StateDragHovered, //Empty = Android.Resource.Attribute.StateEmpty, /// <summary> /// State value for StateListDrawable, set when a view is enabled. /// </summary> Enabled = Attribute.StateEnabled, //Expanded = Android.Resource.Attribute.StateExpanded, /// <summary> /// State value for StateListDrawable, set when a view is enabled. /// </summary> First = Attribute.StateFirst, /// <summary> /// State value for StateListDrawable, set when a view has input focus. /// </summary> Focused = Attribute.StateFocused, //Hovered = Android.Resource.Attribute.StateHovered, /// <summary> /// State value for StateListDrawable, set when a view or drawable is in the last position in an ordered set. /// </summary> Last = Attribute.StateLast, //[Register("state_long_pressable")] //[Obsolete("deprecated")] //public const int StateLongPressable = 16843324; /// <summary> /// State value for StateListDrawable, set when a view or drawable is in the middle position in an ordered set. /// </summary> Middle = Attribute.StateMiddle, //Multiline = Android.Resource.Attribute.StateMultiline, /// <summary> /// State value for StateListDrawable, set when the user is pressing down in a view. /// </summary> Pressed = Attribute.StatePressed, /// <summary> /// State value for StateListDrawable, set when a view (or one of its parents) is currently selected. /// </summary> Selected = Attribute.StateSelected, /// <summary> /// State value for StateListDrawable, set when a view or drawable is considered "single" by its host. /// </summary> Single = Attribute.StateSingle, /// <summary> /// State value for StateListDrawable, set when a view's window has input focus. /// </summary> WindowFocused = Attribute.StateWindowFocused, } public static ColorStateList CreateStateListColor((State[], Color)[] stateListColors) { var stateCount = stateListColors.Length; var states = new int[stateCount][]; var colors = new int[stateCount]; for (var index = 0; index < stateCount; index++) { var state = stateListColors[index]; states[index] = state.Item1.Select(e => (int)e).ToArray(); colors[index] = state.Item2; } return new ColorStateList(states, colors); } } }
38.385475
165
0.588561
[ "MIT" ]
xtuzy/Xamarin.Native.Helper
Yang.Maui.Helper/Platforms/Android/UI/ViewHelper.cs
6,963
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Model { using System; public class PSJobHistory { public string JobName { get; internal set; } public string Status { get; internal set; } public int? Retry { get; internal set; } public int? Occurence { get; internal set; } public DateTime? StartTime { get; internal set; } public DateTime? EndTime { get; internal set; } public PSJobHistoryDetail Details { get; internal set; } } }
36.583333
87
0.593774
[ "MIT" ]
Milstein/azure-sdk-tools
WindowsAzurePowershell/src/Commands.Utilities/Scheduler/Model/PSJobHistory.cs
1,284
C#
using System; using System.Collections.Generic; using System.Net; using Orleans.Runtime; namespace Orleans.Serialization { public interface IBinaryTokenStreamReader { /// <summary> /// Resets this instance with the provided data. /// </summary> /// <param name="buffs">The underlying buffers.</param> void Reset(IList<ArraySegment<byte>> buffs); /// <summary> Current read position in the stream. </summary> int CurrentPosition { get; } /// <summary> /// Gets the total length. /// </summary> int Length { get; } /// <summary> /// Creates a copy of the current stream reader. /// </summary> /// <returns>The new copy</returns> IBinaryTokenStreamReader Copy(); /// <summary> Read a <c>bool</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> bool ReadBoolean(); /// <summary> Read an <c>Int32</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> int ReadInt(); /// <summary> Read an <c>UInt32</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> uint ReadUInt(); /// <summary> Read an <c>Int16</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> short ReadShort(); /// <summary> Read an <c>UInt16</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> ushort ReadUShort(); /// <summary> Read an <c>Int64</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> long ReadLong(); /// <summary> Read an <c>UInt64</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> ulong ReadULong(); /// <summary> Read an <c>float</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> float ReadFloat(); /// <summary> Read an <c>double</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> double ReadDouble(); /// <summary> Read an <c>decimal</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> decimal ReadDecimal(); DateTime ReadDateTime(); /// <summary> Read an <c>string</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> string ReadString(); /// <summary> Read the next bytes from the stream. </summary> /// <param name="count">Number of bytes to read.</param> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> byte[] ReadBytes(int count); /// <summary> Read the next bytes from the stream. </summary> /// <param name="destination">Output array to store the returned data in.</param> /// <param name="offset">Offset into the destination array to write to.</param> /// <param name="count">Number of bytes to read.</param> void ReadByteArray(byte[] destination, int offset, int count); /// <summary> Read an <c>char</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> char ReadChar(); /// <summary> Read an <c>byte</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> byte ReadByte(); /// <summary> Read an <c>sbyte</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> sbyte ReadSByte(); Guid ReadGuid(); /// <summary> Read an <c>IPAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> IPAddress ReadIPAddress(); /// <summary> Read an <c>IPEndPoint</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> IPEndPoint ReadIPEndPoint(); /// <summary> Read an <c>SiloAddress</c> value from the stream. </summary> /// <returns>Data from current position in stream, converted to the appropriate output type.</returns> SiloAddress ReadSiloAddress(); TimeSpan ReadTimeSpan(); /// <summary> /// Read a block of data into the specified output <c>Array</c>. /// </summary> /// <param name="array">Array to output the data to.</param> /// <param name="n">Number of bytes to read.</param> void ReadBlockInto(Array array, int n); byte PeekByte(); } }
45.258065
110
0.63186
[ "MIT" ]
DDzia/orleans
src/Orleans.Core.Abstractions/Serialization/IBinaryTokenStreamReader.cs
5,612
C#
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class GunFire : MonoBehaviour { public GameObject ray_direct_obj; public GameObject flash; public GameObject[] explosion; public AudioClip shoot, blast; int no_of_enemies; AudioSource audioSource; Ray ray; RaycastHit hit; ParticleSystem explosionSys; void Start() { audioSource = GetComponent<AudioSource> (); no_of_enemies = 5; } void FixedUpdate() { if (Input.GetMouseButtonDown (0)) { flash.GetComponent<ParticleSystem> ().Play (); ray = new Ray (transform.position, ray_direct_obj.transform.forward); if (Physics.Raycast (ray, out hit, 100000)) { if (hit.collider.tag == "Enemy") { // explosionSys = explosion[no_of_enemies - 1].GetComponent<ParticleSystem> (); Destroy (hit.collider.gameObject); explosion[no_of_enemies-1].transform.position = hit.transform.position; explosion[no_of_enemies-1].SetActive(true); // explosionSys.Stop (); // explosionSys.Play (); // explosionSys.startLifetime = explosionSys.startLifetime; no_of_enemies--; audioSource.Play (); audioSource.enabled = true; Debug.Log (no_of_enemies); // explosion[no_of_enemies-1].SetActive(false); } } } if (no_of_enemies <= 0) { SceneManager.LoadScene ("Menu", LoadSceneMode.Single); } } }
22.639344
83
0.695148
[ "MIT" ]
rakeshr4/Navex---VR-Game
Navex/Assets/Scripts/GunFire.cs
1,383
C#
using TreniniDotNet.Common.UseCases.Boundaries.Outputs; using TreniniDotNet.SharedKernel.Slugs; namespace TreniniDotNet.Application.Catalog.CatalogItems.AddRollingStockToCatalogItem { public sealed class AddRollingStockToCatalogItemOutput : IUseCaseOutput { public AddRollingStockToCatalogItemOutput(Slug slug) { Slug = slug; } public Slug Slug { get; } } }
26
85
0.725962
[ "MIT" ]
CarloMicieli/TreniniDotNet
Src/Application/Catalog/CatalogItems/AddRollingStockToCatalogItem/AddRollingStockToCatalogItemOutput.cs
416
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Aboutus : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }
18.857143
56
0.742424
[ "MIT" ]
Mukthahar26/Tourist-Project
Aboutus.aspx.cs
266
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CLSim.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CLSim.Test")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("b8797d52-4bcd-466d-a065-3012f7f69e91")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
29.52381
56
0.75
[ "MIT" ]
Simocracy/CLSim
CLSim-Test/Properties/AssemblyInfo.cs
621
C#
using Microsoft.Win32.SafeHandles; using System; using System.IO; using System.ServiceProcess; /* .Net driver manager class template Version:1.0 Autor:JerryAJ */ namespace KernelBox { /// <summary> /// 驱动管理类 /// </summary> public class DriverManager { // 驱动文件的名称 public static string g_strSysName = "MainDriver.sys"; // 驱动文件的路径 public static string g_strSysPath = Directory.GetCurrentDirectory() + "\\" + g_strSysName; // 驱动符号链接名称 public static string g_strSysLinkName = "\\\\.\\AJ_Driver"; //格式:\\\\.\\xxoo // 驱动服务名称 public static string g_strSysSvcLinkName = "AJ_Driver"; // 驱动句柄 public static SafeFileHandle hDrv; // SCM句柄 private IntPtr hSCManager; // 驱动服务句柄 private IntPtr hService; /// <summary> /// 获取驱动服务句柄 /// </summary> /// <returns>bool</returns> public bool GetSvcHandle() { hSCManager = NativeApi.OpenSCManager(null, null, (uint)NativeApiEx.SCM_ACCESS.SC_MANAGER_ALL_ACCESS); if (IntPtr.Zero == hSCManager) return false; hService = NativeApi.OpenService(hSCManager, g_strSysSvcLinkName, (uint)NativeApiEx.SERVICE_ACCESS.SERVICE_ALL_ACCESS); if (IntPtr.Zero == hService) { NativeApi.CloseServiceHandle(hService); return false; } return true; } /// <summary> /// 安装驱动服务 /// </summary> /// <returns>bool</returns> public bool Install() { hSCManager = NativeApi.OpenSCManager(null, null, (uint)NativeApiEx.SCM_ACCESS.SC_MANAGER_ALL_ACCESS); if (IntPtr.Zero == hSCManager) return false; hService = NativeApi.CreateService(hSCManager, g_strSysSvcLinkName, g_strSysSvcLinkName, (uint)NativeApiEx.SERVICE_ACCESS.SERVICE_ALL_ACCESS, (uint)NativeApiEx.SERVICE_TYPE.SERVICE_KERNEL_DRIVER, (uint)NativeApiEx.SERVICE_START.SERVICE_DEMAND_START, (uint)NativeApiEx.SERVICE_ERROR.SERVICE_ERROR_NORMAL, g_strSysPath, null, null, null, null, null); if (IntPtr.Zero == hService) { NativeApi.GetLastError(); NativeApi.CloseServiceHandle(hService); return false; } return true; } /// <summary> /// 启动驱动服务 /// </summary> /// <returns>bool</returns> public bool Start() { if (!NativeApi.StartService(hService, 0x0, null)) return false; return true; } /// <summary> /// 停止驱动服务 /// </summary> /// <returns>bool</returns> public bool Stop() { try { ServiceController service = new ServiceController(g_strSysSvcLinkName); if (service.Status == ServiceControllerStatus.Stopped) return true; else { TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } } catch (Exception) { return false; throw; } return true; } /// <summary> /// 卸载驱动 /// </summary> /// <returns>bool</returns> public bool Remove() { if (!NativeApi.DeleteService(hService)) return false; else { NativeApi.CloseServiceHandle(hService); NativeApi.CloseServiceHandle(hSCManager); } return true; } /// <summary> /// 打开当前驱动 /// </summary> /// <param name="strLinkName">驱动符号链接名称</param> /// <returns>SafeFileHandle</returns> public SafeFileHandle OpenDriver(string strLinkName) { return NativeApi.CreateFile(strLinkName, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero); } /// <summary> /// 驱动通信的IO控制器方法 /// </summary> /// <param name="hDriver">驱动句柄</param> /// <param name="nIoCode">IO控制码</param> /// <param name="InBuffer">传入缓冲区</param> /// <param name="nInBufferSize">传入缓冲区大小</param> /// <param name="OutBuffer">输出缓冲区</param> /// <param name="nOutBufferSize">输出缓冲区大小</param> /// <param name="pBytesReturned">返回字节数</param> /// <param name="Overlapped">输入输出的信息的结构体</param> /// <returns>bool</returns> public static bool IoControl(SafeFileHandle hDriver, uint nIoCode, object InBuffer, uint nInBufferSize, object OutBuffer, uint nOutBufferSize, ref uint pBytesReturned, ref System.Threading.NativeOverlapped Overlapped) { const uint FILE_ANY_ACCESS = 0; const uint METHOD_BUFFERED = 0; bool bRet; nIoCode = ((int)NativeApiEx.DEVICE_TYPE.FILE_DEVICE_UNKNOWN * 65536) | (FILE_ANY_ACCESS * 16384) | (nIoCode * 4) | METHOD_BUFFERED; bRet = NativeApi.DeviceIoControl(hDriver, nIoCode, InBuffer, nInBufferSize, OutBuffer, nOutBufferSize, ref pBytesReturned, ref Overlapped); return bRet; } /// <summary> /// 初始化驱动 /// </summary> /// <returns>bool</returns> public bool InitializeDriver() { bool bRet = false; hDrv = OpenDriver(g_strSysLinkName); NativeApi.GetLastError(); if (!hDrv.IsInvalid) bRet = GetSvcHandle(); else { bRet = Install(); if (!bRet) return bRet; else { bRet = Start(); hDrv = OpenDriver(g_strSysLinkName); } } return bRet; } /// <summary> /// 卸载驱动 /// </summary> /// <returns>bool</returns> public bool RemoveDrvier() { hDrv.Close(); hDrv.Dispose(); hDrv = null; bool bRet = false; bRet = Stop(); if (!bRet) return bRet; bRet = Remove(); return bRet; } } }
32.170732
225
0.52464
[ "MIT" ]
EjiHuang/KernelBox
KernelBox/DrvMgr/cDriverManager.cs
6,917
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Elasticsearch.Net.Utf8Json; namespace Nest { [ReadAs(typeof(IndicesPrivileges))] public interface IIndicesPrivileges { [DataMember(Name = "field_security")] IFieldSecurity FieldSecurity { get; set; } [DataMember(Name = "names")] [JsonFormatter(typeof(IndicesFormatter))] Indices Names { get; set; } [DataMember(Name = "privileges")] IEnumerable<string> Privileges { get; set; } [DataMember(Name = "query")] QueryContainer Query { get; set; } } public class IndicesPrivileges : IIndicesPrivileges { public IFieldSecurity FieldSecurity { get; set; } [JsonFormatter(typeof(IndicesFormatter))] public Indices Names { get; set; } public IEnumerable<string> Privileges { get; set; } public QueryContainer Query { get; set; } } public class IndicesPrivilegesDescriptor : DescriptorPromiseBase<IndicesPrivilegesDescriptor, IList<IIndicesPrivileges>> { public IndicesPrivilegesDescriptor() : base(new List<IIndicesPrivileges>()) { } public IndicesPrivilegesDescriptor Add<T>(Func<IndicesPrivilegesDescriptor<T>, IIndicesPrivileges> selector) where T : class => Assign(selector, (a, v) => a.AddIfNotNull(v?.Invoke(new IndicesPrivilegesDescriptor<T>()))); } public class IndicesPrivilegesDescriptor<T> : DescriptorBase<IndicesPrivilegesDescriptor<T>, IIndicesPrivileges>, IIndicesPrivileges where T : class { IFieldSecurity IIndicesPrivileges.FieldSecurity { get; set; } Indices IIndicesPrivileges.Names { get; set; } IEnumerable<string> IIndicesPrivileges.Privileges { get; set; } QueryContainer IIndicesPrivileges.Query { get; set; } public IndicesPrivilegesDescriptor<T> Names(Indices indices) => Assign(indices, (a, v) => a.Names = v); public IndicesPrivilegesDescriptor<T> Names(params IndexName[] indices) => Assign(indices, (a, v) => a.Names = v); public IndicesPrivilegesDescriptor<T> Names(IEnumerable<IndexName> indices) => Assign(indices.ToArray(), (a, v) => a.Names = v); public IndicesPrivilegesDescriptor<T> Privileges(params string[] privileges) => Assign(privileges, (a, v) => a.Privileges = v); public IndicesPrivilegesDescriptor<T> Privileges(IEnumerable<string> privileges) => Assign(privileges, (a, v) => a.Privileges = v); public IndicesPrivilegesDescriptor<T> FieldSecurity(Func<FieldSecurityDescriptor<T>, IFieldSecurity> fields) => Assign(fields, (a, v) => a.FieldSecurity = v?.Invoke(new FieldSecurityDescriptor<T>())); public IndicesPrivilegesDescriptor<T> Query(Func<QueryContainerDescriptor<T>, QueryContainer> query) => Assign(query, (a, v) => a.Query = v?.Invoke(new QueryContainerDescriptor<T>())); } }
38.957143
133
0.747708
[ "Apache-2.0" ]
AnthAbou/elasticsearch-net
src/Nest/XPack/Security/Role/PutRole/IndicesPrivileges.cs
2,727
C#
using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System; namespace IronPlot { /// <summary> /// A label used to display data in an axis. /// </summary> public class AxisLabel : Control { #region public string StringFormat /// <summary> /// Gets or sets the text string format. /// </summary> public string StringFormat { get { return GetValue(StringFormatProperty) as string; } set { SetValue(StringFormatProperty, value); } } /// <summary> /// Identifies the StringFormat dependency property. /// </summary> public static readonly DependencyProperty StringFormatProperty = DependencyProperty.Register( "StringFormat", typeof(string), typeof(AxisLabel), new PropertyMetadata(null, OnStringFormatPropertyChanged)); /// <summary> /// StringFormatProperty property changed handler. /// </summary> /// <param name="d">AxisLabel that changed its StringFormat.</param> /// <param name="e">Event arguments.</param> private static void OnStringFormatPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AxisLabel source = (AxisLabel)d; string newValue = (string)e.NewValue; source.OnStringFormatPropertyChanged(newValue); } /// <summary> /// StringFormatProperty property changed handler. /// </summary> /// <param name="newValue">New value.</param> protected virtual void OnStringFormatPropertyChanged(string newValue) { UpdateFormattedContent(); } #endregion public string StringFormat #region public string FormattedContent /// <summary> /// Gets the formatted content property. /// </summary> public string FormattedContent { get { return GetValue(FormattedContentProperty) as string; } protected set { SetValue(FormattedContentProperty, value); } } /// <summary> /// Identifies the FormattedContent dependency property. /// </summary> public static readonly DependencyProperty FormattedContentProperty = DependencyProperty.Register( "FormattedContent", typeof(string), typeof(AxisLabel), new PropertyMetadata(null)); #endregion public string FormattedContent #if !SILVERLIGHT /// <summary> /// Initializes the static members of the AxisLabel class. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Dependency properties are initialized in-line.")] static AxisLabel() { DefaultStyleKeyProperty.OverrideMetadata(typeof(AxisLabel), new FrameworkPropertyMetadata(typeof(AxisLabel))); } #endif /// <summary> /// Instantiates a new instance of the AxisLabel class. /// </summary> public AxisLabel() { #if SILVERLIGHT this.DefaultStyleKey = typeof(AxisLabel); #endif this.SetBinding(FormattedContentProperty, new Binding { Converter = new StringFormatConverter(), ConverterParameter = StringFormat ?? "{0}" }); } /// <summary> /// Updates the formatted text. /// </summary> protected virtual void UpdateFormattedContent() { this.SetBinding(FormattedContentProperty, new Binding { Converter = new StringFormatConverter(), ConverterParameter = StringFormat ?? "{0}" }); } } /// <summary> /// Converts a value to a string using a format string. /// </summary> public class StringFormatConverter : IValueConverter { /// <summary> /// Converts a value to a string by formatting it. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The target type of the conversion.</param> /// <param name="parameter">The format string.</param> /// <param name="culture">The culture to use for conversion.</param> /// <returns>The formatted string.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return string.Empty; } return string.Format(CultureInfo.CurrentCulture, (parameter as string) ?? "{0}", value); } /// <summary> /// Converts a value from a string to a target type. /// </summary> /// <param name="value">The value to convert to a string.</param> /// <param name="targetType">The target type of the conversion.</param> /// <param name="parameter">A parameter used during the conversion /// process.</param> /// <param name="culture">The culture to use for the conversion.</param> /// <returns>The converted object.</returns> public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); } } }
38.306122
169
0.591902
[ "Unlicense" ]
ManojJadhav2014/ironlab
IronPlot/PlotCommon/AxisLabel.cs
5,633
C#
#pragma checksum "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "19854bfbef9ac168d3d7c1339cda44226c769e95" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_User_Index), @"mvc.1.0.view", @"/Views/User/Index.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/User/Index.cshtml", typeof(AspNetCore.Views_User_Index))] 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 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\_ViewImports.cshtml" using AssessForm; #line default #line hidden #line 2 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\_ViewImports.cshtml" using AssessForm.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"19854bfbef9ac168d3d7c1339cda44226c769e95", @"/Views/User/Index.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"889cd84baf401d95c4bc3f327c8ffeb1cae7af8e", @"/Views/_ViewImports.cshtml")] public class Views_User_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<AssessForm.Models.User> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("control-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(31, 2, true); WriteLiteral("\r\n"); EndContext(); #line 3 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" ViewData["Title"] = "Index"; #line default #line hidden BeginContext(74, 98, true); WriteLiteral("\r\n<h1>Index</h1>\r\n\r\n<h4>User</h4>\r\n<hr />\r\n<div class=\"row\">\r\n <div class=\"col-md-4\">\r\n "); EndContext(); BeginContext(172, 2198, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e955823", async() => { BeginContext(197, 14, true); WriteLiteral("\r\n "); EndContext(); BeginContext(211, 66, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e956217", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper); #line 14 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.ModelOnly; #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(277, 56, true); WriteLiteral("\r\n <div class=\"form-group\">\r\n "); EndContext(); BeginContext(333, 57, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e958072", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 16 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.FirstName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(390, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(408, 50, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "19854bfbef9ac168d3d7c1339cda44226c769e959799", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 17 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.FirstName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(458, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(476, 64, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9511520", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 18 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.FirstName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(540, 76, true); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); EndContext(); BeginContext(616, 56, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9513382", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 21 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.LastName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(672, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(690, 49, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "19854bfbef9ac168d3d7c1339cda44226c769e9515109", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 22 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.LastName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(739, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(757, 63, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9516830", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 23 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.LastName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(820, 76, true); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); EndContext(); BeginContext(896, 53, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9518691", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 26 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Email); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(949, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(967, 46, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "19854bfbef9ac168d3d7c1339cda44226c769e9520415", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 27 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Email); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1013, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1031, 60, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9522135", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 28 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Email); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1091, 76, true); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); EndContext(); BeginContext(1167, 53, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9523995", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 31 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Phone); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1220, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1238, 46, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "19854bfbef9ac168d3d7c1339cda44226c769e9525721", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 32 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Phone); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1284, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1302, 60, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9527441", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 33 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Phone); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1362, 76, true); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); EndContext(); BeginContext(1438, 55, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9529301", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 36 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Address); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1493, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1511, 48, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "19854bfbef9ac168d3d7c1339cda44226c769e9531029", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 37 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Address); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1559, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1577, 62, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9532751", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 38 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Address); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1639, 76, true); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); EndContext(); BeginContext(1715, 59, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9534613", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 41 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CompanyName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1774, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1792, 52, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "19854bfbef9ac168d3d7c1339cda44226c769e9536345", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 42 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CompanyName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1844, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(1862, 66, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9538071", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 43 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CompanyName); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1928, 76, true); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); EndContext(); BeginContext(2004, 52, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9539937", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #line 46 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Role); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2056, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(2074, 45, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "19854bfbef9ac168d3d7c1339cda44226c769e9541662", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #line 47 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Role); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2119, 18, true); WriteLiteral("\r\n "); EndContext(); BeginContext(2137, 59, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9543381", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #line 48 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Role); #line default #line hidden __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2196, 167, true); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n <input type=\"submit\" value=\"Index\" class=\"btn btn-primary\" />\r\n </div>\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2370, 35, true); WriteLiteral("\r\n </div>\r\n</div>\r\n\r\n<div>\r\n "); EndContext(); BeginContext(2405, 38, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "19854bfbef9ac168d3d7c1339cda44226c769e9546649", async() => { BeginContext(2427, 12, true); WriteLiteral("Back to List"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(2443, 12, true); WriteLiteral("\r\n</div>\r\n\r\n"); EndContext(); DefineSection("Scripts", async() => { BeginContext(2473, 2, true); WriteLiteral("\r\n"); EndContext(); #line 62 "C:\Revature\ConnerKnight_Automation_Challenge1\AssessForm\AssessForm\Views\User\Index.cshtml" await Html.RenderPartialAsync("_ValidationScriptsPartial"); #line default #line hidden } ); } #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<AssessForm.Models.User> Html { get; private set; } } } #pragma warning restore 1591
72.234421
351
0.708849
[ "MIT" ]
1811-nov27-net/ConnerKnight_Automation_Challenge1
AssessForm/AssessForm/obj/Debug/netcoreapp2.2/Razor/Views/User/Index.g.cshtml.cs
48,686
C#
namespace OpenGLBindings { /// <summary> /// Not used directly. /// </summary> public enum FramebufferFetchNoncoherent { /// <summary> /// Original was GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM = 0x96A2 /// </summary> FramebufferFetchNoncoherentQcom = 38562 } }
24.076923
71
0.616613
[ "MIT" ]
DeKaDeNcE/WoWDatabaseEditor
Rendering/OpenGLBindings/FramebufferFetchNoncoherent.cs
313
C#
namespace Hjg.Pngcs.Chunks { using System; using System.Collections; using System.Collections.Generic; using System.IO; using Hjg.Pngcs.Zlib; /// <summary> /// Static utility methods for CHunks /// </summary> /// <remarks> /// Client code should rarely need this, see PngMetada and ChunksList /// </remarks> public class ChunkHelper { internal const String IHDR = "IHDR"; internal const String PLTE = "PLTE"; internal const String IDAT = "IDAT"; internal const String IEND = "IEND"; internal const String cHRM = "cHRM";// No Before PLTE and IDAT internal const String gAMA = "gAMA";// No Before PLTE and IDAT internal const String iCCP = "iCCP";// No Before PLTE and IDAT internal const String sBIT = "sBIT";// No Before PLTE and IDAT internal const String sRGB = "sRGB";// No Before PLTE and IDAT internal const String bKGD = "bKGD";// No After PLTE; before IDAT internal const String hIST = "hIST";// No After PLTE; before IDAT internal const String tRNS = "tRNS";// No After PLTE; before IDAT internal const String pHYs = "pHYs";// No Before IDAT internal const String sPLT = "sPLT";// Yes Before IDAT internal const String tIME = "tIME";// No None internal const String iTXt = "iTXt";// Yes None internal const String tEXt = "tEXt";// Yes None internal const String zTXt = "zTXt";// Yes None internal static readonly byte[] b_IHDR = ToBytes(IHDR); internal static readonly byte[] b_PLTE = ToBytes(PLTE); internal static readonly byte[] b_IDAT = ToBytes(IDAT); internal static readonly byte[] b_IEND = ToBytes(IEND); /// <summary> /// Converts to bytes using Latin1 (ISO-8859-1) /// </summary> /// <param name="x"></param> /// <returns></returns> public static byte[] ToBytes(String x) { return Hjg.Pngcs.PngHelperInternal.charsetLatin1.GetBytes(x); } /// <summary> /// Converts to String using Latin1 (ISO-8859-1) /// </summary> /// <param name="x"></param> /// <returns></returns> public static String ToString(byte[] x) { return Hjg.Pngcs.PngHelperInternal.charsetLatin1.GetString(x); } /// <summary> /// Converts to String using Latin1 (ISO-8859-1) /// </summary> /// <param name="x"></param> /// <param name="offset"></param> /// <param name="len"></param> /// <returns></returns> public static String ToString(byte[] x, int offset, int len) { return Hjg.Pngcs.PngHelperInternal.charsetLatin1.GetString(x, offset, len); } /// <summary> /// Converts to bytes using UTF-8 /// </summary> /// <param name="x"></param> /// <returns></returns> public static byte[] ToBytesUTF8(String x) { return Hjg.Pngcs.PngHelperInternal.charsetUtf8.GetBytes(x); } /// <summary> /// Converts to string using UTF-8 /// </summary> /// <param name="x"></param> /// <returns></returns> public static String ToStringUTF8(byte[] x) { return Hjg.Pngcs.PngHelperInternal.charsetUtf8.GetString(x); } /// <summary> /// Converts to string using UTF-8 /// </summary> /// <param name="x"></param> /// <param name="offset"></param> /// <param name="len"></param> /// <returns></returns> public static String ToStringUTF8(byte[] x, int offset, int len) { return Hjg.Pngcs.PngHelperInternal.charsetUtf8.GetString(x, offset, len); } /// <summary> /// Writes full array of bytes to stream /// </summary> /// <param name="stream"></param> /// <param name="bytes"></param> public static void WriteBytesToStream(Stream stream, byte[] bytes) { stream.Write(bytes, 0, bytes.Length); } /// <summary> /// Critical chunks: first letter is uppercase /// </summary> /// <param name="id"></param> /// <returns></returns> public static bool IsCritical(String id) { // first letter is uppercase return (Char.IsUpper(id[0])); } /// <summary> /// Public chunks: second letter is uppercase /// </summary> /// <param name="id"></param> /// <returns></returns> public static bool IsPublic(String id) { // public chunk? return (Char.IsUpper(id[1])); } /// <summary> /// Safe to copy chunk: fourth letter is lower case /// </summary> /// <param name="id"></param> /// <returns></returns> public static bool IsSafeToCopy(String id) { // safe to copy? // fourth letter is lower case return (!Char.IsUpper(id[3])); } /// <summary> /// We consider a chunk as "unknown" if our chunk factory (even when it has been augmented by client code) doesn't recognize it /// </summary> /// <param name="chunk"></param> /// <returns></returns> public static bool IsUnknown(PngChunk chunk) { return chunk is PngChunkUNKNOWN; } /// <summary> /// Finds position of null byte in array /// </summary> /// <param name="bytes"></param> /// <returns>-1 if not found</returns> public static int PosNullByte(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) if (bytes[i] == 0) return i; return -1; } /// <summary> /// Decides if a chunk should be loaded, according to a ChunkLoadBehaviour /// </summary> /// <param name="id"></param> /// <param name="behav"></param> /// <returns></returns> public static bool ShouldLoad(String id, ChunkLoadBehaviour behav) { if (IsCritical(id)) return true; bool kwown = PngChunk.isKnown(id); switch (behav) { case ChunkLoadBehaviour.LOAD_CHUNK_ALWAYS: return true; case ChunkLoadBehaviour.LOAD_CHUNK_IF_SAFE: return kwown || IsSafeToCopy(id); case ChunkLoadBehaviour.LOAD_CHUNK_KNOWN: return kwown; case ChunkLoadBehaviour.LOAD_CHUNK_NEVER: return false; } return false; // should not reach here } internal static byte[] compressBytes(byte[] ori, bool compress) { return compressBytes(ori, 0, ori.Length, compress); } internal static byte[] compressBytes(byte[] ori, int offset, int len, bool compress) { try { MemoryStream inb = new MemoryStream(ori, offset, len); Stream inx = inb; if (!compress) inx = ZlibStreamFactory.createZlibInputStream(inb); MemoryStream outb = new MemoryStream(); Stream outx = outb; if (compress) outx = ZlibStreamFactory.createZlibOutputStream(outb); shovelInToOut(inx, outx); inx.Close(); outx.Close(); byte[] res = outb.ToArray(); return res; } catch (Exception e) { throw new PngjException(e); } } private static void shovelInToOut(Stream inx, Stream outx) { byte[] buffer = new byte[1024]; int len; while ((len = inx.Read(buffer, 0, 1024)) > 0) { outx.Write(buffer, 0, len); } } internal static bool maskMatch(int v, int mask) { return (v & mask) != 0; } /// <summary> /// Filters a list of Chunks, keeping those which match the predicate /// </summary> /// <remarks>The original list is not altered</remarks> /// <param name="list"></param> /// <param name="predicateKeep"></param> /// <returns></returns> public static List<PngChunk> FilterList(List<PngChunk> list, ChunkPredicate predicateKeep) { List<PngChunk> result = new List<PngChunk>(); foreach (PngChunk element in list) { if (predicateKeep.Matches(element)) { result.Add(element); } } return result; } /// <summary> /// Filters a list of Chunks, removing those which match the predicate /// </summary> /// <remarks>The original list is not altered</remarks> /// <param name="list"></param> /// <param name="predicateRemove"></param> /// <returns></returns> public static int TrimList(List<PngChunk> list, ChunkPredicate predicateRemove) { int cont = 0; for (int i = list.Count - 1; i >= 0; i--) { if (predicateRemove.Matches(list[i])) { list.RemoveAt(i); cont++; } } return cont; } /// <summary> /// Ad-hoc criteria for 'equivalent' chunks. /// </summary> /// <remarks> /// Two chunks are equivalent if they have the same Id AND either: /// 1. they are Single /// 2. both are textual and have the same key /// 3. both are SPLT and have the same palette name /// Bear in mind that this is an ad-hoc, non-standard, nor required (nor wrong) /// criterion. Use it only if you find it useful. Notice that PNG allows to have /// repeated textual keys with same keys. /// </remarks> /// <param name="c1">Chunk1</param> /// <param name="c2">Chunk1</param> /// <returns>true if equivalent</returns> public static bool Equivalent(PngChunk c1, PngChunk c2) { if (c1 == c2) return true; if (c1 == null || c2 == null || !c1.Id.Equals(c2.Id)) return false; // same id if (c1.GetType() != c2.GetType()) return false; // should not happen if (!c2.AllowsMultiple()) return true; if (c1 is PngChunkTextVar) { return ((PngChunkTextVar)c1).GetKey().Equals(((PngChunkTextVar)c2).GetKey()); } if (c1 is PngChunkSPLT) { return ((PngChunkSPLT)c1).PalName.Equals(((PngChunkSPLT)c2).PalName); } // unknown chunks that allow multiple? consider they don't match return false; } public static bool IsText(PngChunk c) { return c is PngChunkTextVar; } } }
38.202091
135
0.53548
[ "MIT" ]
HerbalistElvira/ImageOcclusionEditor
pngcs-master/Hjg.Pngcs/Chunks/ChunkHelper.cs
10,964
C#
// Copyright (c) 2016-2017 Nicolas Musset. All rights reserved. // This file is licensed under the MIT license. // See the LICENSE.md file in the project root for more information. using Markdig.Annotations; using Markdig.Syntax; namespace Markdig.Renderers.Xaml { /// <summary> /// A XAML renderer for a <see cref="QuoteBlock"/>. /// </summary> /// <seealso cref="Xaml.XamlObjectRenderer{T}" /> public class QuoteBlockRenderer : XamlObjectRenderer<QuoteBlock> { protected override void Write([NotNull] XamlRenderer renderer, QuoteBlock obj) { renderer.EnsureLine(); renderer.Write("<Section"); // Apply quote block styling renderer.Write(" Style=\"{StaticResource {x:Static markdig:Styles.QuoteBlockStyleKey}}\""); renderer.WriteLine(">"); renderer.WriteChildren(obj); renderer.WriteLine("</Section>"); } } }
32.724138
103
0.639621
[ "MIT" ]
FCUnlimited/markdig.wpf
src/Markdig.Wpf/Renderers/Xaml/QuoteBlockRenderer.cs
949
C#
using System; using System.Collections.Generic; using NHSD.GPIT.BuyingCatalogue.EntityFramework.Addresses.Models; using NHSD.GPIT.BuyingCatalogue.EntityFramework.Ordering.Models; using NHSD.GPIT.BuyingCatalogue.EntityFramework.Users.Models; namespace NHSD.GPIT.BuyingCatalogue.EntityFramework.Organisations.Models { public sealed class Organisation : IAudited { public Organisation() { Orders = new HashSet<Order>(); RelatedOrganisationOrganisations = new HashSet<RelatedOrganisation>(); RelatedOrganisationRelatedOrganisationNavigations = new HashSet<RelatedOrganisation>(); } public int Id { get; set; } public string Name { get; set; } public Address Address { get; set; } public string OdsCode { get; set; } public string PrimaryRoleId { get; set; } public bool CatalogueAgreementSigned { get; set; } public DateTime LastUpdated { get; set; } public int? LastUpdatedBy { get; set; } public AspNetUser LastUpdatedByUser { get; set; } public ICollection<Order> Orders { get; set; } public ICollection<RelatedOrganisation> RelatedOrganisationOrganisations { get; set; } public ICollection<RelatedOrganisation> RelatedOrganisationRelatedOrganisationNavigations { get; set; } } }
31.651163
111
0.696547
[ "MIT" ]
nhs-digital-gp-it-futures/GPITBuyingCatalogue
src/NHSD.GPIT.BuyingCatalogue.EntityFramework/Organisations/Models/Organisation.cs
1,363
C#
using DevToolsX.Documents.Symbols; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; namespace DevToolsX.Documents { public class DocumentGenerator : IDisposable { private IDocumentWriter writer; private bool newParagraph = true; private bool isInParagraph = false; private bool appendSpace = false; private bool disposing = false; private bool isInCode = false; private int listLevel = 0; private List<Begin> beginStack = new List<Begin>(); private List<ListIterator> listIteratorStack = new List<ListIterator>(); private List<TableIterator> tableIteratorStack = new List<TableIterator>(); private DocumentGenerator(IDocumentWriter writer) { this.writer = writer; this.writer.BeginDocument(); } public bool AutoAppendSpaceBetweenWords { get; set; } public static DocumentGenerator CreateDocument(IDocumentWriter writer) { return new DocumentGenerator(writer); } public static DocumentGenerator CreateLatexDocument(string path) { return new DocumentGenerator(new LatexWriter(path, Encoding.UTF8)); } public static DocumentGenerator CreateLatexDocument(string path, Encoding encoding) { return new DocumentGenerator(new LatexWriter(path, encoding)); } public static DocumentGenerator CreateLatexDocument(Stream stream) { return new DocumentGenerator(new LatexWriter(stream, Encoding.UTF8)); } public static DocumentGenerator CreateLatexDocument(Stream stream, Encoding encoding) { return new DocumentGenerator(new LatexWriter(stream, encoding)); } public static DocumentGenerator CreateHtmlDocument(string path) { return new DocumentGenerator(new HtmlWriter(path, Encoding.UTF8)); } public static DocumentGenerator CreateHtmlDocument(string path, Encoding encoding) { return new DocumentGenerator(new HtmlWriter(path, encoding)); } public static DocumentGenerator CreateHtmlDocument(Stream stream) { return new DocumentGenerator(new HtmlWriter(stream, Encoding.UTF8)); } public static DocumentGenerator CreateHtmlDocument(Stream stream, Encoding encoding) { return new DocumentGenerator(new HtmlWriter(stream, encoding)); } public void Dispose() { if (this.disposing) return; this.disposing = true; this.EndParagraphIfNecessary(); this.writer.EndDocument(); IDisposable disposableWriter = this.writer as IDisposable; if (disposableWriter != null) { disposableWriter.Dispose(); } } private void FlushBegin() { int i = this.beginStack.Count - 1; while (i >= 0 && !this.beginStack[i].IsFlushed) --i; ++i; while (i < this.beginStack.Count) { this.beginStack[i].Apply(this); ++i; } } private Begin CurrentBegin { get { if (this.beginStack.Count > 0) { return this.beginStack[this.beginStack.Count - 1]; } return null; } } private TBegin PopBegin<TBegin>(string close) where TBegin : Begin { Begin currentBegin = this.CurrentBegin; TBegin typedBegin = currentBegin as TBegin; if (typedBegin != null) { if (this.beginStack.Count > 0) { this.beginStack.RemoveAt(this.beginStack.Count - 1); return typedBegin; } } else { throw new DocumentException($"Cannot close '{currentBegin}' with '{close}'"); } return null; } public void AddImage(string filePath) { this.writer.AddImage(filePath); } private ListIterator CurrentListIterator { get { if (this.listIteratorStack.Count == 0) return null; return this.listIteratorStack[this.listIteratorStack.Count - 1]; } } private TableIterator CurrentTableIterator { get { if (this.tableIteratorStack.Count == 0) return null; return this.tableIteratorStack[this.tableIteratorStack.Count - 1]; } } public void Write(bool value, MarkupKind markup = MarkupKind.None) { this.Append(value.ToString(), markup); } public void Write(char value, MarkupKind markup = MarkupKind.None) { this.Append(value.ToString(), markup); } public void Write(int value, MarkupKind markup = MarkupKind.None) { this.Append(value.ToString(), markup); } public void Write(long value, MarkupKind markup = MarkupKind.None) { this.Append(value.ToString(), markup); } public void Write(float value, MarkupKind markup = MarkupKind.None) { this.Append(value.ToString(), markup); } public void Write(double value, MarkupKind markup = MarkupKind.None) { this.Append(value.ToString(), markup); } public void Write(string text, MarkupKind markup = MarkupKind.None) { this.Append(text, markup); } public void Write(string text, params object[] args) { this.Append(string.Format(text, args)); } public void WriteLine() { this.EndParagraphIfNecessary(); } public void LineBreak() { this.writer.LineBreak(); this.appendSpace = false; } public void WriteLine(bool value, MarkupKind markup = MarkupKind.None) { this.AppendLine(value.ToString(), markup); } public void WriteLine(char value, MarkupKind markup = MarkupKind.None) { this.AppendLine(value.ToString(), markup); } public void WriteLine(int value, MarkupKind markup = MarkupKind.None) { this.AppendLine(value.ToString(), markup); } public void WriteLine(long value, MarkupKind markup = MarkupKind.None) { this.AppendLine(value.ToString(), markup); } public void WriteLine(float value, MarkupKind markup = MarkupKind.None) { this.AppendLine(value.ToString(), markup); } public void WriteLine(double value, MarkupKind markup = MarkupKind.None) { this.AppendLine(value.ToString(), markup); } public void WriteLine(string text, MarkupKind markup = MarkupKind.None) { this.AppendLine(text, markup); } public void WriteLine(string text, params object[] args) { this.AppendLine(string.Format(text, args)); } private void Append(string text, MarkupKind markup = MarkupKind.None) { if (!string.IsNullOrEmpty(text)) { if (this.AutoAppendSpaceBetweenWords && this.appendSpace) { this.writer.Write(" "); } this.FlushBegin(); this.BeginParagraphIfNecessary(); if (markup != MarkupKind.None) { this.writer.BeginMarkup(new MarkupKind[] { markup }, Color.Empty, Color.Empty); } this.writer.Write(text); if (markup != MarkupKind.None) { this.writer.EndMarkup(new MarkupKind[] { markup }, Color.Empty, Color.Empty); } this.newParagraph = false; this.appendSpace = true; } } private void AppendLine(string text, MarkupKind markup = MarkupKind.None) { this.Append(text); if (!string.IsNullOrEmpty(text)) { this.EndParagraphIfNecessary(); } } private void DisableParagraph() { this.isInParagraph = false; this.newParagraph = false; this.appendSpace = false; } private void EnableParagraph() { this.EndParagraphIfNecessary(); } public void NewParagraph() { if (this.isInParagraph) { this.EndParagraphIfNecessary(); this.BeginParagraphIfNecessary(); } else { this.EndParagraphIfNecessary(); this.BeginParagraphIfNecessary(); this.EndParagraphIfNecessary(); this.BeginParagraphIfNecessary(); } } public void NewPage() { this.writer.PageBreak(); } private void BeginParagraphIfNecessary() { if (!this.isInParagraph && this.newParagraph) { this.writer.BeginParagraph(); this.isInParagraph = true; } this.appendSpace = false; } private void EndParagraphIfNecessary() { if (this.isInParagraph) { this.writer.EndParagraph(); this.newParagraph = true; this.isInParagraph = false; } this.newParagraph = true; this.appendSpace = false; } public void WriteSectionTitle(int level, string title, string label = null) { if (!string.IsNullOrEmpty(title)) { this.BeginSectionTitle(level, label); this.Write(title); this.EndSectionTitle(); } } public void WriteReference(string document, string id, string text) { if (!string.IsNullOrEmpty(text)) { this.BeginReference(document, id); this.Write(text); this.EndReference(); } } public void AddTableOfContents(int depth) { this.writer.AddTableOfContents(depth); } public void BeginSectionTitle(int level, string label = null) { this.EndParagraphIfNecessary(); this.DisableParagraph(); this.beginStack.Add(new SectionTitleBegin() { Level = level, Label = label }); } public void EndSectionTitle() { SectionTitleBegin begin = this.PopBegin<SectionTitleBegin>("EndSectionTitle"); if (begin.IsFlushed) { this.writer.EndSectionTitle(begin.Level, begin.Label); } this.EnableParagraph(); } public void BeginMarkup(IEnumerable<MarkupKind> markupKinds, Color foregroundColor, Color backgroundColor) { if (markupKinds.Contains(MarkupKind.Code)) { this.EndParagraphIfNecessary(); this.isInCode = true; this.appendSpace = false; } this.beginStack.Add(new MarkupBegin() { MarkupKinds = markupKinds, ForegroundColor = foregroundColor, BackgroundColor = backgroundColor }); } public void EndMarkup() { MarkupBegin begin = this.PopBegin<MarkupBegin>("EndMarkup"); if (begin.IsFlushed) { this.writer.EndMarkup(begin.MarkupKinds, begin.ForegroundColor, begin.BackgroundColor); } if (begin.MarkupKinds.Contains(MarkupKind.Code)) { this.isInCode = false; this.isInParagraph = false; this.newParagraph = true; this.appendSpace = false; } } public void AddLabel(string id) { if (!string.IsNullOrWhiteSpace(id)) { this.writer.AddLabel(id); } else { throw new DocumentException($"Invalid label identifier: '{id}'. It must be non-null and non-whitespace."); } } public void BeginReference(string document, string id) { if (document == null) document = string.Empty; if (id == null) id = string.Empty; this.beginStack.Add(new ReferenceBegin() { Document = document, Id = id }); } public void EndReference() { ReferenceBegin begin = this.PopBegin<ReferenceBegin>("EndReference"); if (begin.IsFlushed) { this.writer.EndReference(begin.Document, begin.Id); } } public void BeginList(ListKind listKind = ListKind.None) { ListIterator iterator = this.CurrentListIterator; if (iterator != null) { this.CloseListItem(iterator); } this.EndParagraphIfNecessary(); this.DisableParagraph(); int level = this.listLevel++; this.beginStack.Add(new ListBegin() { Level = level, ListKind = listKind }); this.listIteratorStack.Add(new ListIterator(this, level, listKind)); } public void AddListItem(string title = null) { ListIterator iterator = this.CurrentListIterator; if (iterator == null) throw new DocumentException("Cannot add a list item within a non-list environment. Wrap AddListItem() between a BeginList() and an EndList() call."); iterator.Next(title); } private void BeginListItem(ListIterator iterator) { this.DisableParagraph(); this.beginStack.Add(new ListItemBegin() { Level = iterator.Level, Index = iterator.Index, Title = iterator.Title }); this.appendSpace = false; } private void CloseListItem(ListIterator iterator) { ListItemBegin begin = this.CurrentBegin as ListItemBegin; if (begin != null && !begin.IsClosed) { if (begin.IsFlushed) { this.writer.EndListItem(begin.Level, begin.Index, begin.Title); this.EnableParagraph(); } begin.IsClosed = true; } } private void EndListItem(ListIterator iterator) { ListItemBegin begin = this.PopBegin<ListItemBegin>("EndListItem"); if (begin.IsFlushed) { if (!begin.IsClosed) { this.writer.EndListItem(begin.Level, begin.Index, begin.Title); this.EnableParagraph(); } } else { iterator.Previous(); } } public void EndList() { ListIterator iterator = this.CurrentListIterator; if (iterator == null) throw new DocumentException("Cannot end a list item within a non-list environment. Start a list with BeginList() first."); iterator.End(); ListBegin begin = this.PopBegin<ListBegin>("EndList"); --this.listLevel; if (begin.IsFlushed) { this.writer.EndList(begin.Level, begin.ListKind); } if (this.listIteratorStack.Count > 0) { this.listIteratorStack.RemoveAt(this.listIteratorStack.Count - 1); } else { // Should not happen: throw new DocumentException("Cannot remove list iterator."); } this.EnableParagraph(); } public void BeginTable(int columnCount, int headColumnCount = 0, int headRowCount = 0) { this.EndParagraphIfNecessary(); //this.DisableParagraph(); this.beginStack.Add(new TableBegin() { ColumnCount = columnCount, HeadColumnCount = headColumnCount, HeadRowCount = headRowCount }); this.tableIteratorStack.Add(new TableIterator(this, columnCount, headColumnCount, headRowCount)); } public void AddTableCell() { TableIterator iterator = this.CurrentTableIterator; if (iterator == null) throw new DocumentException("Cannot add a cell within a non-table environment. Wrap AddTableCell() between a BeginTable() and an EndTable() call."); iterator.Next(); } private void BeginTableCell(TableIterator iterator) { this.FlushBegin(); if (iterator.Column == 0) { if (iterator.Row > 0) { this.writer.EndTableRow(iterator.Row); } this.writer.BeginTableRow(iterator.Row); } this.writer.BeginTableCell(iterator.Row, iterator.Column, iterator.IsHead); this.newParagraph = true; this.isInParagraph = false; } private void EndTableCell(TableIterator iterator) { //this.EndParagraphIfNecessary(); this.writer.EndTableCell(iterator.Row, iterator.Column, iterator.IsHead); } public void EndTable() { TableIterator iterator = this.CurrentTableIterator; if (iterator == null) throw new DocumentException("Cannot end a table a non-table environment. Start a table with BeginTable() first."); iterator.End(); TableBegin begin = this.PopBegin<TableBegin>("EndTable"); if (begin.IsFlushed) { this.writer.EndTableRow(iterator.Row); this.writer.EndTable(begin.ColumnCount); } if (this.tableIteratorStack.Count > 0) { this.tableIteratorStack.RemoveAt(this.tableIteratorStack.Count - 1); } else { // Should not happen: throw new DocumentException("Cannot remove table iterator."); } this.EnableParagraph(); } private abstract class Begin { public bool IsFlushed { get; private set; } public void Apply(DocumentGenerator generator) { this.IsFlushed = true; this.DoApply(generator); } protected abstract void DoApply(DocumentGenerator generator); } private class SectionTitleBegin : Begin { public string Label { get; set; } public int Level { get; set; } protected override void DoApply(DocumentGenerator generator) { generator.writer.BeginSectionTitle(this.Level, this.Label); } public override string ToString() { return "BeginSectionTitle"; } } private class MarkupBegin : Begin { public IEnumerable<MarkupKind> MarkupKinds { get; set; } public Color ForegroundColor { get; set; } public Color BackgroundColor { get; set; } protected override void DoApply(DocumentGenerator generator) { generator.writer.BeginMarkup(this.MarkupKinds, this.ForegroundColor, this.BackgroundColor); } public override string ToString() { return "BeginMarkup"; } } private class ReferenceBegin : Begin { public string Document { get; set; } public string Id { get; set; } protected override void DoApply(DocumentGenerator generator) { generator.writer.BeginReference(this.Document, this.Id); } public override string ToString() { return "BeginReference"; } } private class ListBegin : Begin { public int Level { get; set; } public ListKind ListKind { get; set; } protected override void DoApply(DocumentGenerator generator) { generator.writer.BeginList(this.Level, this.ListKind); } public override string ToString() { return "BeginList"; } } private class ListItemBegin : Begin { public int Level { get; set; } public int Index { get; set; } public string Title { get; set; } public bool IsClosed { get; set; } protected override void DoApply(DocumentGenerator generator) { generator.writer.BeginListItem(this.Level, this.Index, this.Title); } public override string ToString() { return "BeginListItem"; } } private class TableBegin : Begin { public int ColumnCount { get; set; } public int HeadColumnCount { get; set; } public int HeadRowCount { get; set; } protected override void DoApply(DocumentGenerator generator) { generator.writer.BeginTable(this.ColumnCount); } public override string ToString() { return "BeginTable"; } } private class ListIterator { private DocumentGenerator generator; public ListIterator(DocumentGenerator generator, int level, ListKind listKind) { this.generator = generator; this.Level = level; this.ListKind = listKind; this.Index = -1; } public int Level { get; private set; } public int Index { get; private set; } public string Title { get; private set; } public ListKind ListKind { get; private set; } public void Previous() { --this.Index; } public void Next(string title) { if (this.Index >= 0) { this.generator.EndListItem(this); } ++this.Index; this.Title = title; this.generator.BeginListItem(this); } public void End() { if (this.Index >= 0) { this.generator.EndListItem(this); } } } private class TableIterator { private DocumentGenerator generator; private int index; public TableIterator(DocumentGenerator generator, int columnCount, int headColumnCount, int headRowCount) { this.generator = generator; this.ColumnCount = columnCount; this.HeadColumnCount = headColumnCount; this.HeadRowCount = headRowCount; this.index = -1; } public int ColumnCount { get; private set; } public int HeadColumnCount { get; private set; } public int HeadRowCount { get; private set; } public int Column { get { if (this.ColumnCount == 0) return 0; return this.index % this.ColumnCount; } } public int Row { get { if (this.ColumnCount == 0) return 0; return this.index / this.ColumnCount; } } public bool IsHead { get { return this.Column < this.HeadColumnCount || this.Row < this.HeadRowCount; } } public void Next() { if (this.index >= 0) { this.generator.EndTableCell(this); } ++this.index; this.generator.BeginTableCell(this); } public void End() { if (this.index >= 0) { this.generator.EndTableCell(this); } } } } }
31.358302
183
0.522573
[ "Apache-2.0" ]
balazssimon/devtools-cs
Src/Main/DevToolsX.Documents/DocumentGenerator.cs
25,120
C#
using EA; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace EnterpriseArchitectAutoRefresh { /// <summary> /// This class represents a logging table, maintained by a database trigger. /// </summary> class TableAdapter { // Logging table information private readonly String table; private readonly String prefix; private readonly Repository repository; private String timestamp; // Constants from the logging tables, must be similar to those in the Trigger-Generator private const String COLUMN_ID = "ID"; private const String COLUMN_TIMESTAMP = "Timestamp"; /// <summary> /// Creates a new TableListener with given table name and logging table prefix. /// </summary> /// <param name="table">The table name of the EA-related mapping (e.G. "t_object")</param> /// <param name="prefix">The prefix of the logging tables from the Trigger-Generator (e.G. "ht_")</param> /// <param name="repositry">The currently opened repository</param> public TableAdapter(String table, String prefix, Repository repositry) { this.table = table; this.prefix = prefix; this.repository = repositry; // Set NOW() as initial timestamp getDataBaseTimestamp(); } /// <summary> /// Returns the primary keys (e.G. ElementIDs) from all database entries that changed in the last iteration. /// </summary> /// <returns></returns> public List<String> getUpdates() { String updateStatement = "SELECT DATE_FORMAT(NOW(6), '%Y-%m-%d %H:%i:%s.%f') AS `TS`, `{0}` AS `ID` FROM `{1}` WHERE `{2}` >= STR_TO_DATE('{3}', '%Y-%m-%d %H:%i:%s.%f')"; String updatesXML = repository.SQLQuery(String.Format(updateStatement, COLUMN_ID, prefix + table, COLUMN_TIMESTAMP, timestamp)); List<String> updateList = new List<String>(); using (XmlReader reader = XmlReader.Create(new StringReader(updatesXML))) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "TS") { this.timestamp = reader.ReadElementContentAsString(); } if (reader.Name == "ID") { updateList.Add(reader.ReadElementContentAsString()); } } } } return updateList; } /// <summary> /// Sets the initial timestamp by getting the exact date from the database system. /// </summary> private void getDataBaseTimestamp() { String currentTimeXML = repository.SQLQuery("SELECT DATE_FORMAT(NOW(6), '%Y-%m-%d %H:%i:%s.%f') AS TS"); using (XmlReader reader = XmlReader.Create(new StringReader(currentTimeXML))) { reader.ReadToFollowing("TS"); timestamp = reader.ReadElementContentAsString(); } } } }
37.408602
183
0.544697
[ "EPL-1.0" ]
Cooperate-Project/EnterpriseArchitectBridgeEAAddin
EnterpriseArchitectAutoRefresh/TableAdapter.cs
3,481
C#
using System; using System.Threading.Tasks; namespace Xamarin.Essentials { public static partial class Maps { public static Task OpenAsync(Location location) => OpenAsync(location, new MapsLaunchOptions()); public static Task OpenAsync(Location location, MapsLaunchOptions options) { if (location == null) throw new ArgumentNullException(nameof(location)); if (options == null) throw new ArgumentNullException(nameof(options)); return PlatformOpenMapsAsync(location.Latitude, location.Longitude, options); } public static Task OpenAsync(double latitude, double longitude) => OpenAsync(latitude, longitude, new MapsLaunchOptions()); public static Task OpenAsync(double latitude, double longitude, MapsLaunchOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); return PlatformOpenMapsAsync(latitude, longitude, options); } public static Task OpenAsync(Placemark placemark) => OpenAsync(placemark, new MapsLaunchOptions()); public static Task OpenAsync(Placemark placemark, MapsLaunchOptions options) { if (placemark == null) throw new ArgumentNullException(nameof(placemark)); if (options == null) throw new ArgumentNullException(nameof(options)); return PlatformOpenMapsAsync(placemark, options); } } }
32.729167
98
0.637174
[ "MIT" ]
AzureAdvocateBit/Essentials-1
Xamarin.Essentials/Maps/Maps.shared.cs
1,573
C#
// <copyright file="Constants.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace Microsoft.Teams.Apps.FAQPlusPlus.Common { /// <summary> /// constants. /// </summary> public static class Constants { /// <summary> /// Source. /// </summary> public const string Source = "Editorial"; /// <summary> /// Delete command. /// </summary> public const string DeleteCommand = "delete"; /// <summary> /// No command. /// </summary> public const string NoCommand = "no"; /// <summary> /// Regular expression pattern for valid redirection url. /// It checks whether the url is valid or not, while adding/editing the qna pair. /// </summary> public const string ValidRedirectUrlPattern = @"^(http|https|)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?([a-zA-Z0-9\-\?\,\'\/\+&%\$#_]+)"; /// <summary> /// Name of the QnA metadata property to map with the date and time the item was added. /// </summary> public const string MetadataCreatedAt = "createdat"; /// <summary> /// Name of the QnA metadata property to map with the user who created the item. /// </summary> public const string MetadataCreatedBy = "createdby"; /// <summary> /// Name of the QnA metadata property to map with the conversation id of the item. /// </summary> public const string MetadataConversationId = "conversationid"; /// <summary> /// Name of the QnA metadata property to map with the date and time the item was updated. /// </summary> public const string MetadataUpdatedAt = "updatedat"; /// <summary> /// Name of the QnA metadata property to map with the user who updated the item. /// </summary> public const string MetadataUpdatedBy = "updatedby"; /// <summary> /// Name of the QnA metadata property to map with the activity reference id for future reference. /// </summary> public const string MetadataActivityReferenceId = "activityreferenceid"; /// <summary> /// TeamTour - text that triggers team tour action. /// </summary> public const string TeamTour = "team tour"; /// <summary> /// TakeAtour - text that triggers take a tour action for the user. /// </summary> public const string TakeATour = "take a tour"; /// <summary> /// AskAnExpert - text that renders the ask an expert card. /// </summary> public const string AskAnExpert = "ask an expert"; /// <summary> /// Text associated with ask an expert command. /// </summary> public const string AskAnExpertSubmitText = "QuestionForExpert"; /// <summary> /// Feedback - text that renders share feedback card. /// </summary> public const string ShareFeedback = "share feedback"; /// <summary> /// Text associated with share feedback command. /// </summary> public const string ShareFeedbackSubmitText = "ShareFeedback"; /// <summary> /// Table name where SME activity details from bot will be saved. /// </summary> public const string TicketTableName = "Tickets"; /// <summary> /// Name of column value to map with knowledgebase id in table storage. /// </summary> public const string KnowledgeBaseEntityId = "KnowledgeBaseId"; /// <summary> /// FAQ Plus blob storage container name. /// </summary> public const string StorageContainer = "faqplus-search-container"; /// <summary> /// FAQ Plus folder name under FAQ Plus blob storage container name. /// </summary> public const string BlobFolderName = "faqplus-metadata"; /// <summary> /// Represents the command text to identify the action. /// </summary> public const string PreviewCardCommandText = "previewcard"; } }
35.420168
194
0.579834
[ "MIT" ]
Mikhail2k15/microsoft-teams-apps-faqplus
Source/Microsoft.Teams.Apps.FAQPlusPlus.Common/Constants.cs
4,217
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.Sql.Models; namespace Azure.ResourceManager.Sql { internal partial class DatabaseSchemasRestOperations { private Uri endpoint; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; private readonly string _userAgent; /// <summary> Initializes a new instance of DatabaseSchemasRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="options"> The client options used to construct the current client. </param> /// <param name="endpoint"> server parameter. </param> public DatabaseSchemasRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, Uri endpoint = null) { this.endpoint = endpoint ?? new Uri("https://management.azure.com"); _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; _userAgent = HttpMessageUtilities.GetUserAgentName(this, options); } internal HttpMessage CreateListByDatabaseRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, string filter) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/schemas", false); if (filter != null) { uri.AppendQuery("$filter", filter, true); } uri.AppendQuery("api-version", "2020-11-01-preview", true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> List database schemas. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public async Task<Response<DatabaseSchemaListResult>> ListByDatabaseAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, string filter = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListByDatabaseRequest(subscriptionId, resourceGroupName, serverName, databaseName, filter); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DatabaseSchemaListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DatabaseSchemaListResult.DeserializeDatabaseSchemaListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> List database schemas. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public Response<DatabaseSchemaListResult> ListByDatabase(string subscriptionId, string resourceGroupName, string serverName, string databaseName, string filter = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListByDatabaseRequest(subscriptionId, resourceGroupName, serverName, databaseName, filter); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DatabaseSchemaListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DatabaseSchemaListResult.DeserializeDatabaseSchemaListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, string schemaName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/schemas/", false); uri.AppendPath(schemaName, true); uri.AppendQuery("api-version", "2020-11-01-preview", true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Get database schema. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, or <paramref name="schemaName"/> is null. </exception> public async Task<Response<DatabaseSchemaData>> GetAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, string schemaName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, serverName, databaseName, schemaName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DatabaseSchemaData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DatabaseSchemaData.DeserializeDatabaseSchemaData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((DatabaseSchemaData)null, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Get database schema. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="schemaName"> The name of the schema. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/>, or <paramref name="schemaName"/> is null. </exception> public Response<DatabaseSchemaData> Get(string subscriptionId, string resourceGroupName, string serverName, string databaseName, string schemaName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } if (schemaName == null) { throw new ArgumentNullException(nameof(schemaName)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, serverName, databaseName, schemaName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DatabaseSchemaData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DatabaseSchemaData.DeserializeDatabaseSchemaData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((DatabaseSchemaData)null, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListByDatabaseNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName, string filter) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> List database schemas. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public async Task<Response<DatabaseSchemaListResult>> ListByDatabaseNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName, string filter = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListByDatabaseNextPageRequest(nextLink, subscriptionId, resourceGroupName, serverName, databaseName, filter); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DatabaseSchemaListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DatabaseSchemaListResult.DeserializeDatabaseSchemaListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> List database schemas. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="filter"> An OData filter expression that filters elements in the collection. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, or <paramref name="databaseName"/> is null. </exception> public Response<DatabaseSchemaListResult> ListByDatabaseNextPage(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName, string filter = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (serverName == null) { throw new ArgumentNullException(nameof(serverName)); } if (databaseName == null) { throw new ArgumentNullException(nameof(databaseName)); } using var message = CreateListByDatabaseNextPageRequest(nextLink, subscriptionId, resourceGroupName, serverName, databaseName, filter); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DatabaseSchemaListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DatabaseSchemaListResult.DeserializeDatabaseSchemaListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
54.782383
264
0.620779
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/RestOperations/DatabaseSchemasRestOperations.cs
21,146
C#
using System; namespace Events { public class OrderShipped { public Guid OrderId { get; set; } } }
13.222222
41
0.605042
[ "MIT" ]
kamilsoloducha/examples
saga/src/Events/OrderShipped.cs
119
C#
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace MaSchoeller.TakeItEasySolver.Shared.Models { public class Gamefield : IEnumerable<((int x, int y) Position, Gamecard? Card)> { private readonly Gamecard?[,] _field; private readonly Stack<(int x, int y)> _roundChanges; // Y/X --- // ___ / 4/4 \ ___ // / 4/3 \ / 3/4 \ // ___ \ --- --- // / 4/2 ___ / 3/3 \ ___ / 2/4 \ // \ ___ / 3/2 \ / 2/3 \ / // / 3/1 \ --- --- // \ ___ / 2/2 \ ___ / 1/3 \ // ___ / 2/1 \ / 1/2 \ / // / 2/0 \ --- --- // \ Y/X ___ / 1/1 \ ___ / 0/2 \ // ___ / 1/0 \ / 0/1 \ Y/X / // \ Y/X --- Y/X --- // ___ / 0/0 \ ___ / // \ Y/X / // --- public Gamefield() { _field = new Gamecard[5,5]; _roundChanges = new Stack<(int x, int y)>(); } public IEnumerator<((int x, int y) Position, Gamecard? Card)> GetEnumerator() { for (int i = 0; i < 3; i++) yield return ((i, 0), _field[i,0]); for (int i = 0; i < 4; i++) yield return ((i, 1), _field[i, 1]); for (int i = 0; i < 5; i++) yield return ((i, 2), _field[i, 2]); for (int i = 1; i < 5; i++) yield return ((i, 3), _field[i, 3]); for (int i = 2; i < 5; i++) yield return ((i, 4), _field[i, 4]); } public Gamecard? this[(int x, int y) index] { get => _field[index.x,index.y]; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public void SaveRound() => _roundChanges.Clear(); public void ResetRound() { while (TryUndoLastMove()) ; } public bool TrySetCard((int x, int y) position, Gamecard gamecard) { //TODO: Check out of range for the cards.. if (_field[position.x,position.y] is not null) { return false; } _field[position.x,position.y] = gamecard; _roundChanges.Push(position); return true; } public bool TryUndoLastMove() { var success = _roundChanges.TryPop(out var pos); if (!success) return false; _field[pos.x,pos.y] = null; return true; } public IEnumerable<Gamecard> GetUnusedGamecards() => Gamecard.GetAllCards().Except(this.Select(g => g.Card!)).ToArray(); public IEnumerable<(int x, int y)> GetFreePositions() => this.Where(i => i.Card is null).Select(i => i.Position); public PositionInfo GetPositioInfo(int x, int y, Gamecard gamecard, bool removeAfterCalculate = true) { TrySetCard((x, y), gamecard); var rightRowInfo = CalulateRightRow(x); var leftRowInfo = CalulateLeftRow(y); var topRowInfo = CalulateTopRow((x, y) switch { (2, 0) or (3, 1) or (4, 2) => 0, (1, 0) or (2, 1) or (3, 2) or (4, 3) => 1, (0, 0) or (1,1) or (2, 2) or (3, 3) or (4, 4) => 2, (0, 1) or (1, 2) or (2, 3) or (3, 4) => 3, (0, 2) or (1, 3) or (2, 4) => 4, _ => throw new ArgumentException() }); //Console.WriteLine(ToString()); if (removeAfterCalculate) TryUndoLastMove(); return new PositionInfo(leftRowInfo, rightRowInfo, topRowInfo); } public RowInfo CalulateTopRow(int row) { (int x, int y) cord = row switch { 0 => (0, 2), 1 => (0, 1), 2 => (0, 0), 3 => (1, 0), 4 => (2, 0), _ => throw new ArgumentException() }; int number = 0; bool isFinished = true; bool isCorruped = false; var length = GetCountByRow(row); for (int i = 0; i < length; i++) { if (_field[cord.y + i,cord.x + i] is Gamecard card && card is not null) { if (number == 0) { number = card.Top; } else { isCorruped = isCorruped || card.Top != number; } } else { isFinished = false; } } return new RowInfo(isFinished, isCorruped, isCorruped ? 0 : length * number ); } public RowInfo CalulateRightRow(int row) { int number = 0; bool isFinished = true; bool isCorruped = false; var start = GetStartIndex(row); var end = GetEndIndex(row); for (int i = start; i < end; i++) { if (_field[row,i] is Gamecard card) { if (number == 0) { number = card.Right; } else { isCorruped = isCorruped || card.Right != number; } } else { isFinished = false; } } var length = GetCountByRow(row); return new RowInfo(isFinished, isCorruped, isCorruped ? 0 : length * number); } public RowInfo CalulateLeftRow(int row) { int number = 0; bool isFinished = true; bool isCorruped = false; var start = GetStartIndex(row); var end = GetEndIndex(row); for (int i = start; i < end; i++) { if (_field[i,row] is Gamecard card) { if (number == 0) { number = card.Left; } else { isCorruped = isCorruped || card.Left != number; } } else { isFinished = false; } } var length = GetCountByRow(row); return new RowInfo(isFinished, isCorruped, isCorruped ? 0 : length * number); } public int GetBoardPoints() { var numbers = Enumerable.Range(0, 4); var left = numbers.Select(i => CalulateLeftRow(i).Points).Sum(); var right = numbers.Select(i => CalulateRightRow(i).Points).Sum(); var top = numbers.Select(i => CalulateTopRow(i).Points).Sum(); return left + right + top; } public override string ToString() { var builder = new StringBuilder(); builder.AppendLine(@$" --- "); builder.AppendLine(@$" / {this[(4,4)]?.Top ?? 0} \ "); builder.AppendLine(@$" --- --- "); builder.AppendLine(@$" / {this[(4, 3)]?.Top ?? 0} \ {this[(4, 4)]?.Left ?? 0}/{this[(4, 4)]?.Right ?? 0} / {this[(3, 4)]?.Top ?? 0} \ "); builder.AppendLine(@$" --- --- --- "); builder.AppendLine(@$" / {this[(4, 2)]?.Top ?? 0} \ {this[(4, 3)]?.Left ?? 0}/{this[(4, 3)]?.Right ?? 0} / {this[(3, 3)]?.Top ?? 0} \ {this[(3, 4)]?.Left ?? 0}/{this[(3, 4)]?.Right ?? 0} / {this[(2, 4)]?.Top ?? 0} \ "); builder.AppendLine(@$" --- --- "); builder.AppendLine(@$" \ {this[(4, 2)]?.Left ?? 0}/{this[(4, 2)]?.Right ?? 0} / {this[(3, 2)]?.Top ?? 0} \ {this[(3, 3)]?.Left ?? 0}/{this[(3, 3)]?.Right ?? 0} / {this[(2, 3)]?.Top ?? 0} \ {this[(2, 4)]?.Left ?? 0}/{this[(2, 4)]?.Right ?? 0} / "); builder.AppendLine(@$" --- --- --- "); builder.AppendLine(@$" / {this[(3, 1)]?.Top ?? 0} \ {this[(3, 2)]?.Left ?? 0}/{this[(3, 2)]?.Right ?? 0} / {this[(2, 2)]?.Top ?? 0} \ {this[(2, 3)]?.Left ?? 0}/{this[(2, 3)]?.Right ?? 0} / {this[(1, 3)]?.Top ?? 0} \ "); builder.AppendLine(@$" --- --- "); builder.AppendLine(@$" \ {this[(3, 1)]?.Left ?? 0}/{this[(3, 1)]?.Right ?? 0} / {this[(2, 1)]?.Top ?? 0} \ {this[(2, 2)]?.Left ?? 0}/{this[(2, 2)]?.Right ?? 0} / {this[(1, 2)]?.Top ?? 0} \ {this[(1, 3)]?.Left ?? 0}/{this[(1, 3)]?.Right ?? 0} / "); builder.AppendLine(@$" --- --- --- "); builder.AppendLine(@$" / {this[(2, 0)]?.Top ?? 0} \ {this[(2, 1)]?.Left ?? 0}/{this[(2, 1)]?.Right ?? 0} / {this[(1, 1)]?.Top ?? 0} \ {this[(1, 2)]?.Left ?? 0}/{this[(1, 2)]?.Right ?? 0} / {this[(0, 2)]?.Top ?? 0} \ "); builder.AppendLine(@$" --- --- "); builder.AppendLine(@$" \ {this[(2, 0)]?.Left ?? 0}/{this[(2, 0)]?.Right ?? 0} / {this[(1, 0)]?.Top ?? 0} \ {this[(1, 1)]?.Left ?? 0}/{this[(1, 1)]?.Right ?? 0} / {this[(0, 1)]?.Top ?? 0} \ {this[(0, 2)]?.Left ?? 0}/{this[(0, 2)]?.Right ?? 0} / "); builder.AppendLine(@$" --- --- --- "); builder.AppendLine(@$" \ {this[(1, 0)]?.Left ?? 0}/{this[(1, 0)]?.Right ?? 0} / {this[(0, 0)]?.Top ?? 0} \ {this[(0, 1)]?.Left ?? 0}/{this[(0, 1)]?.Right ?? 0} / "); builder.AppendLine(@$" --- --- "); builder.AppendLine(@$" \ {this[(0, 0)]?.Left ?? 0}/{this[(0, 0)]?.Right ?? 0} / "); builder.AppendLine(@$" --- "); // --- // ___ / 4/4 \ ___ // / 4/3 \ / 3/4 \ // ___ \ --- --- // / 4/2 ___ / 3/3 \ ___ / 2/4 \ // \ ___ / 3/2 \ / 2/3 \ / // / 3/1 \ --- --- // \ ___ / 2/2 \ ___ / 1/3 \ // ___ / 2/1 \ / 1/2 \ / // / 2/0 \ --- --- // \ Y/X ___ / 1/1 \ ___ / 0/2 \ // ___ / 1/0 \ / 0/1 \ Y/X / // \ Y/X --- Y/X --- // ___ / 0/0 \ ___ / // \ Y/X / // --- return builder.ToString(); } private static int GetCountByRow(int row) => row switch { 0 or 4 => 3, 1 or 3 => 4, 2 => 5, _ => throw new NotImplementedException() }; private static int GetStartIndex(int row) { return row switch { <= 2 => 0, 3 => 1, 4 => 2, _ => throw new ArgumentException() }; } private static int GetEndIndex(int row) { return row switch { 0 => 3, 1 => 4, >= 2 => 5, _ => throw new ArgumentException() }; } } }
40.262626
273
0.364693
[ "MIT" ]
maSchoeller/take-it-easy-gamesolver
src/MaSchoeller.TakeItEasySolver/Shared/Models/Gamefield.cs
11,960
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Encodings.Web; using Foundation; using Microsoft.AspNetCore.Components.Web; using Microsoft.Extensions.FileProviders; using UIKit; using WebKit; namespace Microsoft.AspNetCore.Components.WebView.Maui { public class IOSWebViewManager : WebViewManager { private const string AppOrigin = "app://0.0.0.0/"; private readonly BlazorWebViewHandler _blazorMauiWebViewHandler; private readonly WKWebView _webview; public IOSWebViewManager(BlazorWebViewHandler blazorMauiWebViewHandler, WKWebView webview, IServiceProvider services, Dispatcher dispatcher, IFileProvider fileProvider, JSComponentConfigurationStore jsComponents, string hostPageRelativePath) : base(services, dispatcher, new Uri(AppOrigin), fileProvider, jsComponents, hostPageRelativePath) { _blazorMauiWebViewHandler = blazorMauiWebViewHandler ?? throw new ArgumentNullException(nameof(blazorMauiWebViewHandler)); _webview = webview ?? throw new ArgumentNullException(nameof(webview)); InitializeWebView(); } /// <inheritdoc /> protected override void NavigateCore(Uri absoluteUri) { using var nsUrl = new NSUrl(absoluteUri.ToString()); using var request = new NSUrlRequest(nsUrl); _webview.LoadRequest(request); } internal bool TryGetResponseContentInternal(string uri, bool allowFallbackOnHostPage, out int statusCode, out string statusMessage, out Stream content, out IDictionary<string, string> headers) => TryGetResponseContent(uri, allowFallbackOnHostPage, out statusCode, out statusMessage, out content, out headers); /// <inheritdoc /> protected override void SendMessage(string message) { var messageJSStringLiteral = JavaScriptEncoder.Default.Encode(message); _webview.EvaluateJavaScript( javascript: $"__dispatchMessageCallback(\"{messageJSStringLiteral}\")", completionHandler: (NSObject result, NSError error) => { }); } internal void MessageReceivedInternal(Uri uri, string message) { MessageReceived(uri, message); } private void InitializeWebView() { _webview.NavigationDelegate = new WebViewNavigationDelegate(_blazorMauiWebViewHandler); _webview.UIDelegate = new WebViewUIDelegate(_blazorMauiWebViewHandler); } internal sealed class WebViewUIDelegate : WKUIDelegate { private static readonly string LocalOK = NSBundle.FromIdentifier("com.apple.UIKit").GetLocalizedString("OK"); private static readonly string LocalCancel = NSBundle.FromIdentifier("com.apple.UIKit").GetLocalizedString("Cancel"); private readonly BlazorWebViewHandler _webView; public WebViewUIDelegate(BlazorWebViewHandler webView) { _webView = webView ?? throw new ArgumentNullException(nameof(webView)); } public override void RunJavaScriptAlertPanel(WKWebView webView, string message, WKFrameInfo frame, Action completionHandler) { PresentAlertController( webView, message, okAction: _ => completionHandler() ); } public override void RunJavaScriptConfirmPanel(WKWebView webView, string message, WKFrameInfo frame, Action<bool> completionHandler) { PresentAlertController( webView, message, okAction: _ => completionHandler(true), cancelAction: _ => completionHandler(false) ); } public override void RunJavaScriptTextInputPanel( WKWebView webView, string prompt, string? defaultText, WKFrameInfo frame, Action<string> completionHandler) { PresentAlertController( webView, prompt, defaultText: defaultText, okAction: x => completionHandler(x.TextFields[0].Text!), cancelAction: _ => completionHandler(null!) ); } private static string GetJsAlertTitle(WKWebView webView) { // Emulate the behavior of UIWebView dialogs. // The scheme and host are used unless local html content is what the webview is displaying, // in which case the bundle file name is used. if (webView.Url != null && webView.Url.AbsoluteString != $"file://{NSBundle.MainBundle.BundlePath}/") return $"{webView.Url.Scheme}://{webView.Url.Host}"; return new NSString(NSBundle.MainBundle.BundlePath).LastPathComponent; } private static UIAlertAction AddOkAction(UIAlertController controller, Action handler) { var action = UIAlertAction.Create(LocalOK, UIAlertActionStyle.Default, (_) => handler()); controller.AddAction(action); controller.PreferredAction = action; return action; } private static UIAlertAction AddCancelAction(UIAlertController controller, Action handler) { var action = UIAlertAction.Create(LocalCancel, UIAlertActionStyle.Cancel, (_) => handler()); controller.AddAction(action); return action; } private static void PresentAlertController( WKWebView webView, string message, string? defaultText = null, Action<UIAlertController>? okAction = null, Action<UIAlertController>? cancelAction = null) { var controller = UIAlertController.Create(GetJsAlertTitle(webView), message, UIAlertControllerStyle.Alert); if (defaultText != null) controller.AddTextField((textField) => textField.Text = defaultText); if (okAction != null) AddOkAction(controller, () => okAction(controller)); if (cancelAction != null) AddCancelAction(controller, () => cancelAction(controller)); GetTopViewController(UIApplication.SharedApplication.Windows.FirstOrDefault(m => m.IsKeyWindow)?.RootViewController)? .PresentViewController(controller, true, null); } private static UIViewController? GetTopViewController(UIViewController? viewController) { if (viewController is UINavigationController navigationController) return GetTopViewController(navigationController.VisibleViewController); if (viewController is UITabBarController tabBarController) return GetTopViewController(tabBarController.SelectedViewController!); if (viewController?.PresentedViewController != null) return GetTopViewController(viewController.PresentedViewController); return viewController; } } internal class WebViewNavigationDelegate : WKNavigationDelegate { private readonly BlazorWebViewHandler _webView; private WKNavigation? _currentNavigation; private Uri? _currentUri; public WebViewNavigationDelegate(BlazorWebViewHandler webView) { _webView = webView ?? throw new ArgumentNullException(nameof(webView)); } public override void DidStartProvisionalNavigation(WKWebView webView, WKNavigation navigation) { _currentNavigation = navigation; } public override void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler) { // TargetFrame is null for navigation to a new window (`_blank`) if (navigationAction.TargetFrame is null) { // Open in a new browser window UIApplication.SharedApplication.OpenUrl(navigationAction.Request.Url); decisionHandler(WKNavigationActionPolicy.Cancel); return; } if (navigationAction.TargetFrame.MainFrame) { _currentUri = navigationAction.Request.Url; } decisionHandler(WKNavigationActionPolicy.Allow); } public override void DidReceiveServerRedirectForProvisionalNavigation(WKWebView webView, WKNavigation navigation) { // We need to intercept the redirects to the app scheme because Safari will block them. // We will handle these redirects through the Navigation Manager. if (_currentUri?.Host == "0.0.0.0") { var uri = _currentUri; _currentUri = null; _currentNavigation = null; var request = new NSUrlRequest(uri); webView.LoadRequest(request); } } public override void DidFailNavigation(WKWebView webView, WKNavigation navigation, NSError error) { _currentUri = null; _currentNavigation = null; } public override void DidFailProvisionalNavigation(WKWebView webView, WKNavigation navigation, NSError error) { _currentUri = null; _currentNavigation = null; } public override void DidCommitNavigation(WKWebView webView, WKNavigation navigation) { if (_currentUri != null && _currentNavigation == navigation) { // TODO: Determine whether this is needed //_webView.HandleNavigationStarting(_currentUri); } } public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation) { if (_currentUri != null && _currentNavigation == navigation) { // TODO: Determine whether this is needed //_webView.HandleNavigationFinished(_currentUri); _currentUri = null; _currentNavigation = null; } } } } }
34.7251
243
0.750229
[ "MIT" ]
APopatanasov/maui
src/BlazorWebView/src/Maui/iOS/IOSWebViewManager.cs
8,716
C#
#region copyright //--------------------------------------------------------------- // Copyright (C) Dmitriy Yukhanov - focus [https://codestage.net] //--------------------------------------------------------------- #endregion namespace CodeStage.Maintainer.Tools { using System; using System.Globalization; using System.IO; using System.Text; using UnityEditor; using UnityEngine; using Core; internal static class CSEditorTools { private static readonly string[] sizes = { "B", "KB", "MB", "GB" }; private static TextInfo textInfo; internal static CSSceneTools.OpenSceneResult lastRevealSceneOpenResult; public static string FormatBytes(double bytes) { var order = 0; while (bytes >= 1024 && order + 1 < 4) { order++; bytes = bytes / 1024; } return string.Format("{0:0.##} {1}", bytes, sizes[order]); } public static int GetPropertyHash(SerializedProperty sp) { var stringHash = new StringBuilder(); stringHash.Append(sp.type); if (sp.isArray) { stringHash.Append(sp.arraySize); } else { switch (sp.propertyType) { case SerializedPropertyType.AnimationCurve: if (sp.animationCurveValue != null) { stringHash.Append(sp.animationCurveValue.length); if (sp.animationCurveValue.keys != null) { foreach (var key in sp.animationCurveValue.keys) { stringHash.Append(key.value) .Append(key.time) .Append(key.outTangent) .Append(key.inTangent); } } } break; case SerializedPropertyType.ArraySize: stringHash.Append(sp.intValue); break; case SerializedPropertyType.Boolean: stringHash.Append(sp.boolValue); break; case SerializedPropertyType.Bounds: stringHash.Append(sp.boundsValue.GetHashCode()); break; case SerializedPropertyType.Character: stringHash.Append(sp.intValue); break; case SerializedPropertyType.Generic: // looks like arrays which we already walk through break; case SerializedPropertyType.Gradient: // unsupported break; case SerializedPropertyType.ObjectReference: if (sp.objectReferenceValue != null) { stringHash.Append(sp.objectReferenceValue.name); } break; case SerializedPropertyType.Color: stringHash.Append(sp.colorValue.GetHashCode()); break; case SerializedPropertyType.Enum: stringHash.Append(sp.enumValueIndex); break; case SerializedPropertyType.Float: stringHash.Append(sp.floatValue); break; case SerializedPropertyType.Integer: stringHash.Append(sp.intValue); break; case SerializedPropertyType.LayerMask: stringHash.Append(sp.intValue); break; case SerializedPropertyType.Quaternion: stringHash.Append(sp.quaternionValue.GetHashCode()); break; case SerializedPropertyType.Rect: stringHash.Append(sp.rectValue.GetHashCode()); break; case SerializedPropertyType.String: stringHash.Append(sp.stringValue); break; case SerializedPropertyType.Vector2: stringHash.Append(sp.vector2Value.GetHashCode()); break; case SerializedPropertyType.Vector3: stringHash.Append(sp.vector3Value.GetHashCode()); break; case SerializedPropertyType.Vector4: stringHash.Append(sp.vector4Value.GetHashCode()); break; case SerializedPropertyType.ExposedReference: if (sp.exposedReferenceValue != null) { stringHash.Append(sp.exposedReferenceValue.name); } break; case SerializedPropertyType.Vector2Int: stringHash.Append(sp.vector2IntValue.GetHashCode()); break; case SerializedPropertyType.Vector3Int: stringHash.Append(sp.vector3IntValue.GetHashCode()); break; case SerializedPropertyType.RectInt: stringHash.Append(sp.rectIntValue.position.GetHashCode()).Append(sp.rectIntValue.size.GetHashCode()); break; case SerializedPropertyType.BoundsInt: stringHash.Append(sp.boundsIntValue.GetHashCode()); break; case SerializedPropertyType.FixedBufferSize: stringHash.Append(sp.fixedBufferSize); break; default: Debug.LogWarning(Maintainer.LogPrefix + "Unknown SerializedPropertyType: " + sp.propertyType); break; } } return stringHash.ToString().GetHashCode(); } public static string GetFullTransformPath(Transform transform, Transform stopAt = null) { var path = transform.name; while (transform.parent != null) { transform = transform.parent; if (transform == stopAt) break; path = transform.name + "/" + path; } return path; } public static EditorWindow GetInspectorWindow() { if (CSReflectionTools.inspectorWindowType == null) { Debug.LogError(Maintainer.ConstructError("Can't find UnityEditor.InspectorWindow type!")); return null; } var inspectorWindow = EditorWindow.GetWindow(CSReflectionTools.inspectorWindowType); if (inspectorWindow == null) { Debug.LogError(Maintainer.ConstructError("Can't get an InspectorWindow!")); return null; } return inspectorWindow; } public static ActiveEditorTracker GetActiveEditorTrackerForSelectedObject() { var inspectorWindow = GetInspectorWindow(); if (inspectorWindow == null) return null; if (CSReflectionTools.inspectorWindowType == null) return null; inspectorWindow.Repaint(); ActiveEditorTracker result = null; var trackerProperty = CSReflectionTools.GetPropertyInfo(CSReflectionTools.inspectorWindowType, "tracker"); if (trackerProperty != null) { result = (ActiveEditorTracker)trackerProperty.GetValue(inspectorWindow, null); } else { Debug.LogError(Maintainer.ConstructError("Can't get ActiveEditorTracker from the InspectorWindow!")); } return result; } public static bool RevealInSettings(AssetSettingsKind settingsKind, string path = null) { var result = true; switch (settingsKind) { case AssetSettingsKind.AudioManager: case AssetSettingsKind.ClusterInputManager: case AssetSettingsKind.InputManager: case AssetSettingsKind.NavMeshAreas: case AssetSettingsKind.NavMeshLayers: case AssetSettingsKind.NavMeshProjectSettings: case AssetSettingsKind.NetworkManager: break; case AssetSettingsKind.NotSettings: Debug.LogWarning(Maintainer.ConstructWarning("Can't open settings of kind NotSettings Oo")); result = false; break; case AssetSettingsKind.DynamicsManager: if (!CSMenuTools.ShowProjectSettingsPhysics()) { Debug.LogError(Maintainer.ConstructError("Can't open Physics Settings!")); result = false; } break; case AssetSettingsKind.EditorBuildSettings: if (!CSMenuTools.ShowEditorBuildSettings()) { Debug.LogError(Maintainer.ConstructError("Can't open EditorBuildSettings!")); result = false; } break; case AssetSettingsKind.EditorSettings: if (!CSMenuTools.ShowEditorSettings()) { Debug.LogError(Maintainer.ConstructError("Can't open Editor Settings!")); result = false; } break; case AssetSettingsKind.GraphicsSettings: if (!CSMenuTools.ShowProjectSettingsGraphics()) { Debug.LogError(Maintainer.ConstructError("Can't open GraphicsSettings!")); result = false; } break; case AssetSettingsKind.Physics2DSettings: if (!CSMenuTools.ShowProjectSettingsPhysics2D()) { Debug.LogError(Maintainer.ConstructError("Can't open Physics2D Settings!")); result = false; } break; case AssetSettingsKind.ProjectSettings: if (!CSMenuTools.ShowProjectSettingsPlayer()) { Debug.LogError(Maintainer.ConstructError("Can't open Player Settings!")); result = false; } break; case AssetSettingsKind.PresetManager: if (!CSMenuTools.ShowProjectSettingsPresetManager()) { Debug.LogError(Maintainer.ConstructError("Can't open Preset Manager!")); result = false; } break; case AssetSettingsKind.QualitySettings: break; case AssetSettingsKind.TagManager: if (!CSMenuTools.ShowProjectSettingsTagsAndLayers()) { Debug.LogError(Maintainer.ConstructError("Can't open Tags and Layers Settings!")); result = false; } break; case AssetSettingsKind.TimeManager: break; case AssetSettingsKind.UnityAdsSettings: break; case AssetSettingsKind.UnityConnectSettings: break; case AssetSettingsKind.VFXManager: if (!CSMenuTools.ShowProjectSettingsVFX()) { Debug.LogError(Maintainer.ConstructError("Can't open VFX Settings!")); result = false; } break; case AssetSettingsKind.Unknown: if (!string.IsNullOrEmpty(path)) EditorUtility.RevealInFinder(path); break; default: throw new ArgumentOutOfRangeException(); } return result; } public static string NicifyName(string name) { var nicePropertyName = ObjectNames.NicifyVariableName(name); if (textInfo == null) textInfo = new CultureInfo("en-US", false).TextInfo; return textInfo.ToTitleCase(nicePropertyName); } public static AssetKind GetAssetKind(string path) { if (!Path.IsPathRooted(path)) { if (path.IndexOf("Assets/", StringComparison.Ordinal) == 0) { return AssetKind.Regular; } if (path.IndexOf("ProjectSettings/", StringComparison.Ordinal) == 0) { return AssetKind.Settings; } if (path.IndexOf("Packages/", StringComparison.Ordinal) == 0) { return AssetKind.FromPackage; } } else { if (path.IndexOf("/unity/cache/packages/", StringComparison.OrdinalIgnoreCase) > 0) { return AssetKind.FromPackage; } } return AssetKind.Unsupported; } } }
29.733333
110
0.657243
[ "MIT" ]
654306663/UnityExtensions
Extensions/Maintainer/Editor/Scripts/Tools/CSEditorTools.cs
10,260
C#
using System.Net; namespace AsyncNet.Tcp.Server { public class TcpServerStartedData : TcpServerEventData { public TcpServerStartedData(IPAddress serverAddress, int serverPort) : base(serverAddress, serverPort) { } } }
21.333333
110
0.691406
[ "MIT" ]
lulzzz/AsyncNet
AsyncNet.Tcp/Server/TcpServerStartedData.cs
258
C#
#if ENABLE_UNET using System; using System.Text; using UnityEngine; namespace UnityEngine.Networking { public class NetworkReader { NetBuffer m_buf; const int k_MaxStringLength = 1024 * 32; const int k_InitialStringBufferSize = 1024; static byte[] s_StringReaderBuffer; static Encoding s_Encoding; public NetworkReader() { m_buf = new NetBuffer(); Initialize(); } public NetworkReader(NetworkWriter writer) { m_buf = new NetBuffer(writer.AsArray()); Initialize(); } public NetworkReader(byte[] buffer) { m_buf = new NetBuffer(buffer); Initialize(); } static void Initialize() { if (s_Encoding == null) { s_StringReaderBuffer = new byte[k_InitialStringBufferSize]; s_Encoding = new UTF8Encoding(); } } public uint Position { get { return m_buf.Position; } } public void SeekZero() { m_buf.SeekZero(); } internal void Replace(byte[] buffer) { m_buf.Replace(buffer); } // http://sqlite.org/src4/doc/trunk/www/varint.wiki // NOTE: big endian. public UInt32 ReadPackedUInt32() { byte a0 = ReadByte(); if (a0 < 241) { return a0; } byte a1 = ReadByte(); if (a0 >= 241 && a0 <= 248) { return (UInt32)(240 + 256 * (a0 - 241) + a1); } byte a2 = ReadByte(); if (a0 == 249) { return (UInt32)(2288 + 256 * a1 + a2); } byte a3 = ReadByte(); if (a0 == 250) { return a1 + (((UInt32)a2) << 8) + (((UInt32)a3) << 16); } byte a4 = ReadByte(); if (a0 >= 251) { return a1 + (((UInt32)a2) << 8) + (((UInt32)a3) << 16) + (((UInt32)a4) << 24); } throw new IndexOutOfRangeException("ReadPackedUInt32() failure: " + a0); } public UInt64 ReadPackedUInt64() { byte a0 = ReadByte(); if (a0 < 241) { return a0; } byte a1 = ReadByte(); if (a0 >= 241 && a0 <= 248) { return 240 + 256 * (a0 - ((UInt64)241)) + a1; } byte a2 = ReadByte(); if (a0 == 249) { return 2288 + (((UInt64)256) * a1) + a2; } byte a3 = ReadByte(); if (a0 == 250) { return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16); } byte a4 = ReadByte(); if (a0 == 251) { return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24); } byte a5 = ReadByte(); if (a0 == 252) { return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24) + (((UInt64)a5) << 32); } byte a6 = ReadByte(); if (a0 == 253) { return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24) + (((UInt64)a5) << 32) + (((UInt64)a6) << 40); } byte a7 = ReadByte(); if (a0 == 254) { return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24) + (((UInt64)a5) << 32) + (((UInt64)a6) << 40) + (((UInt64)a7) << 48); } byte a8 = ReadByte(); if (a0 == 255) { return a1 + (((UInt64)a2) << 8) + (((UInt64)a3) << 16) + (((UInt64)a4) << 24) + (((UInt64)a5) << 32) + (((UInt64)a6) << 40) + (((UInt64)a7) << 48) + (((UInt64)a8) << 56); } throw new IndexOutOfRangeException("ReadPackedUInt64() failure: " + a0); } public NetworkInstanceId ReadNetworkId() { return new NetworkInstanceId(ReadPackedUInt32()); } public NetworkSceneId ReadSceneId() { return new NetworkSceneId(ReadPackedUInt32()); } public byte ReadByte() { return m_buf.ReadByte(); } public sbyte ReadSByte() { return (sbyte)m_buf.ReadByte(); } public short ReadInt16() { ushort value = 0; value |= m_buf.ReadByte(); value |= (ushort)(m_buf.ReadByte() << 8); return (short)value; } public ushort ReadUInt16() { ushort value = 0; value |= m_buf.ReadByte(); value |= (ushort)(m_buf.ReadByte() << 8); return value; } public int ReadInt32() { uint value = 0; value |= m_buf.ReadByte(); value |= (uint)(m_buf.ReadByte() << 8); value |= (uint)(m_buf.ReadByte() << 16); value |= (uint)(m_buf.ReadByte() << 24); return (int)value; } public uint ReadUInt32() { uint value = 0; value |= m_buf.ReadByte(); value |= (uint)(m_buf.ReadByte() << 8); value |= (uint)(m_buf.ReadByte() << 16); value |= (uint)(m_buf.ReadByte() << 24); return value; } public long ReadInt64() { ulong value = 0; ulong other = m_buf.ReadByte(); value |= other; other = ((ulong)m_buf.ReadByte()) << 8; value |= other; other = ((ulong)m_buf.ReadByte()) << 16; value |= other; other = ((ulong)m_buf.ReadByte()) << 24; value |= other; other = ((ulong)m_buf.ReadByte()) << 32; value |= other; other = ((ulong)m_buf.ReadByte()) << 40; value |= other; other = ((ulong)m_buf.ReadByte()) << 48; value |= other; other = ((ulong)m_buf.ReadByte()) << 56; value |= other; return (long)value; } public ulong ReadUInt64() { ulong value = 0; ulong other = m_buf.ReadByte(); value |= other; other = ((ulong)m_buf.ReadByte()) << 8; value |= other; other = ((ulong)m_buf.ReadByte()) << 16; value |= other; other = ((ulong)m_buf.ReadByte()) << 24; value |= other; other = ((ulong)m_buf.ReadByte()) << 32; value |= other; other = ((ulong)m_buf.ReadByte()) << 40; value |= other; other = ((ulong)m_buf.ReadByte()) << 48; value |= other; other = ((ulong)m_buf.ReadByte()) << 56; value |= other; return value; } public float ReadSingle() { #if INCLUDE_IL2CPP return BitConverter.ToSingle(BitConverter.GetBytes(ReadUInt32()), 0); #else uint value = ReadUInt32(); return FloatConversion.ToSingle(value); #endif } public double ReadDouble() { #if INCLUDE_IL2CPP return BitConverter.ToDouble(BitConverter.GetBytes(ReadUInt64()), 0); #else ulong value = ReadUInt64(); return FloatConversion.ToDouble(value); #endif } public string ReadString() { UInt16 numBytes = ReadUInt16(); if (numBytes == 0) return ""; if (numBytes >= k_MaxStringLength) { throw new IndexOutOfRangeException("ReadString() too long: " + numBytes); } while (numBytes > s_StringReaderBuffer.Length) { s_StringReaderBuffer = new byte[s_StringReaderBuffer.Length * 2]; } m_buf.ReadBytes(s_StringReaderBuffer, numBytes); char[] chars = s_Encoding.GetChars(s_StringReaderBuffer, 0, numBytes); return new string(chars); } public char ReadChar() { return (char)m_buf.ReadByte(); } public bool ReadBoolean() { int value = m_buf.ReadByte(); return value == 1; } public byte[] ReadBytes(int count) { if (count < 0) { throw new IndexOutOfRangeException("NetworkReader ReadBytes " + count); } byte[] value = new byte[count]; m_buf.ReadBytes(value, (uint)count); return value; } public byte[] ReadBytesAndSize() { ushort sz = ReadUInt16(); if (sz == 0) return null; return ReadBytes(sz); } public Vector2 ReadVector2() { return new Vector2(ReadSingle(), ReadSingle()); } public Vector3 ReadVector3() { return new Vector3(ReadSingle(), ReadSingle(), ReadSingle()); } public Vector4 ReadVector4() { return new Vector4(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()); } public Color ReadColor() { return new Color(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()); } public Color32 ReadColor32() { return new Color32(ReadByte(), ReadByte(), ReadByte(), ReadByte()); } public Quaternion ReadQuaternion() { return new Quaternion(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()); } public Rect ReadRect() { return new Rect(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle()); } public Plane ReadPlane() { return new Plane(ReadVector3(), ReadSingle()); } public Ray ReadRay() { return new Ray(ReadVector3(), ReadVector3()); } public Matrix4x4 ReadMatrix4x4() { Matrix4x4 m = new Matrix4x4(); m.m00 = ReadSingle(); m.m01 = ReadSingle(); m.m02 = ReadSingle(); m.m03 = ReadSingle(); m.m10 = ReadSingle(); m.m11 = ReadSingle(); m.m12 = ReadSingle(); m.m13 = ReadSingle(); m.m20 = ReadSingle(); m.m21 = ReadSingle(); m.m22 = ReadSingle(); m.m23 = ReadSingle(); m.m30 = ReadSingle(); m.m31 = ReadSingle(); m.m32 = ReadSingle(); m.m33 = ReadSingle(); return m; } public NetworkHash128 ReadNetworkHash128() { NetworkHash128 hash; hash.i0 = ReadByte(); hash.i1 = ReadByte(); hash.i2 = ReadByte(); hash.i3 = ReadByte(); hash.i4 = ReadByte(); hash.i5 = ReadByte(); hash.i6 = ReadByte(); hash.i7 = ReadByte(); hash.i8 = ReadByte(); hash.i9 = ReadByte(); hash.i10 = ReadByte(); hash.i11 = ReadByte(); hash.i12 = ReadByte(); hash.i13 = ReadByte(); hash.i14 = ReadByte(); hash.i15 = ReadByte(); return hash; } public Transform ReadTransform() { NetworkInstanceId netId = ReadNetworkId(); if (netId.IsEmpty()) { return null; } GameObject go = ClientScene.FindLocalObject(netId); if (go == null) { if (LogFilter.logDebug) { Debug.Log("ReadTransform netId:" + netId); } return null; } return go.transform; } public GameObject ReadGameObject() { NetworkInstanceId netId = ReadNetworkId(); if (netId.IsEmpty()) { return null; } GameObject go; if (NetworkServer.active) { go = NetworkServer.FindLocalObject(netId); } else { go = ClientScene.FindLocalObject(netId); } if (go == null) { if (LogFilter.logDebug) { Debug.Log("ReadGameObject netId:" + netId + "go: null"); } } return go; } public NetworkIdentity ReadNetworkIdentity() { NetworkInstanceId netId = ReadNetworkId(); if (netId.IsEmpty()) { return null; } GameObject go; if (NetworkServer.active) { go = NetworkServer.FindLocalObject(netId); } else { go = ClientScene.FindLocalObject(netId); } if (go == null) { if (LogFilter.logDebug) { Debug.Log("ReadNetworkIdentity netId:" + netId + "go: null"); } return null; } return go.GetComponent<NetworkIdentity>(); } public override string ToString() { return m_buf.ToString(); } public TMsg ReadMessage<TMsg>() where TMsg : MessageBase, new() { var msg = new TMsg(); msg.Deserialize(this); return msg; } }; } #endif //ENABLE_UNET
27.187747
187
0.445809
[ "MIT" ]
Haxixi/Unity-Technologies-networkingRuntime
Runtime/NetworkReader.cs
13,757
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Internal.IL.Stubs; using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Represents a single PInvoke MethodFixupCell as defined in the core library. /// </summary> public class PInvokeMethodFixupNode : ObjectNode, ISymbolDefinitionNode { private readonly PInvokeMethodData _pInvokeMethodData; public PInvokeMethodFixupNode(PInvokeMethodData pInvokeMethodData) { _pInvokeMethodData = pInvokeMethodData; } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append("__pinvoke_"); _pInvokeMethodData.AppendMangledName(nameMangler, sb); } public int Offset => 0; public override bool IsShareable => true; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public override ObjectNodeSection Section => ObjectNodeSection.DataSection; public override bool StaticDependenciesAreComputed => true; public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.RequireInitialPointerAlignment(); builder.AddSymbol(this); // // Emit a MethodFixupCell struct // // Address (to be fixed up at runtime) builder.EmitZeroPointer(); // Entry point name string entryPointName = _pInvokeMethodData.EntryPointName; if (factory.Target.IsWindows && entryPointName.StartsWith("#", StringComparison.OrdinalIgnoreCase)) { // Windows-specific ordinal import // CLR-compatible behavior: Strings that can't be parsed as a signed integer are treated as zero. int entrypointOrdinal; if (!int.TryParse(entryPointName.Substring(1), out entrypointOrdinal)) entrypointOrdinal = 0; // CLR-compatible behavior: Ordinal imports are 16-bit on Windows. Discard rest of the bits. builder.EmitNaturalInt((ushort)entrypointOrdinal); } else { // Import by name builder.EmitPointerReloc(factory.ConstantUtf8String(entryPointName)); } // Module fixup cell builder.EmitPointerReloc(factory.PInvokeModuleFixup(_pInvokeMethodData.ModuleData)); builder.EmitInt((int)_pInvokeMethodData.CharSetMangling); return builder.ToObjectData(); } public override int ClassCode => -1592006940; public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return _pInvokeMethodData.CompareTo(((PInvokeMethodFixupNode)other)._pInvokeMethodData, comparer); } } public readonly struct PInvokeMethodData : IEquatable<PInvokeMethodData> { public readonly PInvokeModuleData ModuleData; public readonly string EntryPointName; public readonly CharSet CharSetMangling; public PInvokeMethodData(PInvokeLazyFixupField pInvokeLazyFixupField) { PInvokeMetadata metadata = pInvokeLazyFixupField.PInvokeMetadata; ModuleDesc declaringModule = ((MetadataType)pInvokeLazyFixupField.TargetMethod.OwningType).Module; DllImportSearchPath? dllImportSearchPath = default; if (declaringModule.Assembly is EcmaAssembly asm) { // We look for [assembly:DefaultDllImportSearchPaths(...)] var attrHandle = asm.MetadataReader.GetCustomAttributeHandle(asm.AssemblyDefinition.GetCustomAttributes(), "System.Runtime.InteropServices", "DefaultDllImportSearchPathsAttribute"); if (!attrHandle.IsNil) { var attr = asm.MetadataReader.GetCustomAttribute(attrHandle); var decoded = attr.DecodeValue(new CustomAttributeTypeProvider(asm)); if (decoded.FixedArguments.Length == 1 && decoded.FixedArguments[0].Value is int searchPath) { dllImportSearchPath = (DllImportSearchPath)searchPath; } } } ModuleData = new PInvokeModuleData(metadata.Module, dllImportSearchPath, declaringModule); EntryPointName = metadata.Name; CharSet charSetMangling = default; if (declaringModule.Context.Target.IsWindows && !metadata.Flags.ExactSpelling) { // Mirror CharSet normalization from Marshaller.CreateMarshaller bool isAnsi = metadata.Flags.CharSet switch { CharSet.Ansi => true, CharSet.Unicode => false, CharSet.Auto => false, _ => true }; charSetMangling = isAnsi ? CharSet.Ansi : CharSet.Unicode; } CharSetMangling = charSetMangling; } public bool Equals(PInvokeMethodData other) { return ModuleData.Equals(other.ModuleData) && EntryPointName == other.EntryPointName && CharSetMangling == other.CharSetMangling; } public override bool Equals(object obj) { return obj is PInvokeMethodData other && Equals(other); } public override int GetHashCode() { return ModuleData.GetHashCode() ^ EntryPointName.GetHashCode(); } public int CompareTo(PInvokeMethodData other, CompilerComparer comparer) { var entryPointCompare = StringComparer.Ordinal.Compare(EntryPointName, other.EntryPointName); if (entryPointCompare != 0) return entryPointCompare; var moduleCompare = ModuleData.CompareTo(other.ModuleData, comparer); if (moduleCompare != 0) return moduleCompare; return CharSetMangling.CompareTo(other.CharSetMangling); } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { ModuleData.AppendMangledName(nameMangler, sb); sb.Append("__"); sb.Append(EntryPointName); if (CharSetMangling != default) { sb.Append("__"); sb.Append(CharSetMangling.ToString()); } } } }
38.149171
122
0.620565
[ "MIT" ]
333fred/runtime
src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/PInvokeMethodFixupNode.cs
6,905
C#
using BookFast.Booking.QueryStack.Representations; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace BookFast.Booking.QueryStack { public interface IBookingQueryDataSource { Task<BookingRepresentation> FindAsync(Guid id); Task<IEnumerable<BookingRepresentation>> ListPendingAsync(string user); } }
26.142857
79
0.775956
[ "MIT" ]
PeterJD/book-fast-service-fabric
BookFast.Booking.QueryStack/IBookingQueryDataSource.cs
368
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("AssetPromiseKeeper_AssetBundleModelTests")] namespace DCL { public class AssetPromiseKeeper_AB_GameObject : AssetPromiseKeeper<Asset_AB_GameObject, AssetLibrary_AB_GameObject, AssetPromise_AB_GameObject> { private static AssetPromiseKeeper_AB_GameObject instance; public static AssetPromiseKeeper_AB_GameObject i { get { return instance ??= new AssetPromiseKeeper_AB_GameObject(); } } public AssetPromiseKeeper_AB_GameObject() : base(new AssetLibrary_AB_GameObject()) { } protected override void OnSilentForget(AssetPromise_AB_GameObject promise) { promise.asset.Hide(); } } }
40.882353
147
0.789928
[ "Apache-2.0" ]
CarlosPolygonalMind/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/AssetManager/AssetBundles/AB_GameObject/AssetPromiseKeeper_AB_GameObject.cs
695
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("biggestOfFive")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("biggestOfFive")] [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("f9935533-e6ee-428a-9e8b-821c97ba51ef")] // 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")]
37.810811
84
0.745533
[ "MIT" ]
lubangelova/Csharp-Fundamentals
homework/ConditionalStatement/biggestOfFive/Properties/AssemblyInfo.cs
1,402
C#
using System.Threading.Tasks; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; using TestVersionGrainInterfaces; using Xunit; namespace Tester.HeterogeneousSilosTests.UpgradeTests { [TestCategory("Versioning"), TestCategory("ExcludeXAML"), TestCategory("SlowBVT"), TestCategory("Functional")] public class VersionPlacementTests : UpgradeTestsBase { protected override short SiloCount => 3; protected override VersionSelectorStrategy VersionSelectorStrategy => AllCompatibleVersions.Singleton; protected override CompatibilityStrategy CompatibilityStrategy => AllVersionsCompatible.Singleton; [Fact] public async Task ActivateDominantVersion() { await StartSiloV1(); var grain0 = Client.GetGrain<IVersionPlacementTestGrain>(0); Assert.Equal(1, await grain0.GetVersion()); await StartSiloV2(); for (var i = 1; i < 101; i++) { var grain1 = Client.GetGrain<IVersionPlacementTestGrain>(i); Assert.Equal(1, await grain1.GetVersion()); } await StartSiloV2(); for (var i = 101; i < 201; i++) { var grain2 = Client.GetGrain<IVersionPlacementTestGrain>(i); Assert.Equal(2, await grain2.GetVersion()); } } } }
32.488372
114
0.638511
[ "MIT" ]
1007lu/orleans
test/Tester/HeterogeneousSilosTests/UpgradeTests/VersionPlacementTests.cs
1,397
C#
namespace VSTS.Net.Types { public enum QueryType { Unknown, Flat, Tree } }
11.2
25
0.491071
[ "MIT" ]
BerserkerDotNet/VSTS.Net
src/VSTS.Net/Types/QueryType.cs
114
C#
using UnityEngine; using EZCameraShake; /* * This script begins shaking the camera when the player enters the trigger, and stops shaking when the player leaves. */ public class ShakeOnTrigger : MonoBehaviour { //Our saved shake instance. private CameraShakeInstance _shakeInstance; void Start() { //We make a single shake instance that we will fade in and fade out when the player enters and leaves the trigger area. _shakeInstance = CameraShaker.Instance.StartShake(2, 15, 2); //Immediately make the shake inactive. _shakeInstance.StartFadeOut(0); //We don't want our shake to delete itself once it stops shaking. _shakeInstance.DeleteOnInactive = true; } //When the player enters the trigger, begin shaking. void OnTriggerEnter(Collider c) { //Check to make sure the object that entered the trigger was the player. if (c.CompareTag("Player")) _shakeInstance.StartFadeIn(1); } //When the player exits the trigger, stop shaking. void OnTriggerExit(Collider c) { //Check to make sure the object that exited the trigger was the player. if (c.CompareTag("Player")) { //Fade out the shake over 3 seconds. _shakeInstance.StartFadeOut(3f); } } }
31.795455
128
0.63331
[ "MIT" ]
Brianspha/DodgeEM
Assets/EZ Camera Shake/Demo/Sample Scripts/ShakeOnTrigger.cs
1,401
C#
using Identity.Api.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Identity.Api.Contracts.V1.Responses { public class DoctorViewModel : IViewModel { public string Id { get; set; } public string Username { get; set; } public string Email { get; set; } public string PicPath { get; set; } public Departments Department { get; set; } public List<string> Roles { get; set; } } }
25.55
51
0.649706
[ "Apache-2.0" ]
AhmedKhalil777/TavssOnContainers.Identity
Contracts/V1/Responses/DoctorViewModel.cs
513
C#
namespace SunLine.Community.Repositories.Infrastructure { public interface IDbSession { IDatabaseContext Current { get; } } }
18.375
56
0.693878
[ "Apache-2.0" ]
mczachurski/community
SunLine.Community.Repositories/Infrastructure/IDbSession.cs
149
C#
using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using DidNet.Common; using Newtonsoft.Json; namespace DidNet.Json.Newtonsoft.ModelExt { /// <summary> /// https://www.w3.org/TR/did-core/#service-endpoints /// </summary> [DebuggerDisplay("Service(Id = {Id})")] [DataContract] public class ServiceExt : Service { [JsonExtensionData] public override IDictionary<string, object>? AdditionalData { get; set; } } }
23.045455
81
0.684418
[ "MIT" ]
decentralized-identity/did-common-dotnet
src/DidNet.Json.Newtonsoft/ModelExt/ServiceExt.cs
507
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime:4.0.30319.42000 // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </auto-generated> //------------------------------------------------------------------------------ namespace Win.Rentas { using System; using System.ComponentModel; using CrystalDecisions.Shared; using CrystalDecisions.ReportSource; using CrystalDecisions.CrystalReports.Engine; public class ReporteProductos : ReportClass { public ReporteProductos() { } public override string ResourceName { get { return "ReporteProductos.rpt"; } set { // Do nothing } } public override bool NewGenerator { get { return true; } set { // Do nothing } } public override string FullResourceName { get { return "Win.Rentas.ReporteProductos.rpt"; } set { // Do nothing } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section1 { get { return this.ReportDefinition.Sections[0]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section2 { get { return this.ReportDefinition.Sections[1]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section3 { get { return this.ReportDefinition.Sections[2]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section4 { get { return this.ReportDefinition.Sections[3]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section5 { get { return this.ReportDefinition.Sections[4]; } } } [System.Drawing.ToolboxBitmapAttribute(typeof(CrystalDecisions.Shared.ExportOptions), "report.bmp")] public class CachedReporteProductos : Component, ICachedReport { public CachedReporteProductos() { } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual bool IsCacheable { get { return true; } set { // } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual bool ShareDBLogonInfo { get { return false; } set { // } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual System.TimeSpan CacheTimeOut { get { return CachedReportConstants.DEFAULT_TIMEOUT; } set { // } } public virtual CrystalDecisions.CrystalReports.Engine.ReportDocument CreateReport() { ReporteProductos rpt = new ReporteProductos(); rpt.Site = this.Site; return rpt; } public virtual string GetCustomizedCacheKey(RequestContext request) { String key = null; // // The following is the code used to generate the default // // cache key for caching report jobs in the ASP.NET Cache. // // Feel free to modify this code to suit your needs. // // Returning key == null causes the default cache key to // // be generated. // // key = RequestContext.BuildCompleteCacheKey( // request, // null, // sReportFilename // this.GetType(), // this.ShareDBLogonInfo ); return key; } } }
33.474026
112
0.548206
[ "MIT" ]
adelyprz/ventas
SistemaRentas/Rentas/Win.Rentas/ReporteProductos.cs
5,162
C#
using Cake.Core; using Cake.Core.Annotations; using System; using System.Collections.Generic; namespace Cake.AppCenter { partial class AppCenterAliases { /// <summary> /// Release a React Native update to an app deployment /// </summary> /// <param name="context">The context.</param> /// <param name="settings">The settings.</param> [CakeMethodAlias] [CakeAliasCategory("Codepush")] public static void AppCenterCodepushReleaseReact(this ICakeContext context, AppCenterCodepushReleaseReactSettings settings) { if (context == null) { throw new ArgumentNullException("context"); } var arguments = new string[0]; var runner = new GenericRunner<AppCenterCodepushReleaseReactSettings >(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); runner.Run("codepush release-react", settings ?? new AppCenterCodepushReleaseReactSettings(), arguments); } /// <summary> /// Release a React Native update to an app deployment /// </summary> /// <param name="context">The context.</param> /// <param name="settings">The settings.</param> /// <returns>Output lines.</returns> [CakeMethodAlias] [CakeAliasCategory("Codepush")] public static IEnumerable<string> AppCenterCodepushReleaseReactWithResult(this ICakeContext context, AppCenterCodepushReleaseReactSettings settings) { if (context == null) { throw new ArgumentNullException("context"); } var arguments = new string[0]; var runner = new GenericRunner<AppCenterCodepushReleaseReactSettings >(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools); return runner.RunWithResult("codepush release-react", settings ?? new AppCenterCodepushReleaseReactSettings(), arguments); } } }
36.392157
162
0.70528
[ "MIT" ]
cake-contrib/Cake.AppCenter
src/Cake.AppCenter/Codepush/ReleaseReact/AppCenter.Alias.CodepushReleaseReact.cs
1,856
C#
using System; using System.Diagnostics; namespace Shriek.ServiceProxy.Socket.Exceptions { /// <summary> /// 表示远程端Api行为异常 /// </summary> [DebuggerDisplay("Message = {Message}")] public class RemoteException : Exception { /// <summary> /// 远程端Api行为异常 /// </summary> /// <param name="message">异常信息</param> public RemoteException(string message) : base(message) { } /// <summary> /// 从string隐式转换 /// </summary> /// <param name="message">异常信息</param> /// <returns></returns> public static implicit operator RemoteException(string message) { return new RemoteException(message); } } }
24.290323
71
0.545817
[ "MIT" ]
1051324354/shriek-fx
src/Shriek.ServiceProxy.Socket/Exceptions/RemoteException.cs
813
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetControl4BioMed.Data; using NetControl4BioMed.Data.Models; using NetControl4BioMed.Data.Seed; using System; using System.Linq; using System.Threading.Tasks; namespace NetControl4BioMed.Helpers.Extensions { /// <summary> /// Provides extensions for the application builder. /// </summary> public static class ApplicationBuilderExtensions { /// <summary> /// Seeds the database, if needed, with a default "Administrator" role and users and the code-defined algorithms. /// </summary> /// <param name="app">Represents the application builder.</param> /// <param name="configuration">Represents the application configuration options.</param> /// <returns></returns> public static async Task<IApplicationBuilder> SeedDatabaseAsync(this IApplicationBuilder app, IConfiguration configuration) { // Create the scope for the application. using var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope(); // Get the service provider. var serviceProvider = serviceScope.ServiceProvider; // Get the required services. var roleManager = serviceProvider.GetRequiredService<RoleManager<Role>>(); var userManager = serviceProvider.GetRequiredService<UserManager<User>>(); var context = serviceProvider.GetRequiredService<ApplicationDbContext>(); // Check if the administrator role doesn't already exist. if (!await roleManager.RoleExistsAsync("Administrator")) { // Define a new administrator role. var role = new Role { Name = "Administrator", DateTimeCreated = DateTime.Now }; // Save it into the database. await roleManager.CreateAsync(role); } // Check if administrator users don't already exist. if (!(await userManager.GetUsersInRoleAsync("Administrator")).Any()) { // Get the data for the default administrator users. var items = configuration.GetSection("Administrators").GetChildren().Select(item => new { Email = item.GetSection("Email").Value, Password = item.GetSection("Password").Value }); // Go over each of the users. foreach (var item in items) { // Try to get the user with the provided e-mail. var user = await userManager.FindByEmailAsync(item.Email); // Check if the user is already defined. if (user != null) { // Add the user to the administrator role. await userManager.AddToRoleAsync(user, "Administrator"); // Go to the next user. continue; } // Define a new user. user = new User() { UserName = item.Email, Email = item.Email, EmailConfirmed = true, DateTimeCreated = DateTime.Now }; // Save it into the database. await userManager.CreateAsync(user, item.Password); // Add the user to the administrator role. await userManager.AddToRoleAsync(user, "Administrator"); } // Check if there isn't any entry already defined. if (!context.DatabaseTypes.Any()) { // Mark the seed data for addition. context.DatabaseTypes.AddRange(DatabaseTypes.Seed); // Save the changes. await context.SaveChangesAsync(); } // Check if there isn't any entry already defined. if (!context.Databases.Any()) { // Mark the seed data for addition. context.Databases.AddRange(Databases.Seed); // Save the changes. await context.SaveChangesAsync(); } // Check if there isn't any entry already defined. if (!context.DatabaseNodeFields.Any()) { // Mark the seed data for addition. context.DatabaseNodeFields.AddRange(DatabaseNodeFields.Seed); // Save the changes. await context.SaveChangesAsync(); } // Check if there isn't any entry already defined. if (!context.DatabaseEdgeFields.Any()) { // Mark the seed data for addition. context.DatabaseEdgeFields.AddRange(DatabaseEdgeFields.Seed); // Save the changes. await context.SaveChangesAsync(); } } // Return the application. return app; } } }
46.293103
194
0.542831
[ "MIT" ]
angelcnx/NetControl4BioMed
NetControl4BioMed/Helpers/Extensions/ApplicationBuilderExtensions.cs
5,372
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(EasyJsonToSql.Demo.Startup))] namespace EasyJsonToSql.Demo { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
19.105263
60
0.647383
[ "MIT" ]
434773840/EasyJsonToSql
src/EasyJsonToSqlDemo/Startup.cs
365
C#
using Microsoft.Xaml.Interactivity; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; namespace Pithline.FMS.BusinessLogic.Behaviors { public abstract class Behavior<T> : DependencyObject, IBehavior where T : DependencyObject { public T AssociatedObject { get; private set; } DependencyObject IBehavior.AssociatedObject { get { return this.AssociatedObject; } } protected abstract void OnAttached(); protected abstract void OnDetached(); public void Attach(DependencyObject associatedObject) { if (associatedObject != null && !typeof(T).GetTypeInfo().IsAssignableFrom(associatedObject.GetType().GetTypeInfo())) throw new Exception(string.Format("associatedObject is not assignable to type:", typeof(T))); this.AssociatedObject = associatedObject as T; this.OnAttached(); } public void Detach() { this.OnDetached(); this.AssociatedObject = null; } } }
28.487805
128
0.657534
[ "MIT" ]
noorsyyad/FleetManagementSystem
Pithline.FMS.BusinessLogic/Behaviors/Behavior.cs
1,168
C#
using System.Collections.Generic; namespace SvgMath { public class MathVariant { public MathVariant(string name, string weight, string style) { Name = name; Weight = weight; Style = style; Families = new List<string>(); } public void AddFamily(string familyName) { Families.Add(familyName); } public string Name; public List<string> Families; public string Weight; public string Style; } }
21.8
68
0.548624
[ "MIT" ]
Toxaris-NL/SvgMath
SvgMath/Configuration/MathVariant.cs
547
C#
using UnityEngine; /// <summary> /// A timer /// </summary> public class Timer : MonoBehaviour { #region Fields // timer duration float totalSeconds = 0; // timer execution float elapsedSeconds = 0; bool running = false; // support for Finished property bool started = false; #endregion #region Properties /// <summary> /// Sets the duration of the timer /// The duration can only be set if the timer isn't currently running /// </summary> /// <value>duration</value> public float Duration { set { if (!running) { totalSeconds = value; } } } /// <summary> /// Gets whether or not the timer has finished running /// This property returns false if the timer has never been started /// </summary> /// <value>true if finished; otherwise, false.</value> public bool Finished { get { return started && !running; } } /// <summary> /// Gets whether or not the timer is currently running /// </summary> /// <value>true if running; otherwise, false.</value> public bool Running { get { return running; } } #endregion #region Methods /// <summary> /// Update is called once per frame /// </summary> void Update() { // update timer and check for finished if (running) { elapsedSeconds += Time.deltaTime; if (elapsedSeconds >= totalSeconds) { running = false; } } } /// <summary> /// Runs the timer /// Because a timer of 0 duration doesn't really make sense, /// the timer only runs if the total seconds is larger than 0 /// This also makes sure the consumer of the class has actually /// set the duration to something higher than 0 /// </summary> public void Run() { // only run with valid duration if (totalSeconds > 0) { started = true; running = true; elapsedSeconds = 0; } } /// <summary> /// Stops the timer /// </summary> public void Stop() { started = false; running = false; } public void AddTime(float seconds) { totalSeconds += seconds; } #endregion }
17.690265
70
0.644322
[ "MIT" ]
VsIG-official/Study-Projects
Unity/Intermediate Object-Oriented Programming for Unity Games/3_week/UnityAssignment3/WackyBreakout/Assets/scripts/Gameplay/Timer.cs
2,001
C#
/* * SerialNumberHighCommand.cs * * Copyright (c) 2009, Michael Schwarz (http://www.schwarz-interactive.de) * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ using System; using System.Text; using MFToolkit.IO; namespace MFToolkit.Net.XBee { public class SerialNumberHighCommand : AtCommand { internal static string command = "SH"; public SerialNumberHighCommand() : base(SerialNumberHighCommand.command) { } } }
36.333333
78
0.726081
[ "MIT" ]
MatthewJallah/NETMF-Toolkit
Zigbee/Request/AT/SerialNumberHigh.cs
1,528
C#
using Microsoft.Azure.Cosmos; using Newtonsoft.Json; namespace Cosmos.Abstracts.Tests.Models { [Container(nameof(Template), "/ownerId")] public class Template : CosmosEntity { public string Name { get; set; } public string Description { get; set; } [PartitionKey] [JsonProperty(PropertyName = "ownerId")] public string OwnerId { get; set; } public override PartitionKey GetPartitionKey() { return new PartitionKey(OwnerId); } } }
22.913043
54
0.622391
[ "MIT" ]
loresoft/Cosmos.Abstracts
test/Cosmos.Abstracts.Tests/Models/Template.cs
529
C#
using Nethereum.BlockchainStore.AzureTables.Bootstrap; using Nethereum.Hex.HexTypes; using Nethereum.Microsoft.Configuration.Utils; using System; using System.Collections.Generic; using System.Numerics; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Nethereum.BlockchainStore.Samples.Storage { public class AzureTableStorageExamples { private readonly Web3.Web3 _web3; private readonly string _azureConnectionString; private const string URL = "https://rinkeby.infura.io/v3/7238211010344719ad14a89db874158c"; public AzureTableStorageExamples() { _web3 = new Web3.Web3(URL); ConfigurationUtils.SetEnvironmentAsDevelopment(); var config = ConfigurationUtils.Build(args: Array.Empty<string>(), userSecretsId: "Nethereum.BlockchainStore.AzureTables"); _azureConnectionString = config["AzureStorageConnectionString"]; } [Fact] public async Task BlockStorageProcessing() { var repoFactory = new AzureTablesRepositoryFactory(_azureConnectionString, "bspsamples"); try { //create our processor var processor = _web3.Processing.Blocks.CreateBlockStorageProcessor(repoFactory); //if we need to stop the processor mid execution - call cancel on the token var cancellationToken = new CancellationToken(); //crawl the required block range await processor.ExecuteAsync( toBlockNumber: new BigInteger(2830144), cancellationToken: cancellationToken, startAtBlockNumberIfNotProcessed: new BigInteger(2830144)); var block = await repoFactory.CreateBlockRepository().FindByBlockNumberAsync(new HexBigInteger(2830144)); Assert.NotNull(block); } finally { await repoFactory.DeleteAllTables(); } } } }
35.672414
135
0.652006
[ "MIT" ]
Dave-Whiffin/Nethereum.BlockchainStorage
src/Nethereum.BlockchainStore.Samples/Storage/AzureTableStorageExamples.cs
2,071
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectSpawner : MonoBehaviour { public GameObject m_Object; public Transform m_SpawnLocation; void Start() { } void Update() { } public void Spawn() { Instantiate(m_Object, m_SpawnLocation.position, m_SpawnLocation.rotation); } }
14.692308
82
0.672775
[ "MIT" ]
KaiArch2014/HUD-with-Leap-Motion
Assets/LeapMotionGestureDetection/GestureDetection/Scripts/ExampleScripts/ObjectSpawner.cs
384
C#
using System; using System.Linq; using AutoMapper; using DatingApp.API.DTO; using DatingApp.API.Helpers; using DatingApp.API.Models; namespace DatingApp.API.Mapper { public class AutoMapperProfile : Profile { public AutoMapperProfile() { CreateMap<User, UserForListDto>() .ForMember(dest => dest.PhotoUrl, opt => { opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url); }) .ForMember(dest => dest.Age, opt => opt.ResolveUsing(d => d.DateOfBirth.CalculateAge()) ) .ForMember(dest => dest.PasswordHash, opt => opt.Ignore()) .ForMember(dest => dest.PasswordSalt, opt => opt.Ignore()); CreateMap<User, UserForDetailsDto>() .ForMember(dest => dest.PhotoUrl, opt => { opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url); }) .ForMember(dest => dest.Age, opt => opt.ResolveUsing(d => d.DateOfBirth.CalculateAge()) ) .ForMember(dest => dest.PasswordHash, opt => opt.Ignore()) .ForMember(dest => dest.PasswordSalt, opt => opt.Ignore()); CreateMap<Photos, PhotoForDetaisDto>(); CreateMap<UserForUpdateDTO, User>(); CreateMap<PhotoForCreationDTO, Photos>(); CreateMap<Photos, PhotoForReturnDTO>(); CreateMap<UserForRegister, User>(); } // public static int CalculateAge(DateTime theDateTime) // { // var age = DateTime.Today.Year - theDateTime.Year; // return age; // } } }
34.117647
105
0.53908
[ "MIT" ]
Fudalii/Angular_CSharp
DatingApp.API/Mapper/AutoMapperProfile.cs
1,740
C#
namespace SisoDb.Querying { public static class QueryExtensions { public static bool HasNoDependencies(this IQuery query) { return query.IsEmpty || (query.HasTakeNumOfStructures && !query.HasPaging && !query.HasSkipNumOfStructures && !query.HasSortings && !query.HasWhere); } } }
33.6
162
0.64881
[ "MIT" ]
eric-swann-q2/SisoDb-Provider
Source/Projects/SisoDb/Querying/QueryExtensions.cs
336
C#
// <copyright file="AWSLambdaWrapperTests.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Moq; using OpenTelemetry.Contrib.Instrumentation.AWSLambda.Implementation; using OpenTelemetry.Resources; using OpenTelemetry.Trace; using Xunit; namespace OpenTelemetry.Contrib.Instrumentation.AWSLambda.Tests { public class AWSLambdaWrapperTests { private readonly SampleHandlers sampleHandlers; private readonly SampleLambdaContext sampleLambdaContext; public AWSLambdaWrapperTests() { this.sampleHandlers = new SampleHandlers(); this.sampleLambdaContext = new SampleLambdaContext(); Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1"); Environment.SetEnvironmentVariable("AWS_REGION", "us-east-1"); Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME", "testfunction"); Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_VERSION", "latest"); } [Fact] public void TestLambdaHandler() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { var result = AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerSyncReturn, "TestStream", this.sampleLambdaContext); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); this.AssertSpanAttributes(activity); } [Fact] public void TestLambdaHandlerNoReturn() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerSyncNoReturn, "TestStream", this.sampleLambdaContext); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); this.AssertSpanAttributes(activity); } [Fact] public async Task TestLambdaHandlerAsync() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { var result = await AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerAsyncReturn, "TestStream", this.sampleLambdaContext); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); this.AssertSpanAttributes(activity); } [Fact] public async Task TestLambdaHandlerAsyncNoReturn() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { await AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerAsyncNoReturn, "TestStream", this.sampleLambdaContext); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); this.AssertSpanAttributes(activity); } [Fact] public void TestLambdaHandlerNoContext() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { var result = AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerSyncReturn, "TestStream"); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); } [Fact] public void TestLambdaHandlerNoContextNoReturn() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerSyncNoReturn, "TestStream"); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); } [Fact] public async Task TestLambdaHandlerAsyncNoContext() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { var result = await AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerAsyncReturn, "TestStream"); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); } [Fact] public async Task TestLambdaHandlerAsyncNoContextNoReturn() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { await AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerAsyncNoReturn, "TestStream"); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); } [Fact] public void TestLambdaHandlerException() { var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { try { AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerSyncNoReturnException, "TestException", this.sampleLambdaContext); } catch { var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } } // SetParentProvider -> OnStart -> OnEnd -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(6, processor.Invocations.Count); var activity = (Activity)processor.Invocations[1].Arguments[0]; this.AssertSpanProperties(activity); this.AssertSpanAttributes(activity); this.AssertSpanException(activity); } [Fact] public void TestLambdaHandlerNotSampled() { Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=0"); var processor = new Mock<BaseProcessor<Activity>>(); using (var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAWSLambdaConfigurations() .AddProcessor(processor.Object) .Build()) { var result = AWSLambdaWrapper.Trace(tracerProvider, this.sampleHandlers.SampleHandlerSyncReturn, "TestStream", this.sampleLambdaContext); var resource = tracerProvider.GetResource(); this.AssertResourceAttributes(resource); } // SetParentProvider -> OnForceFlush -> OnShutdown -> Dispose Assert.Equal(4, processor.Invocations.Count); var activities = processor.Invocations.Where(i => i.Method.Name == "OnEnd").Select(i => i.Arguments[0]).Cast<Activity>().ToArray(); Assert.True(activities.Length == 0); } private void AssertSpanProperties(Activity activity) { Assert.Equal("5759e988bd862e3fe1be46a994272793", activity.TraceId.ToHexString()); Assert.Equal("53995c3f42cd8ad8", activity.ParentSpanId.ToHexString()); Assert.Equal(ActivityTraceFlags.Recorded, activity.ActivityTraceFlags); Assert.Equal(ActivityKind.Server, activity.Kind); Assert.Equal("testfunction", activity.DisplayName); } private void AssertResourceAttributes(Resource resource) { var resourceAttributes = resource.Attributes.ToDictionary(x => x.Key, x => x.Value); Assert.Equal("aws", resourceAttributes[AWSLambdaSemanticConventions.AttributeCloudProvider]); Assert.Equal("us-east-1", resourceAttributes[AWSLambdaSemanticConventions.AttributeCloudRegion]); Assert.Equal("testfunction", resourceAttributes[AWSLambdaSemanticConventions.AttributeFaasName]); Assert.Equal("latest", resourceAttributes[AWSLambdaSemanticConventions.AttributeFaasVersion]); } private void AssertSpanAttributes(Activity activity) { Assert.Equal(this.sampleLambdaContext.AwsRequestId, activity.GetTagValue(AWSLambdaSemanticConventions.AttributeFaasExecution)); Assert.Equal(this.sampleLambdaContext.InvokedFunctionArn, activity.GetTagValue(AWSLambdaSemanticConventions.AttributeFaasID)); Assert.Equal("111111111111", activity.GetTagValue(AWSLambdaSemanticConventions.AttributeCloudAccountID)); } private void AssertSpanException(Activity activity) { Assert.Equal("ERROR", activity.GetTagValue(SpanAttributeConstants.StatusCodeKey)); Assert.NotNull(activity.GetTagValue(SpanAttributeConstants.StatusDescriptionKey)); } } }
43.132258
160
0.635854
[ "Apache-2.0" ]
alanwest/opentelemetry-dotnet-contrib
test/OpenTelemetry.Contrib.Instrumentation.AWSLambda.Tests/AWSLambdaWrapperTests.cs
13,371
C#
// https://github.com/Cysharp/UniTask // bu özelliği aktif etmek için yukarıdaki asseti indiriniz // aksi taktirde allttaki satırı commnt satırı yapınız //#define HasCysharpAsset #if HasCysharpAsset using Cysharp.Threading.Tasks; using static Cysharp.Threading.Tasks.UniTask; #endif using UnityEngine; namespace AnilTools.MoveAsync { using static AnilToolsBase; public static class MoveBaseAsync { /// <summary> /// performans için /// </summary> internal const float Tolerance = 0.05f; #if HasCysharpAsset public static async UniTask TranslateLerp(this Transform From, TranslateData moveInfo) { await WhenAll(From.MoveLerp(moveInfo.To.position, moveInfo.MoveSpeed), From.RotateLerp(new RotateData( moveInfo.To.rotation, moveInfo.RotateSpeed))); } public static async UniTask TranslateTowards(this Transform From, Transform to , float speed,float rotateSpeed = 10) { await WhenAll(From.MoveTowards(to.position, speed), From.RotateLerp(new RotateData(to.rotation, rotateSpeed))); } public static async UniTask TranslateTowards(this Transform From,TranslateData moveInfo, Vector3 anchor) { await WhenAll(From.MoveTowards(moveInfo.To.position + anchor, moveInfo.MoveSpeed), From.RotateLerp(new RotateData(moveInfo.To.rotation, moveInfo.RotateSpeed))); } public static async UniTask TranslateTowardsTime(this Transform From, TranslateData moveInfo,Vector3 anchor, byte time = 6) { await WhenAll(From.MoveTowards(moveInfo.To.position + anchor, moveInfo.MoveSpeed), From.RotateLerp(new RotateData(moveInfo.To.rotation, moveInfo.RotateSpeed,time))); } public static async UniTask TranslateTowardsLocal(this Transform From, TranslateData moveInfo) { await WhenAll(From.MoveTowardsLocal(moveInfo.To.position, moveInfo.MoveSpeed), From.RotateTowardsLocal(new RotateData(moveInfo.To.rotation, moveInfo.RotateSpeed))); } public static async UniTask SmoothLookat(Transform pos, Vector3 targetPos, float speed) { var targetDir = targetPos - pos.position; var targetRot = Quaternion.LookRotation(targetDir); while (Quaternion.Angle(pos.rotation, targetRot) > 1) { pos.rotation = Quaternion.RotateTowards(pos.rotation, targetRot, speed * Time.deltaTime); await Delay(UpdateSpeed); } } #endif public readonly struct RotateData { public readonly Quaternion To; public readonly float Speed; public readonly float time; public RotateData(Quaternion to, float speed,float time = 6) { To = to; Speed = speed; this.time = time; } } public readonly struct TranslateData { public readonly Transform To; public readonly float MoveSpeed; public readonly float RotateSpeed; public TranslateData(Transform to, float moveSpeed, float rotateSpeed) { To = to; MoveSpeed = moveSpeed; RotateSpeed = rotateSpeed; } } } }
36.742268
132
0.605219
[ "MIT" ]
benanil/Bukra_Game
Utils/Move Rotate/AsyncMove/MoveBaseAsync.cs
3,577
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace CoverTemplate { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.36
76
0.694581
[ "MIT" ]
middle-coast-software/NetCoreBootstrapMVC
NetCoreBootstrapMVC/CoverTemplate/Program.cs
611
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; #nullable disable namespace T0001 { public partial class BasePartCargospace { public string Cpartnumber { get; set; } public string Cwareid { get; set; } public string Cpositioncode { get; set; } public string Ccreateownercode { get; set; } public DateTime Cdatetime { get; set; } public string Id { get; set; } } }
29.944444
97
0.640074
[ "MIT" ]
twoutlook/BlazorServerDbContextExample
BlazorServerEFCoreSample/T0001/BasePartCargospace.cs
541
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Project.SpellSystem { public abstract class Spell : ScriptableObject { public string name; public string description; //public Sprite icon; public int manaCost; public float castingTime; public GameObject vfx; public SpellType type; //public abstract void Initialize(GameObject obj); public abstract void TriggerSpell(IDamageable damageable); } public enum SpellType { PROJECTILE, CIRCLE_AREA } }
21.103448
66
0.650327
[ "MIT" ]
Kalystee/WizardGame
Assets/Scripts/Spell/SpellSystem/Spell.cs
614
C#
using appLauncher.Model; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel.Core; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using appLauncher; using Windows.UI; using System.Collections.ObjectModel; using Windows.UI.Input; using Windows.UI.Core; // The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236 namespace appLauncher.Control { public sealed partial class appControl : UserControl { int page; DispatcherTimer dispatcher; public ObservableCollection<finalAppItem> listOfApps { get { return (ObservableCollection<finalAppItem>)GetValue(listOfAppsProperty); } set { SetValue(listOfAppsProperty, value); } } // Using a DependencyProperty as the backing store for listOfApps. This enables animation, styling, binding, etc... public static readonly DependencyProperty listOfAppsProperty = DependencyProperty.Register("listOfApps", typeof(ObservableCollection<finalAppItem>), typeof(appControl), null); //Each copy of this control is binded to an app. //public finalAppItem appItem { get { return this.DataContext as finalAppItem; } } public appControl() { this.InitializeComponent(); this.Loaded += AppControl_Loaded; // this.DataContextChanged += (s, e) => Bindings.Update(); } private void AppControl_Loaded(object sender, RoutedEventArgs e) { //dispatcher = new DispatcherTimer(); //dispatcher.Interval = TimeSpan.FromSeconds(2); //dispatcher.Tick += Dispatcher_Tick; //if (GlobalVariables.pagenum==0) //{ // SwitchedToThisPage(); //} GridViewMain.ItemsSource = AllApps.listOfApps.Skip(GlobalVariables.pagenum * GlobalVariables.appsperscreen).Take(GlobalVariables.appsperscreen).ToList(); } private void Dispatcher_Tick(object sender, object e) { ProgressRing.IsActive = false; dispatcher.Stop(); GridViewMain.ItemsSource = AllApps.listOfApps.Skip(GlobalVariables.pagenum * GlobalVariables.appsperscreen).Take(GlobalVariables.appsperscreen).ToList(); } public void SwitchedToThisPage() { //if (dispatcher != null) //{ // ProgressRing.IsActive = true; // dispatcher.Start(); //} GridViewMain.ItemsSource = AllApps.listOfApps.Skip(GlobalVariables.pagenum * GlobalVariables.appsperscreen).Take(GlobalVariables.appsperscreen).ToList(); } public void SwitchedFromThisPage() { GridViewMain.ItemsSource = null; } private void GridViewMain_DragItemsStarting(object sender, DragItemsStartingEventArgs e) { GlobalVariables.isdragging = true; object item = e.Items.First(); var source = sender; e.Data.Properties.Add("item", item); GlobalVariables.itemdragged = (finalAppItem)item; GlobalVariables.oldindex = AllApps.listOfApps.IndexOf((finalAppItem)item); } private void GridViewMain_Drop(object sender, DragEventArgs e) { GridView view = sender as GridView; // Get your data // var item = e.Data.Properties.Where(p => p.Key == "item").Single(); //Find the position where item will be dropped in the gridview Point pos = e.GetPosition(view.ItemsPanelRoot); //Get the size of one of the list items GridViewItem gvi = (GridViewItem)view.ContainerFromIndex(0); double itemHeight = gvi.ActualHeight + gvi.Margin.Top + gvi.Margin.Bottom; double itemwidth = gvi.ActualHeight + gvi.Margin.Left + gvi.Margin.Right; //Determine the index of the item from the item position (assumed all items are the same size) int index = Math.Min(view.Items.Count - 1, (int)(pos.Y / itemHeight)); int indexy = Math.Min(view.Items.Count - 1, (int)(pos.X / itemwidth)); var t = (List<finalAppItem>)view.ItemsSource; var te = t[((index * GlobalVariables.columns) + (indexy))]; GlobalVariables.newindex = AllApps.listOfApps.IndexOf(te); AllApps.listOfApps.Move(GlobalVariables.oldindex,GlobalVariables.newindex); GlobalVariables.pagenum = (int)this.DataContext; SwitchedToThisPage(); ((Window.Current.Content as Frame).Content as MainPage).UpdateIndicator(GlobalVariables.pagenum); } private void GridViewMain_DragOver(object sender, DragEventArgs e) { GridView d = (GridView)sender; e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move; FlipView c = (FlipView)((Window.Current.Content as Frame).Content as MainPage).getFlipview(); Point startpoint = e.GetPosition(this); if (GlobalVariables.startingpoint.X == 0) { GlobalVariables.startingpoint = startpoint; } else { var a = this.TransformToVisual(c); var b = a.TransformPoint(new Point(0, 0)); if (GlobalVariables.startingpoint.X > startpoint.X && startpoint.X < (b.X + 100)) { if (c.SelectedIndex > 0) { c.SelectedIndex -= 1; GlobalVariables.startingpoint = startpoint; } } else if (GlobalVariables.startingpoint.X < startpoint.X && startpoint.X > (b.X + d.ActualWidth - 100)) { if (c.SelectedIndex < c.Items.Count() - 1) { c.SelectedIndex += 1; GlobalVariables.startingpoint = startpoint; } } } GlobalVariables.pagenum = c.SelectedIndex; ((Window.Current.Content as Frame).Content as MainPage).UpdateIndicator(GlobalVariables.pagenum); } private async void GridViewMain_ItemClick(object sender, ItemClickEventArgs e) { finalAppItem fi = (finalAppItem)e.ClickedItem; await fi.appEntry.LaunchAsync(); } } }
37.727778
165
0.626712
[ "MIT" ]
IsaacMorris1980/UWP-App-Launcher
appLauncher/Control/appControl.xaml.cs
6,793
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.Payroll.Interface { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Time_Tracking_Eligibility_RuleObjectType : INotifyPropertyChanged { private Time_Tracking_Eligibility_RuleObjectIDType[] idField; private string descriptorField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement("ID", Order = 0)] public Time_Tracking_Eligibility_RuleObjectIDType[] ID { get { return this.idField; } set { this.idField = value; this.RaisePropertyChanged("ID"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string Descriptor { get { return this.descriptorField; } set { this.descriptorField = value; this.RaisePropertyChanged("Descriptor"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
22.803279
136
0.742631
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.Payroll.Interface/Time_Tracking_Eligibility_RuleObjectType.cs
1,391
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; using Aop.Api.Domain; namespace Aop.Api.Response { /// <summary> /// KoubeiItemBatchqueryResponse. /// </summary> public class KoubeiItemBatchqueryResponse : AopResponse { /// <summary> /// 当前页码 /// </summary> [XmlElement("current_page_no")] public string CurrentPageNo { get; set; } /// <summary> /// 商品信息 /// </summary> [XmlArray("item_infos")] [XmlArrayItem("item_query_response")] public List<ItemQueryResponse> ItemInfos { get; set; } /// <summary> /// 每页记录数 /// </summary> [XmlElement("page_size")] public string PageSize { get; set; } /// <summary> /// 总共商品数目 /// </summary> [XmlElement("total_items")] public string TotalItems { get; set; } /// <summary> /// 总页码数目 /// </summary> [XmlElement("total_page_no")] public string TotalPageNo { get; set; } } }
24.955556
63
0.521817
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/KoubeiItemBatchqueryResponse.cs
1,171
C#
namespace Gu.Roslyn.AnalyzerExtensions.Tests.Walkers.ExecutionWalkerTests { using System.Threading; using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.CSharp; using NUnit.Framework; public static class Invocation { [TestCase(SearchScope.Member, "2, 3")] [TestCase(SearchScope.Instance, "1, 2, 3")] [TestCase(SearchScope.Type, "1, 2, 3")] [TestCase(SearchScope.Recursive, "1, 2, 3")] public static void StatementBody(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class C { public C() { Equals(this.Value(), 2); int j = 3; } public int Value() { return 1; } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindConstructorDeclaration("C"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "2, 3")] [TestCase(SearchScope.Instance, "2, 3")] [TestCase(SearchScope.Type, "1, 2, 3")] [TestCase(SearchScope.Recursive, "1, 2, 3")] public static void Static(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class C { public C() { Equals(Value(), 2); int j = 3; } public static int Value() { return 1; } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindConstructorDeclaration("C"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "2, 3")] [TestCase(SearchScope.Instance, "2, 3")] [TestCase(SearchScope.Type, "2, 3")] [TestCase(SearchScope.Recursive, "1, 2, 3")] public static void StaticOtherType(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public static class C1 { public static int Value() => 1; } public class C2 { public C2() { Equals(C1.Value(), 2); int j = 3; } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindConstructorDeclaration("C"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "2, 3")] [TestCase(SearchScope.Instance, "1, 2, 3")] [TestCase(SearchScope.Type, "1, 2, 3")] [TestCase(SearchScope.Recursive, "1, 2, 3")] public static void ExpressionBody(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class C { public C() { Equals(this.Value(), 2); int j = 3; } public int Value() => 1; } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindConstructorDeclaration("C"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "1")] [TestCase(SearchScope.Instance, "1, 2")] [TestCase(SearchScope.Type, "1, 2")] [TestCase(SearchScope.Recursive, "1, 2")] public static void WalkOverridden(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class CBase { protected virtual int M() => 2; } public sealed class C : CBase { protected override int M() => 1 * base.M(); } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindMethodDeclaration("protected override int M()"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "2, 3")] [TestCase(SearchScope.Instance, "1, 2, 3")] [TestCase(SearchScope.Type, "1, 2, 3")] [TestCase(SearchScope.Recursive, "1, 2, 3")] public static void InvocationAsArgument(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class C { public C() { Equals(this.Value(), 2); int j = 3; } public int Value() => 1; } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindConstructorDeclaration("C"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "1, 3")] [TestCase(SearchScope.Instance, "1, 2, 3")] [TestCase(SearchScope.Type, "1, 2, 3")] [TestCase(SearchScope.Recursive, "1, 2, 3")] public static void InvocationVirtual(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { using System; public class C : IDisposable { public void Dispose() { var i = 1; Dispose(true); i = 3; } protected virtual void Dispose(bool disposing) { if (disposing) { var j = 2; } } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindMethodDeclaration("public void Dispose()"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "3")] [TestCase(SearchScope.Instance, "1, 2, 3")] [TestCase(SearchScope.Type, "1, 2, 3")] [TestCase(SearchScope.Recursive, "1, 2, 3")] public static void ArgumentBeforeInvocation(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class C { public C() { var value = this.Meh(this.Value()); value = 3; } public int Value() => 1; private int Meh(int i) { return 2 * i; } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindConstructorDeclaration("C"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "3")] [TestCase(SearchScope.Instance, "1, 3")] [TestCase(SearchScope.Type, "1, 2, 3")] [TestCase(SearchScope.Recursive, "1, 2, 3")] public static void ArgumentBeforeInvocationStaticAndInstance(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class C { public C() { var value = Meh(this.Value()); value = 3; } public int Value() => 1; private static int Meh(int i) { return 2 * i; } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindConstructorDeclaration("C"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "")] [TestCase(SearchScope.Instance, "2")] [TestCase(SearchScope.Type, "2")] [TestCase(SearchScope.Recursive, "2")] public static void ExplicitBase(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class BaseClass { protected virtual void M1() { _ = 2; } } public class C : BaseClass { public void Start() => base.M1(); protected override void M1() { _ = 1; base.M1(); } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindMethodDeclaration("Start"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "")] [TestCase(SearchScope.Instance, "1, 2")] [TestCase(SearchScope.Type, "1, 2")] [TestCase(SearchScope.Recursive, "1, 2")] public static void OverrideCallingBase(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class BaseClass { protected virtual void M1() { _ = 2; } } public class C : BaseClass { public void Start() => M1(); protected override void M1() { _ = 1; base.M1(); } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindMethodDeclaration("Start"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "")] [TestCase(SearchScope.Instance, "1, 2")] [TestCase(SearchScope.Type, "1, 2")] [TestCase(SearchScope.Recursive, "1, 2")] public static void OverrideCallingBaseStartingFromBase(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public class BaseClass { public void M1() => this.M2(); protected virtual void M2() { _ = 2; } } public class C : BaseClass { public void Start() => this.M1(); protected override void M2() { _ = 1; base.M2(); } } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindMethodDeclaration("Start"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } [TestCase(SearchScope.Member, "1")] [TestCase(SearchScope.Instance, "1, 2, 2, 2, 2")] [TestCase(SearchScope.Type, "1, 2, 2, 2, 2")] [TestCase(SearchScope.Recursive, "1, 2, 2, 2, 2")] public static void Chained(SearchScope scope, string expected) { var syntaxTree = CSharpSyntaxTree.ParseText(@" namespace N { public static class C { public C() { 1.M() .M() .M() .M(); } public static int M(this int i) => j + 2; } }"); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, Settings.Default.MetadataReferences); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindConstructorDeclaration("C"); using var walker = LiteralWalker.Borrow(node, scope, semanticModel, CancellationToken.None); Assert.AreEqual(expected, string.Join(", ", walker.Literals)); } } }
33.707434
122
0.585586
[ "MIT" ]
JohanLarsson/Gu.Roslyn.Extensions
Gu.Roslyn.AnalyzerExtensions.Tests/Walkers/ExecutionWalkerTests/Invocation.cs
14,058
C#
#region License /* Copyright © 2014-2019 European Support Limited Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using GingerCore; using System; using System.Collections.Generic; namespace Amdocs.Ginger.Common { public enum eUserMsgKey { GeneralErrorOccured, MissingImplementation, MissingImplementation2, ApplicationInitError, PageLoadError, UserProfileLoadError, ItemToSaveWasNotSelected, ToSaveChanges, SaveLocalChanges, LooseLocalChanges, RegistryValuesCheckFailed, AddRegistryValue, AddRegistryValueSucceed, AddRegistryValueFailed, NoItemWasSelected, AskToAddCheckInComment, FailedToGetProjectsListFromSVN, AskToSelectSolution, UpdateToRevision, CommitedToRevision, GitUpdateState, SourceControlConnFaild, SourceControlRemoteCannotBeAccessed, SourceControlUnlockFaild, SourceControlConnSucss, SourceControlLockSucss, SourceControlUnlockSucss, SourceControlConnMissingConnInputs, SourceControlConnMissingLocalFolderInput, PleaseStartAgent, AskToSelectValidation, EnvironmentItemLoadError, MissingUnixCredential, ErrorConnectingToDataBase, ErrorClosingConnectionToDataBase, DbTableError, DbTableNameError, DbQueryError, DbConnSucceed, DbConnFailed, SuccessfullyConnectedToAgent, FailedToConnectAgent, SshCommandError, GoToUrlFailure, HookLinkEventError, AskToStartAgent, RestartAgent, MissingActionPropertiesEditor, AskToSelectItem, AskToSelectAction, ImportSeleniumScriptError, AskToSelectVariable, VariablesAssignError, SetCycleNumError, VariablesParentNotFound, CantStoreToVariable, AskToSelectSolutionFolder, SolutionLoadError, BeginWithNoSelectSolution, AddSupportValidationFailed, UploadSupportRequestSuccess, UploadSupportRequestFailure, FunctionReturnedError, ShowInfoMessage, LogoutSuccess, TestCompleted, CantFindObject, QcConnectSuccess, QcConnectFailure, ALMConnectFailureWithCurrSettings, ALMOperationFailed, QcLoginSuccess, ALMLoginFailed, ALMConnectFailure, QcNeedLogin, ErrorWhileExportingExecDetails, ExportedExecDetailsToALM, ExportItemToALMSucceed, ExportAllItemsToALMSucceed, ExportAllItemsToALMFailed, ExportQCNewTestSetSelectDiffFolder, TestSetExists, ErrorInTestsetImport, TestSetsImportedSuccessfully, TestCasesUpdatedSuccessfully, TestCasesUploadedSuccessfully, ASCFNotConnected, DeleteRepositoryItemAreYouSure, DeleteTreeFolderAreYouSure, RenameRepositoryItemAreYouSure, NoPathForCheckIn, SaveBusinessFlowChanges, UnknownParamInCommandLine, SetDriverConfigTypeNotHandled, DriverConfigUnknownDriverType, SetDriverConfigTypeFieldNotFound, ApplicationNotFoundInEnvConfig, UnknownConsoleCommand, DOSConsolemissingCMDFileName, ExecutionReportSent, CannontFindBusinessFlow, ResetBusinessFlowRunVariablesFailed, AgentNotFound, MissingNewAgentDetails, MissingNewTableDetails, InvalidTableDetails, MissingNewColumn, ChangingAgentDriverAlert, MissingNewDSDetails, DuplicateDSDetails, GingerKeyNameError, GingerKeyNameDuplicate, ConfirmToAddTreeItem, FailedToAddTreeItem, SureWantToDeleteAll, SureWantToDeleteSelectedItems, SureWantToDelete, NoItemToDelete, SelectItemToDelete, FailedToloadTheGrid, SureWantToContinue, BaseAPIWarning, ErrorReadingRepositoryItem, EnvNotFound, SelectItemToAdd, CannotAddGinger, ShortcutCreated, ShortcutCreationFailed, CannotRunShortcut, SolutionFileNotFound, PlugInFileNotFound, MissingAddSolutionInputs, SolutionAlreadyExist, AddSolutionSucceed, AddSolutionFailed, MobileConnectionFailed, MobileRefreshScreenShotFailed, MobileShowElementDetailsFailed, MobileActionWasAdded, RefreshTreeGroupFailed, FailedToDeleteRepoItem, RunsetNoGingerPresentForBusinessFlow, ExcelNoWorksheetSelected, ExcelBadWhereClause, RecommendNewVersion, DragDropOperationFailed, ActionIDNotFound, ActivityIDNotFound, ActionsDependenciesLoadFailed, ActivitiesDependenciesLoadFailed, SelectValidColumn, SelectValidRow, DependenciesMissingActions, DependenciesMissingVariables, DuplicateVariable, AskIfToGenerateAutoRunDescription, MissingApplicationPlatform, NoActivitiesGroupWasSelected, ActivitiesGroupActivitiesNotFound, PartOfActivitiesGroupActsNotFound, SureWantToDeleteGroup, ItemNameExistsInRepository, ItemExistsInRepository, ItemExternalExistsInRepository, ItemParentExistsInRepository, AskIfWantsToUpdateRepoItemInstances, AskIfWantsToChangeeRepoItem, GetRepositoryItemUsagesFailed, UpdateRepositoryItemUsagesSuccess, FailedToAddItemToSharedRepository, OfferToUploadAlsoTheActivityGroupToRepository, ConnectionCloseWarning, InvalidCharactersWarning, InvalidValueExpression, FolderExistsWithName, DownloadedSolutionFromSourceControl, SourceControlFileLockedByAnotherUser, SourceControlUpdateFailed, SourceControlCommitFailed, SourceControlChkInSucss, SourceControlChkInConflictHandledFailed, SourceControlGetLatestConflictHandledFailed, SourceControlChkInConflictHandled, SourceControlCheckInLockedByAnotherUser, SourceControlCheckInLockedByMe, SourceControlCheckInUnsavedFileChecked, FailedToUnlockFileDuringCheckIn, SourceControlChkInConfirmtion, SourceControlMissingSelectionToCheckIn, SourceControlResolveConflict, SureWantToDoRevert, SureWantToDoCheckIn, NoOptionalAgent, MissingActivityAppMapping, SettingsChangeRequireRestart, ChangesRequireRestart, UnsupportedFileFormat, WarnRegradingMissingVariablesUse, NotAllMissingVariablesWereAdded, UpdateApplicationNameChangeInSolution, ShareEnvAppWithAllEnvs, ShareEnvAppParamWithAllEnvs, CtrlSsaveEnvApp, CtrlSMissingItemToSave, FailedToSendEmail, FailedToExportBF, ReportTemplateNotFound, DriverNotSupportingWindowExplorer, AgentNotRunningAfterWaiting, FoundDuplicateAgentsInRunSet, StaticErrorMessage, StaticWarnMessage, StaticInfoMessage, ApplicationAgentNotMapped, ActivitiesGroupAlreadyMappedToTC, ExportItemToALMFailed, AskIfToSaveBFAfterExport, BusinessFlowAlreadyMappedToTC, AskIfSureWantToClose, WindowClosed, TargetWindowNotSelected, ChangingEnvironmentParameterValue, IFSaveChangesOfBF, AskIfToLoadExternalFields, WhetherToOpenSolution, AutomationTabExecResultsNotExists, FolderNamesAreTooLong, FolderSizeTooSmall, DefaultTemplateCantBeDeleted, FileNotExist, ExecutionsResultsProdIsNotOn, ExecutionsResultsNotExists, ExecutionsResultsToDelete, AllExecutionsResultsToDelete, FilterNotBeenSet, RetreivingAllElements, ClickElementAgain, CloseFilterPage, BusinessFlowNeedTargetApplication, HTMLReportAttachment, ImageSize, GherkinAskToSaveFeatureFile, GherkinScenariosGenerated, GherkinNotifyFeatureFileExists, GherkinNotifyFeatureFileSelectedFromTheSolution, GherkinNotifyBFIsNotExistForThisFeatureFile, GherkinFileNotFound, GherkinColumnNotExist, GherkinActivityNotFound, GherkinBusinessFlowNotCreated, GherkinFeatureFileImportedSuccessfully, GherkinFeatureFileImportOnlyFeatureFileAllowedErrorMessage, AskIfSureWantToDeLink, AnalyzerFoundIssues, AnalyzerSaveRunSet, AskIfSureWantToUndoChange, CurrentActionNotSaved, LoseChangesWarn, BFNotExistInDB, // Merged from GingerCore CopiedVariableSuccessfully, AskIfShareVaribalesInRunner, ShareVariableNotSelected, WarnOnDynamicActivities, QcConnectFailureRestAPI, ExportedExecDetailsToALMIsInProcess, RenameItemError, BusinessFlowUpdate, MissingExcelDetails, InvalidExcelDetails, InvalidDataSourceDetails, ExportFailed, ExportDetails, ParamExportMessage, MappedtoDataSourceError, CreateTableError, InvalidColumnName, DeleteDSFileError, InvalidDSPath, FailedToLoadPlugIn, RunsetBuinessFlowWasChanged, RunSetReloadhWarn, RefreshWholeSolution, GetModelItemUsagesFailed, RecoverItemsMissingSelectionToRecover, SourceControlItemAlreadyLocked, SoruceControlItemAlreadyUnlocked, SourceControlConflictResolveFailed, AskIfToCloseAgent, AskIfToDownloadPossibleValues, AskIfToDownloadPossibleValuesShortProcesss, SelectAndSaveCategoriesValues, FolderNotExistOrNotAvailible, FolderNameTextBoxIsEmpty, UserHaveNoWritePermission, MissingTargetPlatformForConversion, NoConvertibleActionsFound, NoConvertibleActionSelected, SuccessfulConversionDone, NoActivitySelectedForConversion, ActivitiesConversionFailed, FileExtensionNotSupported, NotifyFileSelectedFromTheSolution, FileImportedSuccessfully, CompilationErrorOccured, CompilationSucceed, Failedtosaveitems, SaveItemParentWarning, SaveAllItemsParentWarning, APIParametersListUpdated, APIMappedToActionIsMissing, NoAPIExistToMappedTo, CreateRunset, DeleteRunners, DeleteRunner, DeleteBusinessflow, DeleteBusinessflows, MissingErrorHandler, CantDeleteRunner, AllItemsSaved, APIModelAlreadyContainsReturnValues, InitializeBrowser, AskBeforeDefectProfileDeleting, MissedMandatotryFields, NoDefaultDefectProfileSelected, ALMDefectsWereOpened, AskALMDefectsOpening, WrongValueSelectedFromTheList, WrongNonNumberValueInserted, WrongDateValueInserted, NoDefectProfileCreated, IssuesInSelectedDefectProfile, VisualTestingFailedToDeleteOldBaselineImage, ApplitoolsLastExecutionResultsNotExists, ApplitoolsMissingChromeOrFirefoxBrowser, ParameterOptionalValues, FindAndRepalceFieldIsEmpty, FindAndReplaceListIsEmpty, FindAndReplaceNoItemsToRepalce, OracleDllIsMissing, ReportsTemplatesSaveWarn, POMWizardFailedToLearnElement, POMWizardReLearnWillDeleteAllElements, WizardCantMoveWhileInProcess, POMDriverIsBusy, FindAndReplaceViewRunSetNotSupported, WizardSureWantToCancel, POMSearchByGUIDFailed, POMElementSearchByGUIDFailed, NoRelevantAgentInRunningStatus, SolutionSaveWarning, InvalidIndexValue, FileOperationError, FolderOperationError, ObjectUnavailable, PatternNotHandled, LostConnection, AskToSelectBusinessflow, ScriptPaused, MissingFileLocation, ElementNotFound, TextNotFound, ProvideSearchString, NoTextOccurrence, JSExecutionFailed, FailedToInitiate, FailedToCreateRequestResponse, ActionNotImplemented, ValueIssue, MissingTargetApplication, ThreadError, ParsingError, SpecifyUniqueValue, ParameterAlreadyExists, DeleteNodesFromRequest, ParameterMerge, ParameterEdit, ParameterUpdate, ParameterDelete, SaveAll, SaveSelected, CopiedErrorInfo, RepositoryNameCantEmpty, ExcelProcessingError, EnterValidBusinessflow, DeleteItem, RefreshFolder, RefreshFailed, ReplaceAll, ItemSelection, DifferentItemType, CopyCutOperation, ObjectLoad, POMAgentIsNotRunning, POMNotOnThePageWarn, POMCannotDeleteAutoLearnedElement, ALMDefectsUserInOtaAPI, DuplicateRunsetName, AskIfToUndoChanges, AskIfToUndoItemChanges, FileAlreadyExistWarn, POMDeltaWizardReLearnWillEraseModification,WarnAddLegacyAction, WarnAddLegacyActionAndOfferNew, PluginDownloadInProgress, SaveRunsetChanges, LegacyActionsCleanup, MissingImplementationForPlatform } public static class UserMsgsPool { public static void LoadUserMsgsPool() { //Initialize the pool Reporter.UserMsgsPool = new Dictionary<eUserMsgKey, UserMsg>(); //Add user messages to the pool #region General Application Messages Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinNotifyFeatureFileExists, new UserMsg(eUserMsgType.ERROR, "Feature File Already Exists", "Feature File with the same name already exist - '{0}'." + Environment.NewLine + "Please select another Feature File to continue.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinNotifyFeatureFileSelectedFromTheSolution, new UserMsg(eUserMsgType.ERROR, "Feature File Already Exists", "Feature File - '{0}'." + Environment.NewLine + "Selected From The Solution folder hence its already exist and cannot be copy to the same place" + Environment.NewLine + "Please select another Feature File to continue.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinNotifyBFIsNotExistForThisFeatureFile, new UserMsg(eUserMsgType.ERROR, GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " Is Not Exists", GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " has to been generated for Feature File - '{0}'." + Environment.NewLine + Environment.NewLine + "Please create " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " from the Editor Page.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinFileNotFound, new UserMsg(eUserMsgType.ERROR, "Gherkin File Not Found", "Gherkin file was not found at the path: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinColumnNotExist, new UserMsg(eUserMsgType.WARN, "Column Not Exist", "Cant find value for: '{0}' Item/s. since column/s not exist in example table", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinActivityNotFound, new UserMsg(eUserMsgType.ERROR, "Activity Not Found", "Activity not found, Name: '{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinBusinessFlowNotCreated, new UserMsg(eUserMsgType.WARN, "Gherkin " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " Creation Failed", "The file did not passed Gherkin compilation hence the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " not created" + Environment.NewLine + "please correct the imported file and create the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " from Gherkin Page", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinFeatureFileImportedSuccessfully, new UserMsg(eUserMsgType.INFO, "Gherkin feature file imported successfully", "Gherkin feature file imported successfully", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinFeatureFileImportOnlyFeatureFileAllowedErrorMessage, new UserMsg(eUserMsgType.ERROR, "Gherkin feature file not valid", "Only Gherkin feature files can be imported", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinAskToSaveFeatureFile, new UserMsg(eUserMsgType.WARN, "Feature File Changes were made", "Do you want to Save the Feature File?" + Environment.NewLine + "WARNING: If you do not manually Save your Feature File, you may loose your work if you close out of Ginger.", eUserMsgOption.YesNoCancel, eUserMsgSelection.Yes)); Reporter.UserMsgsPool.Add(eUserMsgKey.GherkinScenariosGenerated, new UserMsg(eUserMsgType.INFO, "Scenarios generated", "{0} Scenarios generated successfully", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GeneralErrorOccured, new UserMsg(eUserMsgType.ERROR, "Error Occurred", "Application error occurred." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingImplementation, new UserMsg(eUserMsgType.WARN, "Missing Implementation", "The {0} functionality hasn't been implemented yet.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingImplementation2, new UserMsg(eUserMsgType.WARN, "Missing Implementation", "The functionality hasn't been implemented yet.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingImplementationForPlatform, new UserMsg(eUserMsgType.WARN, "Missing Implementation", "Functionality hasn't been implemented yet for {0} platform.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ApplicationInitError, new UserMsg(eUserMsgType.ERROR, "Application Initialization Error", "Error occurred during application initialization." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.PageLoadError, new UserMsg(eUserMsgType.ERROR, "Page Load Error", "Failed to load the page '{0}'." + Environment.NewLine + "Error Details: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.UserProfileLoadError, new UserMsg(eUserMsgType.ERROR, "User Profile Load Error", "Error occurred during user profile loading." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ItemToSaveWasNotSelected, new UserMsg(eUserMsgType.WARN, "Save", "Item to save was not selected.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.RecommendNewVersion, new UserMsg(eUserMsgType.WARN, "Upgrade required", "You are not using the latest version of Ginger. Please go to http://cmitechint1srv:8089/ to get the latest build.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ToSaveChanges, new UserMsg(eUserMsgType.QUESTION, "Save Changes?", "Do you want to save changes?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.UnsupportedFileFormat, new UserMsg(eUserMsgType.ERROR, "Save Changes", "File format not supported.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CtrlSsaveEnvApp, new UserMsg(eUserMsgType.WARN, "Save Environment", "Please select the environment to save.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CtrlSMissingItemToSave, new UserMsg(eUserMsgType.WARN, "Missing Item to Save", "Please select individual item to save or use menu toolbar to save all the items.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.StaticErrorMessage, new UserMsg(eUserMsgType.ERROR, "Error", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.StaticWarnMessage, new UserMsg(eUserMsgType.WARN, "Warning", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.StaticInfoMessage, new UserMsg(eUserMsgType.INFO, "Info", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfSureWantToClose, new UserMsg(eUserMsgType.QUESTION, "Close Ginger", "Are you sure you want to close Ginger?" + Environment.NewLine + Environment.NewLine + "Notice: Un-saved changes won't be saved.", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.BusinessFlowNeedTargetApplication, new UserMsg(eUserMsgType.WARN, "Target Application Not Selected", "Target Application Not Selected! Please Select at least one Target Application", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfSureWantToUndoChange, new UserMsg(eUserMsgType.WARN, "Undo Changes", "Are you sure you want to undo all changes?", eUserMsgOption.YesNo, eUserMsgSelection.No)); #endregion General Application Messages #region Settings Reporter.UserMsgsPool.Add(eUserMsgKey.SettingsChangeRequireRestart, new UserMsg(eUserMsgType.INFO, "Settings Change", "For the settings change to take affect you must '{0}' restart Ginger.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ChangesRequireRestart, new UserMsg(eUserMsgType.INFO, "Restart to apply", "The changes will be applied only after save and restart Ginger", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Settings #region Repository Reporter.UserMsgsPool.Add(eUserMsgKey.ItemNameExistsInRepository, new UserMsg(eUserMsgType.WARN, "Add Item to Repository", "Item with the name '{0}' already exist in the repository." + Environment.NewLine + Environment.NewLine + "Please change the item name to be unique and try to upload it again.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ItemExistsInRepository, new UserMsg(eUserMsgType.WARN, "Add Item to Repository", "The item '{0}' already exist in the repository (item name in repository is '{1}')." + Environment.NewLine + Environment.NewLine + "Do you want to continue and overwrite it?" + Environment.NewLine + Environment.NewLine + "Note: If you select 'Yes', backup of the existing item will be saved into 'PreVersions' folder.", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.ItemExternalExistsInRepository, new UserMsg(eUserMsgType.WARN, "Add Item to Repository", "The item '{0}' is mapped to the same external item like the repository item '{1}'." + Environment.NewLine + Environment.NewLine + "Do you want to continue and overwrite the existing repository item?" + Environment.NewLine + Environment.NewLine + "Note: If you select 'Yes', backup of the existing repository item will be saved into 'PreVersions' folder.", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.ItemParentExistsInRepository, new UserMsg(eUserMsgType.WARN, "Add Item to Repository", "The item '{0}' source is from the repository item '{1}'." + Environment.NewLine + Environment.NewLine + "Do you want to overwrite the source repository item?" + Environment.NewLine + Environment.NewLine + "Note:" + Environment.NewLine + "If you select 'No', the item will be added as a new item to the repository." + Environment.NewLine + "If you select 'Yes', backup of the existing repository item will be saved into 'PreVersions' folder.", eUserMsgOption.YesNoCancel, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToAddItemToSharedRepository, new UserMsg(eUserMsgType.ERROR, "Add Item to Repository", "Failed to add the item '{0}' to shared repository." + Environment.NewLine + Environment.NewLine + "Error Details: {1}.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfWantsToUpdateRepoItemInstances, new UserMsg(eUserMsgType.WARN, "Update Repository Item Usages", "The item '{0}' has {1} instances." + Environment.NewLine + Environment.NewLine + "Do you want to review them and select which one to get updated as well?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfWantsToChangeeRepoItem, new UserMsg(eUserMsgType.WARN, "Change Repository Item", "The item '{0}' is been used in {1} places." + Environment.NewLine + Environment.NewLine + "Are you sure you want to {2} it?" + Environment.NewLine + Environment.NewLine + "Note: Anyway the changes won't affect the linked instances of this item", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.GetRepositoryItemUsagesFailed, new UserMsg(eUserMsgType.ERROR, "Repository Item Usages", "Failed to get the '{0}' item usages." + Environment.NewLine + Environment.NewLine + "Error Details: {1}.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.UpdateRepositoryItemUsagesSuccess, new UserMsg(eUserMsgType.INFO, "Update Repository Item Usages", "Finished to update the repository items usages." + Environment.NewLine + Environment.NewLine + "Note: Updates were not saved yet.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfSureWantToDeLink, new UserMsg(eUserMsgType.WARN, "De-Link to Shared Repository", "Are you sure you want to de-link the item from it Shared Repository source item?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.OfferToUploadAlsoTheActivityGroupToRepository, new UserMsg(eUserMsgType.QUESTION, "Add the " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " to Repository", "The " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '{0}' is part of the " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " '{1}', do you want to add the " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " to the shared repository as well?" + System.Environment.NewLine + System.Environment.NewLine + "Note: If you select Yes, only the " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " will be added to the repository and not all of it " + GingerDicser.GetTermResValue(eTermResKey.Activities) + ".", eUserMsgOption.YesNo, eUserMsgSelection.No)); #endregion Repository #region Analyzer Reporter.UserMsgsPool.Add(eUserMsgKey.AnalyzerFoundIssues, new UserMsg(eUserMsgType.WARN, "Issues Detected By Analyzer", "Critical/High Issues were detected, please handle them before execution.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AnalyzerSaveRunSet, new UserMsg(eUserMsgType.WARN, "Issues Detected By Analyzer", "Please save the " + GingerDicser.GetTermResValue(eTermResKey.RunSet) + " first", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Analyzer #region Registry Values Check Messages Reporter.UserMsgsPool.Add(eUserMsgKey.RegistryValuesCheckFailed, new UserMsg(eUserMsgType.ERROR, "Run Registry Values Check", "Failed to check if all needed registry values exist.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AddRegistryValue, new UserMsg(eUserMsgType.QUESTION, "Missing Registry Value", "The required registry value for the key: '{0}' is missing or wrong. Do you want to add/fix it?", eUserMsgOption.YesNo, eUserMsgSelection.Yes)); Reporter.UserMsgsPool.Add(eUserMsgKey.AddRegistryValueSucceed, new UserMsg(eUserMsgType.INFO, "Add Registry Value", "Registry value added successfully for the key: '{0}'." + Environment.NewLine + "Please restart the application.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AddRegistryValueFailed, new UserMsg(eUserMsgType.ERROR, "Add Registry Value", "Registry value add failed for the key: '{0}'." + Environment.NewLine + "Please restart the application as administrator and try again.", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Registry Values Check Messages #region SourceControl Messages Reporter.UserMsgsPool.Add(eUserMsgKey.NoItemWasSelected, new UserMsg(eUserMsgType.WARN, "No item was selected", "Please select an item to proceed.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskToAddCheckInComment, new UserMsg(eUserMsgType.WARN, "Check-In Changes", "Please enter check-in comments.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToGetProjectsListFromSVN, new UserMsg(eUserMsgType.ERROR, "Source Control Error", "Failed to get the solutions list from the source control." + Environment.NewLine + "Error Details: '{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskToSelectSolution, new UserMsg(eUserMsgType.WARN, "Select Solution", "Please select solution.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlFileLockedByAnotherUser, new UserMsg(eUserMsgType.WARN, "Source Control File Locked", "The file '{0}' was locked by: {1} " + Environment.NewLine + "Locked comment {2}." + Environment.NewLine + Environment.NewLine + " Are you sure you want to unlock the file?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.DownloadedSolutionFromSourceControl, new UserMsg(eUserMsgType.INFO, "Download Solution", "The solution '{0}' was downloaded successfully." + Environment.NewLine + "Do you want to open the downloaded Solution?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.UpdateToRevision, new UserMsg(eUserMsgType.INFO, "Update Solution", "The solution was updated successfully to revision: {0}.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CommitedToRevision, new UserMsg(eUserMsgType.INFO, "Commit Solution", "The changes were committed successfully, Revision: {0}.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GitUpdateState, new UserMsg(eUserMsgType.INFO, "Update Solution", "The solution was updated successfully, Update status: {0}.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoPathForCheckIn, new UserMsg(eUserMsgType.ERROR, "No Path for Check-In", "Missing Path", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlConnFaild, new UserMsg(eUserMsgType.ERROR, "Source Control Connection", "Failed to establish connection to the source control." + Environment.NewLine + "Error Details: '{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlRemoteCannotBeAccessed, new UserMsg(eUserMsgType.ERROR, "Source Control Connection", "Failed to establish connection to the source control." + Environment.NewLine + "The remote repository cannot be accessed, please check your internet connection and your proxy configurations" + Environment.NewLine + Environment.NewLine + "Error details: '{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlUnlockFaild, new UserMsg(eUserMsgType.ERROR, "Source Control Unlock", "Failed to unlock remote file, File locked by different user." + Environment.NewLine + "Locked by: '{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlConnSucss, new UserMsg(eUserMsgType.INFO, "Source Control Connection", "Succeed to establish connection to the source control", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlLockSucss, new UserMsg(eUserMsgType.INFO, "Source Control Lock", "Succeed to Lock the file in the source control", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlUnlockSucss, new UserMsg(eUserMsgType.INFO, "Source Control Unlock", "Succeed to unlock the file in the source control", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlConnMissingConnInputs, new UserMsg(eUserMsgType.WARN, "Source Control Connection", "Missing connection inputs, please set the source control URL, user name and password.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlConnMissingLocalFolderInput, new UserMsg(eUserMsgType.WARN, "Download Solution", "Missing local folder input, please select local folder to download the solution into.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlUpdateFailed, new UserMsg(eUserMsgType.ERROR, "Update Solution", "Failed to update the solution from source control." + Environment.NewLine + "Error Details: '{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlCommitFailed, new UserMsg(eUserMsgType.ERROR, "Commit Solution", "Failed to commit the solution from source control." + Environment.NewLine + "Error Details: '{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlChkInSucss, new UserMsg(eUserMsgType.QUESTION, "Check-In Changes", "Check-in process ended successfully." + Environment.NewLine + Environment.NewLine + "Do you want to do another check-in?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlChkInConflictHandled, new UserMsg(eUserMsgType.QUESTION, "Check-In Results", "The check in process ended, please notice that conflict was identified during the process and may additional check in will be needed for pushing the conflict items." + Environment.NewLine + Environment.NewLine + "Do you want to do another check-in?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlChkInConflictHandledFailed, new UserMsg(eUserMsgType.WARN, "Check-In Results", "Check in process ended with unhandled conflict please notice that you must handled them prior to the next check in of those items", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlGetLatestConflictHandledFailed, new UserMsg(eUserMsgType.WARN, "Get Latest Results", "Get latest process encountered conflicts which must be resolved for successful Solution loading", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlCheckInLockedByAnotherUser, new UserMsg(eUserMsgType.WARN, "Locked Item Check-In", "The item: '{0}'" + Environment.NewLine + "is locked by the user: '{1}'" + Environment.NewLine + "The locking comment is: '{2}' ." + Environment.NewLine + Environment.NewLine + "Do you want to unlock the item and proceed with check in process?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlCheckInLockedByMe, new UserMsg(eUserMsgType.WARN, "Locked Item Check-In", "The item: '{0}'" + Environment.NewLine + "is locked by you please noticed that during check in the lock will need to be removed please confirm to continue", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlCheckInUnsavedFileChecked, new UserMsg(eUserMsgType.QUESTION, "Unsaved Item Checkin", "The item: '{0}' contains unsaved changes which must be saved prior to the check in process." + Environment.NewLine + Environment.NewLine + "Do you want to save the item and proceed with check in process?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToUnlockFileDuringCheckIn, new UserMsg(eUserMsgType.QUESTION, "Locked Item Check-In Failure", "The item: '{0}' unlock operation failed on the URL: '{1}'." + Environment.NewLine + Environment.NewLine + "Do you want to proceed with the check in process for rest of the items?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlChkInConfirmtion, new UserMsg(eUserMsgType.QUESTION, "Check-In Changes", "Checking in changes will effect all project users, are you sure you want to continue and check in those {0} changes?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlMissingSelectionToCheckIn, new UserMsg(eUserMsgType.WARN, "Check-In Changes", "Please select items to check-in.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlResolveConflict, new UserMsg(eUserMsgType.QUESTION, "Source Control Conflicts", "Source control conflicts has been identified for the path: '{0}'." + Environment.NewLine + "You probably won't be able to use the item which in the path till conflicts will be resolved." + Environment.NewLine + Environment.NewLine + "Do you want to automatically resolve the conflicts and keep your local changes for all conflicts?" + Environment.NewLine + Environment.NewLine + "Select 'No' for accepting server updates for all conflicts or select 'Cancel' for canceling the conflicts handling.", eUserMsgOption.YesNoCancel, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SureWantToDoRevert, new UserMsg(eUserMsgType.QUESTION, "Undo Changes", "Are you sure you want to revert changes?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SureWantToDoCheckIn, new UserMsg(eUserMsgType.QUESTION, "Check-In Changes", "Are you sure you want to check-in changes?", eUserMsgOption.YesNo, eUserMsgSelection.No)); #endregion SourceControl Messages #region Validation Messages Reporter.UserMsgsPool.Add(eUserMsgKey.PleaseStartAgent, new UserMsg(eUserMsgType.WARN, "Start Agent", "Please start agent in order to run validation.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskToSelectValidation, new UserMsg(eUserMsgType.WARN, "Select Validation", "Please select validation to edit.", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Validation Messages #region DataBase Messages Reporter.UserMsgsPool.Add(eUserMsgKey.ErrorConnectingToDataBase, new UserMsg(eUserMsgType.ERROR, "Cannot connect to database", "DB Connection error." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ErrorClosingConnectionToDataBase, new UserMsg(eUserMsgType.ERROR, "Error in closing connection to database", "DB Close Connection error" + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DbTableNameError, new UserMsg(eUserMsgType.ERROR, "Invalid DB Table Name", "Table with the name '{0}' already exist in the Database. Please try another name.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DbTableError, new UserMsg(eUserMsgType.ERROR, "DB Table Error", "Error occurred while trying to get the {0}." + Environment.NewLine + "Error Details: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DbQueryError, new UserMsg(eUserMsgType.ERROR, "DB Query Error", "The DB Query returned error, please double check the table name and field name." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DbConnFailed, new UserMsg(eUserMsgType.ERROR, "DB Connection Status", "Connect to the DB failed.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DbConnSucceed, new UserMsg(eUserMsgType.INFO, "DB Connection Status", "Connect to the DB succeeded.", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion DataBase Messages #region Environment Messages Reporter.UserMsgsPool.Add(eUserMsgKey.MissingUnixCredential, new UserMsg(eUserMsgType.ERROR, "Unix credential is missing or invalid", "Unix credential is missing or invalid in Environment settings, please open Environment tab to check.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.EnvironmentItemLoadError, new UserMsg(eUserMsgType.ERROR, "Environment Item Load Error", "Failed to load the {0}." + Environment.NewLine + "Error Details: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ShareEnvAppWithAllEnvs, new UserMsg(eUserMsgType.INFO, "Share Environment Applications", "The selected application/s were added to the other solution environments." + Environment.NewLine + Environment.NewLine + "Note: The changes were not saved, please perform save for all changed environments.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ShareEnvAppParamWithAllEnvs, new UserMsg(eUserMsgType.INFO, "Share Environment Application Parameter", "The selected parameter/s were added to the other solution environments matching applications." + Environment.NewLine + Environment.NewLine + "Note: The changes were not saved, please perform save for all changed environments.", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Environment Messages #region Agents/Drivers Messages Reporter.UserMsgsPool.Add(eUserMsgKey.SuccessfullyConnectedToAgent, new UserMsg(eUserMsgType.INFO, "Connect Agent Success", "Agent connection successful!", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToConnectAgent, new UserMsg(eUserMsgType.ERROR, "Connect to Agent", "Failed to connect to the {0} agent." + Environment.NewLine + "Error Details: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SshCommandError, new UserMsg(eUserMsgType.ERROR, "Ssh Command Error", "The Ssh Run Command returns error, please double check the connection info and credentials." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GoToUrlFailure, new UserMsg(eUserMsgType.ERROR, "Go To URL Error", "Failed to go to the URL: '{0}'." + Environment.NewLine + "Error Details: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.HookLinkEventError, new UserMsg(eUserMsgType.ERROR, "Hook Link Event Error", "The link type is unknown.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskToStartAgent, new UserMsg(eUserMsgType.WARN, "Missing Agent", "Please start/select agent.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.RestartAgent, new UserMsg(eUserMsgType.WARN, "Agent Restart needed", "Please restart agent.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ASCFNotConnected, new UserMsg(eUserMsgType.ERROR, "Not Connected to ASCF", "Please Connect first.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SetDriverConfigTypeNotHandled, new UserMsg(eUserMsgType.ERROR, "Set Driver configuration", "Unknown Type {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DriverConfigUnknownDriverType, new UserMsg(eUserMsgType.ERROR, "Driver Configuration", "Unknown Driver Type {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SetDriverConfigTypeFieldNotFound, new UserMsg(eUserMsgType.ERROR, "Driver Configuration", "Unknown Driver Parameter {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.UnknownConsoleCommand, new UserMsg(eUserMsgType.ERROR, "Unknown Console Command", "Command {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DOSConsolemissingCMDFileName, new UserMsg(eUserMsgType.ERROR, "DOS Console Driver Error", "DOSConsolemissingCMDFileName", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CannontFindBusinessFlow, new UserMsg(eUserMsgType.ERROR, "Cannot Find " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow), "Missing flow in solution {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AgentNotFound, new UserMsg(eUserMsgType.ERROR, "Cannot Find Agent", "Missing Agent from Run Config- {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingNewAgentDetails, new UserMsg(eUserMsgType.WARN, "Missing Agent Details", "The new Agent {0} is missing.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingNewTableDetails, new UserMsg(eUserMsgType.ERROR, "Missing Table Details", "The new Table {0} is missing.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.InvalidTableDetails, new UserMsg(eUserMsgType.ERROR, "InValid Table Details", "The Table Name provided is Invalid. It cannot contain spaces", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingNewDSDetails, new UserMsg(eUserMsgType.WARN, "Missing Data Source Details", "The new Data Source {0} is missing.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DuplicateDSDetails, new UserMsg(eUserMsgType.ERROR, "Duplicate DataSource Details", "The Data Source with the File Path {0} already Exist. Please use another File Path", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GingerKeyNameError, new UserMsg(eUserMsgType.ERROR, "InValid Ginger Key Name", "The Ginger Key Name cannot be Duplicate or NULL. Please fix before continuing.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GingerKeyNameDuplicate, new UserMsg(eUserMsgType.ERROR, "InValid Ginger Key Name", "The Ginger Key Name cannot be Duplicated. Please change the Key Name : {0} in Table : {1}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingNewColumn, new UserMsg(eUserMsgType.WARN, "Missing Column Details", "The new Column {0} is missing.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingApplicationPlatform, new UserMsg(eUserMsgType.WARN, "Missing Application Platform Info", "The default Application Platform Info is missing, please go to Solution level to add at least one Target Application.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ConnectionCloseWarning, new UserMsg(eUserMsgType.WARN, "Connection Close", "Closing this window will cause the connection to {0} to be closed, to continue and close?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.ChangingAgentDriverAlert, new UserMsg(eUserMsgType.WARN, "Changing Agent Driver", "Changing the Agent driver type will cause all driver configurations to be reset, to continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.InvalidCharactersWarning, new UserMsg(eUserMsgType.WARN, "Invalid Details", "Name can't contain any of the following characters: " + Environment.NewLine + " /, \\, *, :, ?, \", <, >, |", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.InvalidValueExpression, new UserMsg(eUserMsgType.WARN, "Invalid Value Expression", "{0} - Value Expression has some Error. Do you want to continue?", eUserMsgOption.YesNo, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoOptionalAgent, new UserMsg(eUserMsgType.WARN, "No Optional Agent", "No optional Agent was found." + Environment.NewLine + "Please configure new Agent under the Solution to be used for this application.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DriverNotSupportingWindowExplorer, new UserMsg(eUserMsgType.WARN, "Open Window Explorer", "The driver '{0}' is not supporting the Window Explorer yet.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AgentNotRunningAfterWaiting, new UserMsg(eUserMsgType.WARN, "Running Agent", "The Agent '{0}' failed to start running after {1} seconds.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ApplicationAgentNotMapped, new UserMsg(eUserMsgType.WARN, "Agent Not Mapped to Target Application", "The Agent Mapping for Target Application '{0}' , Please map Agent.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.WindowClosed, new UserMsg(eUserMsgType.WARN, "Invalid target window", "Target window is either closed or no longer available. \n\n Please Add switch Window action by selecting correct target window on Window Explorer", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.TargetWindowNotSelected, new UserMsg(eUserMsgType.WARN, "Target Window not Selected", "Please choose the target window from available list", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ChangingEnvironmentParameterValue, new UserMsg(eUserMsgType.WARN, "Changing Environment Variable Name", "Changing the Environment variable name will cause rename this environment variable name in every " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ", do you want to continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SaveLocalChanges, new UserMsg(eUserMsgType.QUESTION, "Save Local Changes?", "Your Local Changes will be saved. Do you want to Continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.LooseLocalChanges, new UserMsg(eUserMsgType.WARN, "Loose Local Changes?", "Your Local Changes will be Lost. Do you want to Continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.IFSaveChangesOfBF, new UserMsg(eUserMsgType.WARN, "Save Current" + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " Before Change?", "Do you want to save the changes made in the '{0}' " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + "?", eUserMsgOption.YesNo, eUserMsgSelection.No)); #endregion Agents/Drivers Messages #region Actions Messages Reporter.UserMsgsPool.Add(eUserMsgKey.MissingActionPropertiesEditor, new UserMsg(eUserMsgType.ERROR, "Action Properties Editor", "No Action properties Editor yet for '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskToSelectItem, new UserMsg(eUserMsgType.WARN, "Select Item", "Please select item.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskToSelectAction, new UserMsg(eUserMsgType.WARN, "Select Action", "Please select action.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ImportSeleniumScriptError, new UserMsg(eUserMsgType.ERROR, "Import Selenium Script Error", "Error occurred while trying to import Selenium Script, please make sure the html file is a Selenium script generated by Selenium IDE.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.WarnAddLegacyAction, new UserMsg(eUserMsgType.WARN, "Legacy Action Warning", "This Action is part of the Legacy Actions which will be deprecated soon and not recommended to be used anymore." + Environment.NewLine + "Do you still interested adding it?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.WarnAddLegacyActionAndOfferNew, new UserMsg(eUserMsgType.WARN, "Legacy Action Warning", "This Action is part of the Legacy Actions which will be deprecated soon and not recommended to be used anymore." + Environment.NewLine + "Do you prefer to add the replacement Action ({0}) for it?", eUserMsgOption.YesNoCancel, eUserMsgSelection.Yes)); #endregion Actions Messages #region Runset Messages Reporter.UserMsgsPool.Add(eUserMsgKey.RunsetNoGingerPresentForBusinessFlow, new UserMsg(eUserMsgType.WARN, "No Ginger in " + GingerDicser.GetTermResValue(eTermResKey.RunSet), "Please add at least one Ginger to your " + GingerDicser.GetTermResValue(eTermResKey.RunSet) + " before choosing a " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ".", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ResetBusinessFlowRunVariablesFailed, new UserMsg(eUserMsgType.ERROR, GingerDicser.GetTermResValue(eTermResKey.Variables) + " Reset Failed", "Failed to reset the " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " to original configurations." + System.Environment.NewLine + "Error Details: {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfToGenerateAutoRunDescription, new UserMsg(eUserMsgType.QUESTION, "Automatic Description Creation", "Do you want to automatically populate the Run Description?", eUserMsgOption.YesNo, eUserMsgSelection.No)); #endregion Runset Messages #region Excel Messages Reporter.UserMsgsPool.Add(eUserMsgKey.ExcelNoWorksheetSelected, new UserMsg(eUserMsgType.WARN, "Missing worksheet", "Please select a worksheet", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExcelBadWhereClause, new UserMsg(eUserMsgType.WARN, "Problem with WHERE clause", "Please check your WHERE clause. Do all column names exist and are they spelled correctly?", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Excel Messages #region Variables Messages Reporter.UserMsgsPool.Add(eUserMsgKey.AskToSelectVariable, new UserMsg(eUserMsgType.WARN, "Select " + GingerDicser.GetTermResValue(eTermResKey.Variable), "Please select " + GingerDicser.GetTermResValue(eTermResKey.Variable) + ".", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.VariablesAssignError, new UserMsg(eUserMsgType.ERROR, GingerDicser.GetTermResValue(eTermResKey.Variables) + " Assign Error", "Failed to assign " + GingerDicser.GetTermResValue(eTermResKey.Variables) + "." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SetCycleNumError, new UserMsg(eUserMsgType.ERROR, "Set Cycle Number Error", "Failed to set the cycle number." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.VariablesParentNotFound, new UserMsg(eUserMsgType.ERROR, GingerDicser.GetTermResValue(eTermResKey.Variables) + " Parent Error", "Failed to find the " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " parent.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CantStoreToVariable, new UserMsg(eUserMsgType.ERROR, "Store to " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " Failed", "Cannot Store to " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " '{0}'- " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " not found", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.WarnRegradingMissingVariablesUse, new UserMsg(eUserMsgType.WARN, "Unassociated " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " been Used in " + GingerDicser.GetTermResValue(eTermResKey.Activity), GingerDicser.GetTermResValue(eTermResKey.Variables) + " which are not part of the '{0}' " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " list are been used in it." + Environment.NewLine + "For the " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " to work as a standalone you will need to add those " + GingerDicser.GetTermResValue(eTermResKey.Variables, suffixString: ".") + Environment.NewLine + Environment.NewLine + "Missing " + GingerDicser.GetTermResValue(eTermResKey.Variables, suffixString: ":") + Environment.NewLine + "{1}" + Environment.NewLine + Environment.NewLine + "Do you want to automatically add the missing " + GingerDicser.GetTermResValue(eTermResKey.Variables, suffixString: "?") + Environment.NewLine + "Note: Clicking 'No' will cancel the " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " Upload.", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.NotAllMissingVariablesWereAdded, new UserMsg(eUserMsgType.WARN, "Unassociated " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " been Used in " + GingerDicser.GetTermResValue(eTermResKey.Activity), "Failed to find and add the following missing " + GingerDicser.GetTermResValue(eTermResKey.Variables, suffixString: ":") + Environment.NewLine + "{0}" + Environment.NewLine + Environment.NewLine + "Please add those " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " manually for allowing the " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " Upload.", eUserMsgOption.OK, eUserMsgSelection.No)); #endregion Variables Messages #region Solution Messages Reporter.UserMsgsPool.Add(eUserMsgKey.BeginWithNoSelectSolution, new UserMsg(eUserMsgType.INFO, "No solution is selected", "You have not selected any existing solution, please open an existing one or create a new solution by pressing the New button.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskToSelectSolutionFolder, new UserMsg(eUserMsgType.WARN, "Missing Folder Selection", "Please select the folder you want to perform the action on.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteRepositoryItemAreYouSure, new UserMsg(eUserMsgType.WARN, "Delete", "Are you sure you want to delete '{0}' item?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteTreeFolderAreYouSure, new UserMsg(eUserMsgType.WARN, "Delete Folder", "Are you sure you want to delete the '{0}' folder and all of it content?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.RenameRepositoryItemAreYouSure, new UserMsg(eUserMsgType.WARN, "Rename", "Are you sure you want to rename '{0}'?", eUserMsgOption.YesNoCancel, eUserMsgSelection.Yes)); Reporter.UserMsgsPool.Add(eUserMsgKey.SaveBusinessFlowChanges, new UserMsg(eUserMsgType.QUESTION, "Save Changes", "Save Changes to - {0}", eUserMsgOption.YesNoCancel, eUserMsgSelection.Yes)); Reporter.UserMsgsPool.Add(eUserMsgKey.SolutionLoadError, new UserMsg(eUserMsgType.ERROR, "Solution Load Error", "Failed to load the solution." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingAddSolutionInputs, new UserMsg(eUserMsgType.WARN, "Add Solution", "Missing solution inputs, please set the solution name, folder and main application details.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SolutionAlreadyExist, new UserMsg(eUserMsgType.WARN, "Add Solution", "The solution already exist, please select different name/folder.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AddSolutionSucceed, new UserMsg(eUserMsgType.INFO, "Add Solution", "The solution was created and loaded successfully.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AddSolutionFailed, new UserMsg(eUserMsgType.ERROR, "Add Solution", "Failed to create the new solution. " + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.RefreshTreeGroupFailed, new UserMsg(eUserMsgType.ERROR, "Refresh", "Failed to perform the refresh operation." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToDeleteRepoItem, new UserMsg(eUserMsgType.ERROR, "Delete", "Failed to perform the delete operation." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FolderExistsWithName, new UserMsg(eUserMsgType.WARN, "Folder Creation Failed", "Folder with same name already exists. Please choose a different name for the folder.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.UpdateApplicationNameChangeInSolution, new UserMsg(eUserMsgType.WARN, "Target Application Name Change", "Do you want to automatically update the Target Application name in all Solution items?" + Environment.NewLine + Environment.NewLine + "Note: If you choose 'Yes', changes won't be saved, for saving them please click 'SaveAll'", eUserMsgOption.YesNo, eUserMsgSelection.Yes)); Reporter.UserMsgsPool.Add(eUserMsgKey.SaveRunsetChanges, new UserMsg(eUserMsgType.QUESTION, "Save Changes", "There are unsaved changes in runset, Do you want to save it?", eUserMsgOption.YesNo, eUserMsgSelection.No)); #endregion Solution Messages #region Activities Reporter.UserMsgsPool.Add(eUserMsgKey.ActionsDependenciesLoadFailed, new UserMsg(eUserMsgType.ERROR, "Actions-" + GingerDicser.GetTermResValue(eTermResKey.Variables) + " Dependencies Load Failed", "Failed to load the Actions-" + GingerDicser.GetTermResValue(eTermResKey.Variables) + " dependencies data." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ActivitiesDependenciesLoadFailed, new UserMsg(eUserMsgType.ERROR, GingerDicser.GetTermResValue(eTermResKey.Activities) + "-" + GingerDicser.GetTermResValue(eTermResKey.Variables) + " Dependencies Load Failed", "Failed to load the " + GingerDicser.GetTermResValue(eTermResKey.Activities) + "-" + GingerDicser.GetTermResValue(eTermResKey.Variables) + " dependencies data." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DependenciesMissingActions, new UserMsg(eUserMsgType.INFO, "Missing Actions", "Actions not found." + System.Environment.NewLine + "Please add Actions to the " + GingerDicser.GetTermResValue(eTermResKey.Activity) + ".", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DependenciesMissingVariables, new UserMsg(eUserMsgType.INFO, "Missing " + GingerDicser.GetTermResValue(eTermResKey.Variables), GingerDicser.GetTermResValue(eTermResKey.Variables) + " not found." + System.Environment.NewLine + "Please add " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " from type 'Selection List' to the " + GingerDicser.GetTermResValue(eTermResKey.Activity) + ".", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DuplicateVariable, new UserMsg(eUserMsgType.WARN, "Duplicated " + GingerDicser.GetTermResValue(eTermResKey.Variable), "The " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " name '{0}' and value '{1}' exist more than once." + System.Environment.NewLine + "Please make sure only one instance exist in order to set the " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " dependencies.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingActivityAppMapping, new UserMsg(eUserMsgType.WARN, "Missing " + GingerDicser.GetTermResValue(eTermResKey.Activity) + "-Application Mapping", "Target Application was not mapped to the " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " so the required Actions platform is unknown." + System.Environment.NewLine + System.Environment.NewLine + "Map Target Application to the Activity by double clicking the " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " record and select the application you want to test using it.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.LegacyActionsCleanup, new UserMsg(eUserMsgType.INFO, "Legacy Actions Cleanup", "Legacy Actions cleanup was ended." + Environment.NewLine + Environment.NewLine + "Cleanup Statistics:" + Environment.NewLine + "Number of Processed " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlows) + ": {0}" + Environment.NewLine + "Number of Deleted " + GingerDicser.GetTermResValue(eTermResKey.Activities) + ": {1}" + Environment.NewLine + "Number of Deleted Actions: {2}", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Activities #region Support Messages Reporter.UserMsgsPool.Add(eUserMsgKey.AddSupportValidationFailed, new UserMsg(eUserMsgType.WARN, "Add Support Request Validation Error", "Add support request validation failed." + Environment.NewLine + "Failure Reason:" + Environment.NewLine + "'{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.UploadSupportRequestSuccess, new UserMsg(eUserMsgType.INFO, "Upload Support Request", "Upload was completed successfully.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.UploadSupportRequestFailure, new UserMsg(eUserMsgType.ERROR, "Upload Support Request", "Failed to complete the upload." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Support Messages #region SharedFunctions Messages Reporter.UserMsgsPool.Add(eUserMsgKey.FunctionReturnedError, new UserMsg(eUserMsgType.ERROR, "Error Occurred", "The {0} returns error. please check the provided details." + Environment.NewLine + "Error Details: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ShowInfoMessage, new UserMsg(eUserMsgType.INFO, "Message", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion SharedFunctions Messages #region CustomeFunctions Messages Reporter.UserMsgsPool.Add(eUserMsgKey.LogoutSuccess, new UserMsg(eUserMsgType.INFO, "Logout", "Logout completed successfully- {0}.", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion CustomeFunctions Messages #region ALM Reporter.UserMsgsPool.Add(eUserMsgKey.QcConnectSuccess, new UserMsg(eUserMsgType.INFO, "QC/ALM Connection", "QC/ALM connection successful!", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.QcConnectFailure, new UserMsg(eUserMsgType.WARN, "QC/ALM Connection Failed", "QC/ALM connection failed." + System.Environment.NewLine + "Please make sure that the credentials you use are correct and that QC/ALM Client is registered on your machine." + System.Environment.NewLine + System.Environment.NewLine + "For registering QC/ALM Client- please follow below steps:" + System.Environment.NewLine + "1. Launch Internet Explorer as Administrator" + System.Environment.NewLine + "2. Go to http://<QCURL>/qcbin" + System.Environment.NewLine + "3. Click on 'Add-Ins Page' link" + System.Environment.NewLine + "4. In next page, click on 'HP ALM Client Registration'" + System.Environment.NewLine + "5. In next page click on 'Register HP ALM Client'" + System.Environment.NewLine + "6. Restart Ginger and try to reconnect", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ALMConnectFailureWithCurrSettings, new UserMsg(eUserMsgType.WARN, "ALM Connection Failed", "ALM Connection Failed, Please make sure credentials are correct.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ALMConnectFailure, new UserMsg(eUserMsgType.WARN, "ALM Connection Failed", "ALM connection failed." + System.Environment.NewLine + "Please make sure that the credentials you use are correct and that ALM Client is registered on your machine.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.QcLoginSuccess, new UserMsg(eUserMsgType.INFO, "Login Success", "QC/ALM Login successful!", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ALMLoginFailed, new UserMsg(eUserMsgType.WARN, "Login Failed", "ALM Login Failed - {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.QcNeedLogin, new UserMsg(eUserMsgType.WARN, "Not Connected to QC/ALM", "You Must Log Into QC/ALM First.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.TestCasesUpdatedSuccessfully, new UserMsg(eUserMsgType.INFO, "TestCase Update", "TestCases Updated Successfully.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.TestCasesUploadedSuccessfully, new UserMsg(eUserMsgType.INFO, "TestCases Uploaded", "TestCases Uploaded Successfully.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.TestSetsImportedSuccessfully, new UserMsg(eUserMsgType.INFO, "Import ALM Test Set", "ALM Test Set/s import process ended successfully.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.TestSetExists, new UserMsg(eUserMsgType.WARN, "Import Exiting Test Set", "The Test Set '{0}' was imported before and already exists in current Solution." + System.Environment.NewLine + "Do you want to delete the existing mapped " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " and import the Test Set again?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.ErrorInTestsetImport, new UserMsg(eUserMsgType.ERROR, "Import Test Set Error", "Error Occurred while exporting the Test Set '{0}'." + System.Environment.NewLine + "Error Details:{1}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ErrorWhileExportingExecDetails, new UserMsg(eUserMsgType.ERROR, "Export Execution Details Error", "Error occurred while exporting the execution details to QC/ALM." + System.Environment.NewLine + "Error Details:{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportedExecDetailsToALM, new UserMsg(eUserMsgType.INFO, "Export Execution Details", "Export execution details result: {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportAllItemsToALMSucceed, new UserMsg(eUserMsgType.INFO, "Export All Items to ALM", "All items has been successfully exported to ALM.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportAllItemsToALMFailed, new UserMsg(eUserMsgType.INFO, "Export All Items to ALM", "While exporting to ALM One or more items failed to export.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportItemToALMSucceed, new UserMsg(eUserMsgType.INFO, "Export ALM Item", "Exporting item to ALM process ended successfully.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ALMOperationFailed, new UserMsg(eUserMsgType.ERROR, "ALM Operation Failed", "Failed to perform the {0} operation." + Environment.NewLine + Environment.NewLine + "Error Details: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ActivitiesGroupAlreadyMappedToTC, new UserMsg(eUserMsgType.WARN, "Export " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " to QC/ALM", "The " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " '{0}' is already mapped to the QC/ALM '{1}' Test Case, do you want to update it?" + Environment.NewLine + Environment.NewLine + "Select 'Yes' to update or 'No' to create new Test Case.", eUserMsgOption.YesNoCancel, eUserMsgSelection.Cancel)); Reporter.UserMsgsPool.Add(eUserMsgKey.BusinessFlowAlreadyMappedToTC, new UserMsg(eUserMsgType.WARN, "Export " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " to QC/ALM", "The " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '{0}' is already mapped to the QC/ALM '{1}' Test Set, do you want to update it?" + Environment.NewLine + Environment.NewLine + "Select 'Yes' to update or 'No' to create new Test Set.", eUserMsgOption.YesNoCancel, eUserMsgSelection.Cancel)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportQCNewTestSetSelectDiffFolder, new UserMsg(eUserMsgType.INFO, "Export QC Item - Creating new Test Set", "Please select QC folder to export to that the Test Set does not exist there.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportItemToALMFailed, new UserMsg(eUserMsgType.ERROR, "Export to ALM Failed", "The {0} '{1}' failed to be exported to ALM." + Environment.NewLine + Environment.NewLine + "Error Details: {2}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfToSaveBFAfterExport, new UserMsg(eUserMsgType.QUESTION, "Save Links to QC/ALM Items", "The " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '{0}' must be saved for keeping the links to QC/ALM items." + Environment.NewLine + "To perform the save now?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfToLoadExternalFields, new UserMsg(eUserMsgType.QUESTION, "Load/Refresh ALM External Fields", "The activity will run in the background for several hours." + Environment.NewLine + "Please do not close Ginger until operation is complete." + Environment.NewLine + "Would you like to continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); #endregion QC #region UnitTester Messages Reporter.UserMsgsPool.Add(eUserMsgKey.TestCompleted, new UserMsg(eUserMsgType.INFO, "Test Completed", "Test completed successfully.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CantFindObject, new UserMsg(eUserMsgType.INFO, "Missing Object", "Cannot find the {0}, the ID is: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion UnitTester Messages #region CommandLineParams Reporter.UserMsgsPool.Add(eUserMsgKey.UnknownParamInCommandLine, new UserMsg(eUserMsgType.ERROR, "Unknown Parameter", "Parameter not recognized {0}", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion CommandLineParams Messages #region Tree / Grid / List Reporter.UserMsgsPool.Add(eUserMsgKey.ConfirmToAddTreeItem, new UserMsg(eUserMsgType.QUESTION, "Add New Item to Tree", "Are you Sure you want to add new item to tree?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToAddTreeItem, new UserMsg(eUserMsgType.ERROR, "Add Tree Item", "Failed to add the tree item '{0}'." + Environment.NewLine + "Error Details: '{1}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SureWantToDeleteAll, new UserMsg(eUserMsgType.QUESTION, "Delete All", "Are you sure you want to delete all?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SureWantToDeleteSelectedItems, new UserMsg(eUserMsgType.QUESTION, "Delete Selected", "Are you sure you want to delete selected {0} like '{1}'?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SureWantToContinue, new UserMsg(eUserMsgType.QUESTION, "Replace Existing", "Are you sure you want to delete the existing '{1}' ?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.BaseAPIWarning, new UserMsg(eUserMsgType.WARN, "Merged API Not found", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SureWantToDelete, new UserMsg(eUserMsgType.QUESTION, "Delete", "Are you sure you want to delete '{0}'?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoItemToDelete, new UserMsg(eUserMsgType.WARN, "Delete All", "Didn't found item to delete", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SelectItemToDelete, new UserMsg(eUserMsgType.WARN, "Delete", "Please select items to delete", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SelectItemToAdd, new UserMsg(eUserMsgType.WARN, "Add New Item", "Please select an Activity on which you want to add a new Action", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToloadTheGrid, new UserMsg(eUserMsgType.ERROR, "Load Grid", "Failed to load the grid." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DragDropOperationFailed, new UserMsg(eUserMsgType.ERROR, "Drag and Drop", "Drag & Drop operation failed." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SelectValidColumn, new UserMsg(eUserMsgType.WARN, "Column Not Found", "Please select a valid column", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SelectValidRow, new UserMsg(eUserMsgType.WARN, "Row Not Found", "Please select a valid row", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Tree / Grid #region ActivitiesGroup Reporter.UserMsgsPool.Add(eUserMsgKey.NoActivitiesGroupWasSelected, new UserMsg(eUserMsgType.WARN, "Missing " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " Selection", "No " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " was selected.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ActivitiesGroupActivitiesNotFound, new UserMsg(eUserMsgType.WARN, "Import " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " " + GingerDicser.GetTermResValue(eTermResKey.Activities), GingerDicser.GetTermResValue(eTermResKey.Activities) + " to import were not found in the repository.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.PartOfActivitiesGroupActsNotFound, new UserMsg(eUserMsgType.WARN, "Import " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup) + " " + GingerDicser.GetTermResValue(eTermResKey.Activities), "The following " + GingerDicser.GetTermResValue(eTermResKey.Activities) + " to import were not found in the repository:" + System.Environment.NewLine + "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SureWantToDeleteGroup, new UserMsg(eUserMsgType.QUESTION, "Delete Group", "Are you sure you want to delete the '{0}' group?", eUserMsgOption.YesNo, eUserMsgSelection.No)); #endregion ActivitiesGroup #region Mobile Reporter.UserMsgsPool.Add(eUserMsgKey.MobileConnectionFailed, new UserMsg(eUserMsgType.ERROR, "Mobile Connection", "Failed to connect to the mobile device." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MobileRefreshScreenShotFailed, new UserMsg(eUserMsgType.ERROR, "Mobile Screen Image", "Failed to refresh the mobile device screen image." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MobileShowElementDetailsFailed, new UserMsg(eUserMsgType.ERROR, "Mobile Elements Inspector", "Failed to locate the details of the selected element." + Environment.NewLine + "Error Details: '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MobileActionWasAdded, new UserMsg(eUserMsgType.INFO, "Add Action", "Action was added.", eUserMsgOption.OK, eUserMsgSelection.None)); //Reporter.UserMessagesPool.Add(eUserMsgKey.MobileActionWasAdded, new UserMessage(eMessageType.INFO, "Add Action", "Action was added." + System.Environment.NewLine + System.Environment.NewLine + "Do you want to run the Action?", MessageBoxButton.YesNo, MessageBoxResult.No)); #endregion Mobile #region Reports Reporter.UserMsgsPool.Add(eUserMsgKey.ReportTemplateNotFound, new UserMsg(eUserMsgType.ERROR, "Report Template", "Report Template '{0}' not found", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AutomationTabExecResultsNotExists, new UserMsg(eUserMsgType.WARN, "Execution Results are not existing", "Results from last execution are not existing (yet). Nothing to report, please wait for execution finish and click on report creation.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FolderNamesAreTooLong, new UserMsg(eUserMsgType.WARN, "Folders Names Are Too Long", "Provided folders names are too long. Please change them to be less than 100 characters", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FolderSizeTooSmall, new UserMsg(eUserMsgType.WARN, "Folders Size is Too Small", "Provided folder size is Too Small. Please change it to be bigger than 50 Mb", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DefaultTemplateCantBeDeleted, new UserMsg(eUserMsgType.WARN, "Default Template Can't Be Deleted", "Default Template Can't Be Deleted. Please change it to be a non-default", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExecutionsResultsProdIsNotOn, new UserMsg(eUserMsgType.WARN, "Executions Results Producing Should Be Switched On", "In order to perform this action, executions results producing should be switched On", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExecutionsResultsNotExists, new UserMsg(eUserMsgType.WARN, "Executions Results Are Not Existing Yet", "In order to get HTML report, please, perform executions before", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExecutionsResultsToDelete, new UserMsg(eUserMsgType.QUESTION, "Delete Executions Results", "Are you sure you want to delete selected Executions Results?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.AllExecutionsResultsToDelete, new UserMsg(eUserMsgType.QUESTION, "Delete All Executions Results", "Are you sure you want to delete all Executions Results?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.HTMLReportAttachment, new UserMsg(eUserMsgType.WARN, "HTML Report Attachment", "HTML Report Attachment already exists, please delete existing one.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ImageSize, new UserMsg(eUserMsgType.WARN, "Image Size", "Image Size should be less than 30 Kb", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.BFNotExistInDB, new UserMsg(eUserMsgType.INFO, "Run " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow), "Business Flow data don't exist in LiteDB, Please run to generate report", eUserMsgOption.OK, eUserMsgSelection.None)); #endregion Reports Reporter.UserMsgsPool.Add(eUserMsgKey.ApplicationNotFoundInEnvConfig, new UserMsg(eUserMsgType.ERROR, "Application Not Found In EnvConfig", "Application = {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExecutionReportSent, new UserMsg(eUserMsgType.INFO, "Publish", "Execution report sent by email", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ErrorReadingRepositoryItem, new UserMsg(eUserMsgType.ERROR, "Error Reading Repository Item", "Repository Item {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.EnvNotFound, new UserMsg(eUserMsgType.ERROR, "Env not found", "Env not found {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CannotAddGinger, new UserMsg(eUserMsgType.ERROR, "Cannot Add Ginger", "Number of Gingers is limited to 12 Gingers.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ShortcutCreated, new UserMsg(eUserMsgType.INFO, "New Shortcut created", "Shortcut created on selected path - {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ShortcutCreationFailed, new UserMsg(eUserMsgType.ERROR, "Shortcut creation Failed", "Cannot create shortcut.Please avoid special characters in the Name/Description. Details: -{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CannotRunShortcut, new UserMsg(eUserMsgType.ERROR, "Shortcut Execution Failed", "Cannot execute shortcut. Details: -{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SolutionFileNotFound, new UserMsg(eUserMsgType.ERROR, "Solution File Not Found", "Cannot find Solution File at - {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.PlugInFileNotFound, new UserMsg(eUserMsgType.ERROR, "Plugin Configuration File Not Found", "Cannot find Plugin Configuration File at - {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.PluginDownloadInProgress, new UserMsg(eUserMsgType.WARN,"Plugins Download is in Progress" ,"Missing Plugins download is in progress, please wait for it to finish and then try to load page again.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ActionIDNotFound, new UserMsg(eUserMsgType.ERROR, "Action ID Not Found", "Cannot find action with ID - {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ActivityIDNotFound, new UserMsg(eUserMsgType.ERROR, GingerDicser.GetTermResValue(eTermResKey.Activity) + " ID Not Found", "Cannot find " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " with ID - {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToSendEmail, new UserMsg(eUserMsgType.ERROR, "Failed to Send E-mail", "Failed to send the {0} over e-mail using {1}." + Environment.NewLine + Environment.NewLine + "Error Details: {2}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToExportBF, new UserMsg(eUserMsgType.ERROR, "Failed to export BusinessFlow to CSV", "Failed to export BusinessFlow to CSV file. Got error {0}" + Environment.NewLine, eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FoundDuplicateAgentsInRunSet, new UserMsg(eUserMsgType.ERROR, "Found Duplicate Agents in " + GingerDicser.GetTermResValue(eTermResKey.RunSet), "Agent name '{0}' is defined more than once in the " + GingerDicser.GetTermResValue(eTermResKey.RunSet), eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FileNotExist, new UserMsg(eUserMsgType.WARN, "XML File Not Exist", "XML File has not been found on the specified path, either deleted or been re-named on the define XML path", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FilterNotBeenSet, new UserMsg(eUserMsgType.QUESTION, "Filter Not Been Set", "No filtering criteria has been set, Retrieving all elements from page can take long time to complete, Do you want to continue?", eUserMsgOption.OKCancel, eUserMsgSelection.Cancel)); Reporter.UserMsgsPool.Add(eUserMsgKey.CloseFilterPage, new UserMsg(eUserMsgType.QUESTION, "Confirmation", "'{0}' Elements Found, Close Filtering Page?", eUserMsgOption.YesNo, eUserMsgSelection.Yes)); Reporter.UserMsgsPool.Add(eUserMsgKey.RetreivingAllElements, new UserMsg(eUserMsgType.QUESTION, "Retrieving all elements", "Retrieving all elements from page can take long time to complete, Do you want to continue?", eUserMsgOption.OKCancel, eUserMsgSelection.Cancel)); Reporter.UserMsgsPool.Add(eUserMsgKey.WhetherToOpenSolution, new UserMsg(eUserMsgType.QUESTION, "Open Downloaded Solution?", "Do you want to open the downloaded Solution?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.ClickElementAgain, new UserMsg(eUserMsgType.INFO, "Please Click", "Please click on the desired element again", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CurrentActionNotSaved, new UserMsg(eUserMsgType.INFO, "Current Action Not Saved", "Before using the 'next/previous action' button, Please save the current action", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.LoseChangesWarn, new UserMsg(eUserMsgType.WARN, "Save Changes", "The operation may result with lost of un-saved local changes." + Environment.NewLine + "Please make sure all changes were saved before continue." + Environment.NewLine + Environment.NewLine + "To perform the operation?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.CompilationErrorOccured, new UserMsg(eUserMsgType.ERROR, "Compilation Error Occurred", "Compilation error occurred." + Environment.NewLine + "Error Details: " + Environment.NewLine + " '{0}'.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CopiedVariableSuccessfully, new UserMsg(eUserMsgType.INFO, "Info Message", "'{0}'" + GingerDicser.GetTermResValue(eTermResKey.BusinessFlows) + " Affected." + Environment.NewLine + Environment.NewLine + "Notice: Un-saved changes won't be saved.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.RenameItemError, new UserMsg(eUserMsgType.ERROR, "Rename", "Failed to rename the Item. Error: '{0}'?", eUserMsgOption.OK, eUserMsgSelection.OK)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfShareVaribalesInRunner, new UserMsg(eUserMsgType.QUESTION, "Share" + GingerDicser.GetTermResValue(eTermResKey.Variables), "Are you sure you want to share selected " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " Values to all the similar " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlows) + " and " + GingerDicser.GetTermResValue(eTermResKey.Activities) + " across all Runners?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.CompilationSucceed, new UserMsg(eUserMsgType.INFO, "Compilation Succeed", "Compilation Passed successfully.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FileExtensionNotSupported, new UserMsg(eUserMsgType.ERROR, "File Extension Not Supported", "The selected file extension is not supported by this editor." + Environment.NewLine + "Supported extensions: '{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NotifyFileSelectedFromTheSolution, new UserMsg(eUserMsgType.ERROR, "File Already Exists", "File - '{0}'." + Environment.NewLine + "Selected From The Solution folder hence its already exist and cannot be copy to the same place" + Environment.NewLine + "Please select another File to continue.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FileImportedSuccessfully, new UserMsg(eUserMsgType.INFO, "File imported successfully", "The File was imported successfully", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfToUndoChanges, new UserMsg(eUserMsgType.QUESTION, "Undo Changes?", "Do you want to undo changes (in case changes were done) and close?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfToUndoItemChanges, new UserMsg(eUserMsgType.QUESTION, "Undo Changes?", "Do you want to undo changes for '{0}'?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.InvalidIndexValue, new UserMsg(eUserMsgType.ERROR, "Invalid index value", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FileOperationError, new UserMsg(eUserMsgType.ERROR, "Error occurred during file operation", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FolderOperationError, new UserMsg(eUserMsgType.ERROR, "Error occurred during folder operation", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ObjectUnavailable, new UserMsg(eUserMsgType.ERROR, "Object Unavailable", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.PatternNotHandled, new UserMsg(eUserMsgType.ERROR, "Pattern not handled", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.LostConnection, new UserMsg(eUserMsgType.ERROR, "Lost Connection", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskToSelectBusinessflow, new UserMsg(eUserMsgType.INFO, "Select Businessflow", "Please select " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow), eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingFileLocation, new UserMsg(eUserMsgType.INFO, "Missing file location", "Please select a location for the file.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ScriptPaused, new UserMsg(eUserMsgType.INFO, "Script Paused", "Script is paused!", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ElementNotFound, new UserMsg(eUserMsgType.ERROR, "Element Not Found", "Element not found", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.TextNotFound, new UserMsg(eUserMsgType.ERROR, "Text Not Found", "Text not found", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ProvideSearchString, new UserMsg(eUserMsgType.ERROR, "Provide Search String", "Please provide search string", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoTextOccurrence, new UserMsg(eUserMsgType.ERROR, "No Text Occurrence", "No more text occurrence", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToInitiate, new UserMsg(eUserMsgType.ERROR, "Failed to initiate", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToCreateRequestResponse, new UserMsg(eUserMsgType.ERROR, "Failed to create Request / Response", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ActionNotImplemented, new UserMsg(eUserMsgType.ERROR, "Action is not implemented yet for control type ", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ValueIssue, new UserMsg(eUserMsgType.ERROR, "Value Issue", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.JSExecutionFailed, new UserMsg(eUserMsgType.ERROR, "Error Executing JS", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingTargetApplication, new UserMsg(eUserMsgType.ERROR, "Missing target application", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ThreadError, new UserMsg(eUserMsgType.ERROR, "Thread Exception", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ParsingError, new UserMsg(eUserMsgType.ERROR, "Error while parsing", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SpecifyUniqueValue, new UserMsg(eUserMsgType.WARN, "Please specify unique value", "Optional value already exists", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ParameterAlreadyExists, new UserMsg(eUserMsgType.WARN, "Cannot upload the selected parameter", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteNodesFromRequest, new UserMsg(eUserMsgType.WARN, "Delete nodes from request body?", "Do you want to delete also nodes from request body that contain those parameters?", eUserMsgOption.YesNo, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ParameterMerge, new UserMsg(eUserMsgType.WARN, "Models Parameters Merge", "Do you want to update the merged instances on all model configurations?", eUserMsgOption.YesNo, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ParameterEdit, new UserMsg(eUserMsgType.WARN, "Global Parameter Edit", "Global Parameter Place Holder cannot be edit.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ParameterUpdate, new UserMsg(eUserMsgType.WARN, "Update Global Parameter Value Expression Instances", "{0}", eUserMsgOption.YesNo, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ParameterDelete, new UserMsg(eUserMsgType.WARN, "Delete Parameter", "{0}", eUserMsgOption.YesNo, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SaveAll, new UserMsg(eUserMsgType.WARN, "Save All", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SaveSelected, new UserMsg(eUserMsgType.WARN, "Save Selected", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CopiedErrorInfo, new UserMsg(eUserMsgType.INFO, "Copied Error information", "Error Information copied to Clipboard", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.RepositoryNameCantEmpty, new UserMsg(eUserMsgType.WARN, "QTP to Ginger Converter", "Object Repository name cannot be empty", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExcelProcessingError, new UserMsg(eUserMsgType.ERROR, "Excel processing error", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.EnterValidBusinessflow, new UserMsg(eUserMsgType.WARN, "Enter valid businessflow", "Please enter a Valid " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " Name", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteItem, new UserMsg(eUserMsgType.WARN, "Delete Item", "Are you sure you want to delete '{0}' item ?", eUserMsgOption.YesNo, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.RefreshFolder, new UserMsg(eUserMsgType.WARN, "Refresh Folder", "Un saved items changes under the refreshed folder will be lost, to continue with refresh?", eUserMsgOption.YesNo, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.RefreshFailed, new UserMsg(eUserMsgType.ERROR, "Refresh Failed", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ReplaceAll, new UserMsg(eUserMsgType.QUESTION, "Replace All", "{0}", eUserMsgOption.OKCancel, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ItemSelection, new UserMsg(eUserMsgType.WARN, "Item Selection", "{0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DifferentItemType, new UserMsg(eUserMsgType.WARN, "Not Same Item Type", "The source item type do not match to the destination folder type", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CopyCutOperation, new UserMsg(eUserMsgType.INFO, "Copy/Cut Operation", "Please select Copy/Cut operation first.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ObjectLoad, new UserMsg(eUserMsgType.ERROR, "Object Load", "Not able to load the object details", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.InitializeBrowser, new UserMsg(eUserMsgType.INFO, "Initialize Browser", "Initialize Browser action automatically added." + Environment.NewLine + "Please continue to spy the required element.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.GetModelItemUsagesFailed, new UserMsg(eUserMsgType.ERROR, "Model Item Usages", "Failed to get the '{0}' item usages." + Environment.NewLine + Environment.NewLine + "Error Details: {1}.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SolutionSaveWarning, new UserMsg(eUserMsgType.WARN, "Save", "Note: save will include saving also changes which were done to: {0}." + System.Environment.NewLine + System.Environment.NewLine + "To continue with Save operation?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SaveItemParentWarning, new UserMsg(eUserMsgType.WARN, "Item Parent Save", "Save process will actually save the item {0} parent which called '{1}'." + System.Environment.NewLine + System.Environment.NewLine + "To continue with save?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SaveAllItemsParentWarning, new UserMsg(eUserMsgType.WARN, "Items Parent Save", "Save process will actually save item\\s parent\\s (" + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ")" + System.Environment.NewLine + System.Environment.NewLine + "To continue with save?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlConflictResolveFailed, new UserMsg(eUserMsgType.ERROR, "Resolve Conflict Failed", "Ginger failed to resolve the conflicted file" + Environment.NewLine + "File Path: {0}" + Environment.NewLine + Environment.NewLine + "It seems like the SVN conflict content (e.g. '<<<<<<< .mine') has been updated on the remote repository", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.SourceControlItemAlreadyLocked, new UserMsg(eUserMsgType.INFO, "Source Control File Locked", "The file is already locked" + Environment.NewLine + "Please do Get info for more details", eUserMsgOption.OK, eUserMsgSelection.OK)); Reporter.UserMsgsPool.Add(eUserMsgKey.SoruceControlItemAlreadyUnlocked, new UserMsg(eUserMsgType.INFO, "Source Control File not Locked", "The file is not locked" + Environment.NewLine + "Please do Get info for more details", eUserMsgOption.OK, eUserMsgSelection.OK)); Reporter.UserMsgsPool.Add(eUserMsgKey.RefreshWholeSolution, new UserMsg(eUserMsgType.QUESTION, "Refresh Solution", "Do you want to Refresh the whole Solution to get the Latest changes?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.OracleDllIsMissing, new UserMsg(eUserMsgType.ERROR, "DB Connection Status", "Connect to the DB failed." + Environment.NewLine + "The file Oracle.ManagedDataAccess.dll is missing," + Environment.NewLine + "Please download the file, place it under the below folder, restart Ginger and retry:" + Environment.NewLine + "{0}" + Environment.NewLine + "Do you want to download the file now?", eUserMsgOption.YesNo, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingExcelDetails, new UserMsg(eUserMsgType.ERROR, "Missing Export Path Details", "The Export Excel File Path is missing", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.InvalidExcelDetails, new UserMsg(eUserMsgType.ERROR, "InValid Export Sheet Details", "The Export Excel can be *.xlsx only.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportFailed, new UserMsg(eUserMsgType.ERROR, "Export Failed", "Error Occurred while exporting the {0}: {1}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportDetails, new UserMsg(eUserMsgType.INFO, "Export Details", "Export execution ended successfully", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ParamExportMessage, new UserMsg(eUserMsgType.QUESTION, "Param Export to Data Source", "Special Characters will be removed from Parameter Names while exporting to Data Source. Do you wish to Continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.CreateTableError, new UserMsg(eUserMsgType.ERROR, "Create Table Error", "Failed to Create the Table. Error: {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MappedtoDataSourceError, new UserMsg(eUserMsgType.ERROR, "Output Param Mapping Error ", "Failed to map the Output Params to Data Source", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.InvalidDataSourceDetails, new UserMsg(eUserMsgType.ERROR, "Invalid Data Source Details", "The Data Source Details provided are Invalid.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteDSFileError, new UserMsg(eUserMsgType.WARN, "Delete DataSource File", "The Data Source File with the File Path '{0}' Could not be deleted. Please Delete file Manually", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.InvalidDSPath, new UserMsg(eUserMsgType.ERROR, "Invalid DataSource Path", "The Data Source with the File Path {0} is not valid. Please use correct File Path", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.InvalidColumnName, new UserMsg(eUserMsgType.ERROR, "Invalid Column Details", "The Column Name is invalid.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.CreateRunset, new UserMsg(eUserMsgType.WARN, "Create Runset", "No runset found, Do you want to create new runset", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteRunners, new UserMsg(eUserMsgType.WARN, "Delete Runners", "Are you sure you want to delete all runners", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteRunner, new UserMsg(eUserMsgType.WARN, "Delete Runner", "Are you sure you want to delete selected runner", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteBusinessflows, new UserMsg(eUserMsgType.WARN, "Delete " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlows), "Are you sure you want to delete all" + GingerDicser.GetTermResValue(eTermResKey.BusinessFlows), eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.DeleteBusinessflow, new UserMsg(eUserMsgType.WARN, "Delete " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow), "Are you sure you want to delete selected " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow), eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.RunsetBuinessFlowWasChanged, new UserMsg(eUserMsgType.WARN, GingerDicser.GetTermResValue(eTermResKey.RunSet) + " " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " Changed", "One or more of the " + GingerDicser.GetTermResValue(eTermResKey.RunSet) + " " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlows) + " were changed/deleted." + Environment.NewLine + "You must reload the " + GingerDicser.GetTermResValue(eTermResKey.RunSet) + " for changes to be viewed/executed." + Environment.NewLine + Environment.NewLine + "Do you want to reload the " + GingerDicser.GetTermResValue(eTermResKey.RunSet) + "?" + Environment.NewLine + Environment.NewLine + "Note: Reload will cause un-saved changes to be lost.", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.RunSetReloadhWarn, new UserMsg(eUserMsgType.WARN, "Reload " + GingerDicser.GetTermResValue(eTermResKey.RunSet), "Reload process will cause all un-saved changes to be lost." + Environment.NewLine + Environment.NewLine + " To continue with reload?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.CantDeleteRunner, new UserMsg(eUserMsgType.WARN, "Delete Runner", "You can't delete last Runner, you must have at least one.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.DuplicateRunsetName, new UserMsg(eUserMsgType.WARN, "Duplicate Runset Name", "'{0}' already exists, please use different name", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.WarnOnDynamicActivities, new UserMsg(eUserMsgType.QUESTION, "Dynamic " + GingerDicser.GetTermResValue(eTermResKey.Activities) + " Warning", "The dynamically added Shared Repository " + GingerDicser.GetTermResValue(eTermResKey.Activities) + " will not be saved (but they will continue to appear on the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow, suffixString:")") + System.Environment.NewLine + System.Environment.NewLine + "To continue with Save?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.QcConnectFailureRestAPI, new UserMsg(eUserMsgType.WARN, "QC/ALM Connection Failed", "QC/ALM connection failed." + System.Environment.NewLine + "Please make sure that the server url and the credentials you use are correct.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ExportedExecDetailsToALMIsInProcess, new UserMsg(eUserMsgType.INFO, "Export Execution Details", "Please Wait, Exporting Execution Details is in process.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskBeforeDefectProfileDeleting, new UserMsg(eUserMsgType.QUESTION, "Profiles Deleting", "After deletion there will be no way to restore deleted profiles.\nAre you sure that you want to delete the selected profiles?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissedMandatotryFields, new UserMsg(eUserMsgType.INFO, "Profiles Saving", "Please, populate value for mandatory field '{0}' of '{1}' Defect Profile", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoDefaultDefectProfileSelected, new UserMsg(eUserMsgType.INFO, "Profiles Saving", "Please, select one of the Defect Profiles to be a 'Default'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.IssuesInSelectedDefectProfile, new UserMsg(eUserMsgType.INFO, "ALM Defects Opening", "Please, revise the selected Defect Profile, current fields/values are not corresponded with ALM", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoDefectProfileCreated, new UserMsg(eUserMsgType.INFO, "Defect Profiles", "Please, create at least one Defect Profile", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.WrongValueSelectedFromTheList, new UserMsg(eUserMsgType.INFO, "Profiles Saving", "Please, select one of the existed values from the list\n(Field '{0}', Defect Profile '{1}')", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.WrongNonNumberValueInserted, new UserMsg(eUserMsgType.INFO, "Profiles Saving", "Please, insert numeric value\n(Field '{0}', Defect Profile '{1}')", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.WrongDateValueInserted, new UserMsg(eUserMsgType.INFO, "Profiles Saving", "Please, insert Date in format 'yyyy-mm-dd'\n(Field '{0}', Defect Profile '{1}')", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ALMDefectsWereOpened, new UserMsg(eUserMsgType.INFO, "ALM Defects Opening", "{0} ALM Defects were opened", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskALMDefectsOpening, new UserMsg(eUserMsgType.QUESTION, "ALM Defects Opening", "Are you sure that you want to open {0} ALM Defects?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.ALMDefectsUserInOtaAPI, new UserMsg(eUserMsgType.INFO, "ALM Defects Valid for Rest API only", "You are in ALM Ota API mode, Please change to Rest API", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfToDownloadPossibleValuesShortProcesss, new UserMsg(eUserMsgType.QUESTION, "ALM External Items Fields", "Would you like to download and save possible values for Categories Items? ", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfToDownloadPossibleValues, new UserMsg(eUserMsgType.QUESTION, "ALM External Items Fields", "Would you like to download and save possible values for Categories Items? " + Environment.NewLine + "This process could take up to several hours.", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.SelectAndSaveCategoriesValues, new UserMsg(eUserMsgType.QUESTION, "ALM External Items Fields", "Please select values for each Category Item and click on Save", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMSearchByGUIDFailed, new UserMsg(eUserMsgType.WARN, "POM not found", "Previously saved POM not found. Please choose another one.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMElementSearchByGUIDFailed, new UserMsg(eUserMsgType.WARN, "POM Element not found", "Previously saved POM Element not found. Please choose another one.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoRelevantAgentInRunningStatus, new UserMsg(eUserMsgType.WARN, "No Relevant Agent In Running Status", "Relevant Agent In should be up and running in order to see the highlighted element.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMWizardFailedToLearnElement, new UserMsg(eUserMsgType.WARN, "Learn Elements Failed", "Error occurred while learning the elements." + Environment.NewLine + "Error Details:" + Environment.NewLine + "'{0}'", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMWizardReLearnWillDeleteAllElements, new UserMsg(eUserMsgType.WARN, "Re-Learn Elements", "Re-Learn Elements will delete all existing elements" + Environment.NewLine + "Do you want to continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMDeltaWizardReLearnWillEraseModification, new UserMsg(eUserMsgType.WARN, "Re-Learn Elements", "Re-Learn Elements will delete all existing modifications" + Environment.NewLine + "Do you want to continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMDriverIsBusy, new UserMsg(eUserMsgType.WARN, "Driver Is Busy", "Operation cannot be complete because the Driver is busy with learning operation" + Environment.NewLine + "Do you want to continue?", eUserMsgOption.OK, eUserMsgSelection.OK)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMAgentIsNotRunning, new UserMsg(eUserMsgType.WARN, "Agent is Down", "In order to perform this operation the Agent needs to be up and running." + Environment.NewLine + "Please start the agent and re-try", eUserMsgOption.OK, eUserMsgSelection.OK)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMNotOnThePageWarn, new UserMsg(eUserMsgType.WARN, "Not On the Same Page", "'{0}' Elements out of '{1}' Elements failed to be found on the page" + Environment.NewLine + "Looks like you are not on the right page" + Environment.NewLine + "Do you want to continue?", eUserMsgOption.YesNo, eUserMsgSelection.Yes)); Reporter.UserMsgsPool.Add(eUserMsgKey.POMCannotDeleteAutoLearnedElement, new UserMsg(eUserMsgType.WARN, "Cannot Delete Auto Learned Element", "The Element you are trying to delete has been learned automatically from page and cannot be deleted", eUserMsgOption.OK, eUserMsgSelection.OK)); Reporter.UserMsgsPool.Add(eUserMsgKey.WizardCantMoveWhileInProcess, new UserMsg(eUserMsgType.WARN, "Process is Still Running", "Move '{0}' until the process will be finished or stopped." + Environment.NewLine + "Please wait for the process to be finished or stop it and then retry.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AskIfToCloseAgent, new UserMsg(eUserMsgType.QUESTION, "Close Agent?", "Close Agent '{0}'?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.FolderNameTextBoxIsEmpty, new UserMsg(eUserMsgType.WARN, "Folders Names is Empty", "Please provide a proper folder name.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.UserHaveNoWritePermission, new UserMsg(eUserMsgType.WARN, "User Have No Write Permission On Folder", "User that currently in use have no write permission on selected folder. Pay attention that attachment at shared folder may be not created.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FolderNotExistOrNotAvailible, new UserMsg(eUserMsgType.WARN, "Folder Not Exist Or Not Available", "Folder Not Exist Or Not Available. Please select another one.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.WizardSureWantToCancel, new UserMsg(eUserMsgType.QUESTION, "Cancel Wizard?", "Are you sure you want to cancel wizard and close?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.ReportsTemplatesSaveWarn, new UserMsg(eUserMsgType.WARN, "Default Template Report Change", "Default change will cause all templates to be updated and saved, to continue?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.FailedToLoadPlugIn, new UserMsg(eUserMsgType.ERROR, "Failed to Load Plug In", "Ginger could not load the plug in '{0}'" + Environment.NewLine + "Error Details: {1}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.Failedtosaveitems, new UserMsg(eUserMsgType.ERROR, "Failed to Save", "Failed to do Save All", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.AllItemsSaved, new UserMsg(eUserMsgType.INFO, "All Changes Saved", "All Changes Saved", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoConvertibleActionsFound, new UserMsg(eUserMsgType.INFO, "No Convertible Actions Found", "The selected " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " doesn't contain any convertible actions.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoConvertibleActionSelected, new UserMsg(eUserMsgType.WARN, "No Convertible Action Selected", "Please select the actions that you want to convert.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoActivitySelectedForConversion, new UserMsg(eUserMsgType.WARN, "No Activity Selected", "Please select an " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " that you want to convert.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ActivitiesConversionFailed, new UserMsg(eUserMsgType.WARN, "Activities Conversion Failed", "Activities Conversion Failed.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ShareVariableNotSelected, new UserMsg(eUserMsgType.INFO, "Info Message", "Please select the " + GingerDicser.GetTermResValue(eTermResKey.Variables) + " to share.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.APIParametersListUpdated, new UserMsg(eUserMsgType.WARN, "API Model Parameters Difference", "Difference was identified between the list of parameters which configured on the API Model and the parameters exists on the Action.\n\nDo you want to update the Action parameters?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.APIMappedToActionIsMissing, new UserMsg(eUserMsgType.WARN, "Missing Mapped API Model", "The API Model which mapped to this action is missing, please remap API Model to the action.", eUserMsgOption.OK, eUserMsgSelection.OK)); Reporter.UserMsgsPool.Add(eUserMsgKey.NoAPIExistToMappedTo, new UserMsg(eUserMsgType.WARN, "No API Model Found", "API Models repository is empty, please add new API Models into it and map it to the action", eUserMsgOption.OK, eUserMsgSelection.OK)); Reporter.UserMsgsPool.Add(eUserMsgKey.APIModelAlreadyContainsReturnValues, new UserMsg(eUserMsgType.WARN, "Return Values Already Exist Warning", "{0} Return Values already exist for this API Model" + Environment.NewLine + "Do you want to override them by importing form new response template file?" + Environment.NewLine + Environment.NewLine + "Please Note! - by clicking yes all {0} return values will be deleted with no option to restore.", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.VisualTestingFailedToDeleteOldBaselineImage, new UserMsg(eUserMsgType.WARN, "Creating New Baseline Image", "Error while trying to create and save new Baseline Image.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ApplitoolsLastExecutionResultsNotExists, new UserMsg(eUserMsgType.INFO, "Show Last Execution Results", "No last execution results exists, Please run first the action, Close Applitools Eyes and then view the results.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ApplitoolsMissingChromeOrFirefoxBrowser, new UserMsg(eUserMsgType.INFO, "View Last Execution Results", "Applitools support only Chrome or Firefox Browsers, Please install at least one of them in order to browse Applitools URL results.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.ParameterOptionalValues, new UserMsg(eUserMsgType.INFO, "Parameters Optional Values", "{0} parameters were updated.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.RecoverItemsMissingSelectionToRecover, new UserMsg(eUserMsgType.WARN, "Recover Changes", "Please select valid Recover items to {0}", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingErrorHandler, new UserMsg(eUserMsgType.WARN, "Mismatch in Mapped Error Handler Found", "A mismatch has been detected in error handlers mapped with your activity." + Environment.NewLine + "Please check if any mapped error handler has been deleted or marked as inactive. ", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.BusinessFlowUpdate, new UserMsg(eUserMsgType.INFO, GingerDicser.GetTermResValue(eTermResKey.BusinessFlow), GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '{0}' {1} Successfully", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FindAndRepalceFieldIsEmpty, new UserMsg(eUserMsgType.WARN, "Field is Empty", "Field '{0}' cannot be empty", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FindAndReplaceListIsEmpty, new UserMsg(eUserMsgType.WARN, "List is Empty", "No items were found hence nothing can be replaced", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FindAndReplaceNoItemsToRepalce, new UserMsg(eUserMsgType.WARN, "No Suitable Items", "No suitable items selected to replace.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FindAndReplaceViewRunSetNotSupported, new UserMsg(eUserMsgType.INFO, "View " + GingerDicser.GetTermResValue(eTermResKey.RunSet), "View " + GingerDicser.GetTermResValue(eTermResKey.RunSet) + " is not supported.", eUserMsgOption.OK, eUserMsgSelection.None)); Reporter.UserMsgsPool.Add(eUserMsgKey.FileAlreadyExistWarn, new UserMsg(eUserMsgType.WARN, "File Already Exists", "File already exists, do you want to override?", eUserMsgOption.OKCancel, eUserMsgSelection.Cancel)); Reporter.UserMsgsPool.Add(eUserMsgKey.SuccessfulConversionDone, new UserMsg(eUserMsgType.INFO, "Obsolete actions converted successfully", "The obsolete actions have been converted successfully" + Environment.NewLine + "Do you want to convert more actions?", eUserMsgOption.YesNo, eUserMsgSelection.No)); Reporter.UserMsgsPool.Add(eUserMsgKey.MissingTargetPlatformForConversion, new UserMsg(eUserMsgType.WARN, "Missing Target Platform for Conversion", "For {0}, you need to add a Target Application of type {1}. Please add it to your " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + Environment.NewLine + "Do you want to continue with the conversion?", eUserMsgOption.YesNo, eUserMsgSelection.No)); } } }
176.809192
1,212
0.775949
[ "Apache-2.0" ]
ranadheerrannu/qa-accelerator
Ginger/GingerCoreCommon/ReporterLib/UserMsgsPool.cs
126,952
C#
//Copyright (c) Microsoft Corporation. All rights reserved. namespace Microsoft.WindowsAPI.Dialogs { /// <summary> /// Dialog Show State /// </summary> public enum DialogShowState { /// <summary> /// Pre Show /// </summary> PreShow, /// <summary> /// Currently Showing /// </summary> Showing, /// <summary> /// Currently Closing /// </summary> Closing, /// <summary> /// Closed /// </summary> Closed } }
18.096774
60
0.470588
[ "MIT" ]
shellscape/Shellscape.Common
Microsoft/Windows API/Interop/Dialogs/DialogShowState.cs
561
C#
using Entia.Core; using Entia.Injectables; using Entia.Modules; using Entia.Modules.Family; using Entia.Queryables; using FsCheck; using System; using System.Collections.Generic; using System.Linq; namespace Entia.Test { public static class Tests { static readonly Type[] _injectables; static readonly Type[] _queryables; static readonly Type[] _components; static readonly Type[] _resources; static Tests() { var injectables = new List<Type>(); var queryables = new List<Type>(); var components = new List<Type>(); var resources = new List<Type>(); foreach (var type in ReflectionUtility.AllTypes.Where(type => !type.IsAbstract && !type.IsGenericType)) { if (type.Is<IInjectable>()) injectables.Add(type); if (type.Is<Queryables.IQueryable>()) queryables.Add(type); if (type.Is<IComponent>()) components.Add(type); if (type.Is<IResource>()) resources.Add(type); } _injectables = injectables.ToArray(); _queryables = queryables.ToArray(); _components = components.ToArray(); _resources = resources.ToArray(); } public interface IComponentA : IComponentC { } public interface IComponentB : IComponentC { } public interface IComponentC : IComponent { } public struct ComponentA : IComponentA { } public struct ComponentB : IComponentA { [Default] public static ComponentB Default => new ComponentB { Value = 19f }; public float Value; } public struct ComponentC<T> : IComponentB { [Default] public static ComponentC<T> Default => new ComponentC<T> { B = new List<T>(), C = new List<T> { default, default } }; public List<T> A, B, C; } public struct MessageA : IMessage { } public struct MessageB : IMessage { [Default] public static MessageB Default() => new MessageB { A = 12, B = 26 }; public ulong A, B; } public struct MessageC<T> : IMessage { public T[] Values; } public struct ResourceA : IResource { } public struct ResourceB : IResource { [Default] public static readonly ResourceB Default = new ResourceB { A = 11, B = 23, C = 37 }; public byte A, B, C; } public struct ResourceC<T> : IResource { [Default] public static ResourceC<T> Default => new ResourceC<T> { Values = new Stack<T>() }; public Stack<T> Values; } [All(typeof(ComponentC<>))] public struct ProviderA { } [None(typeof(ComponentA), typeof(ComponentB))] public struct ProviderB { } [All(typeof(IComponentA))] [None(typeof(ComponentB))] public struct ProviderC { } public unsafe struct QueryA : Queryables.IQueryable { public ComponentA* P1; public Entity Entity; public ComponentB* P2; public Read<ComponentB> A; public ComponentB* P3; } public struct QueryB : Queryables.IQueryable { public All<Read<ComponentB>, Write<ComponentA>> A; public Maybe<Write<ComponentC<Unit>>> B; } public unsafe struct QueryC : Queryables.IQueryable { public ComponentA* P1; public ComponentB* P2; public ComponentB* P3; public QueryA A; public ComponentB* P4; public ComponentA* P5; public ComponentB* P6; public Entity Entity; public Any<Read<ComponentB>, Write<ComponentA>> B; public ComponentA* P7; public ComponentB* P8; } public struct Injectable : IInjectable { public readonly World World; public readonly AllEntities Entities; public readonly AllEntities.Read EntitiesRead; public readonly AllComponents Components; public readonly AllComponents.Read ComponentsRead; public readonly AllComponents.Write ComponentsWrite; public readonly Components<ComponentA> ComponentsA; public readonly Components<ComponentB>.Read ComponentsB; public readonly Components<ComponentC<Unit>>.Write ComponentsC; public readonly AllEmitters Emitters; public readonly Emitter<MessageA> EmitterA; public readonly Reaction<MessageB> ReactionB; public readonly Receiver<MessageC<string>> ReceiverC; public readonly Defer Defer; public readonly Defer.Components DeferComponents; public readonly Defer.Entities DeferEntities; [All(typeof(IComponentA))] [None(typeof(ComponentB))] public readonly Group<QueryA> GroupA; [None(typeof(ComponentA), typeof(ComponentB))] public readonly Group<QueryB> GroupB; [All(typeof(ComponentC<>))] public readonly Group<QueryC> GroupC; public readonly Resource<ResourceA> ResourceA; public readonly Resource<ResourceB>.Read ResourceB; } public static void Run(int count = 8192, int size = 512, int? seed = null) { Console.Clear(); var generator = Generator.Frequency( #region World (10, Gen.Fresh(() => new ResolveWorld().ToAction())), #endregion #region Entities (100, Gen.Fresh(() => new CreateEntity().ToAction())), (5, Gen.Fresh(() => new DestroyEntity().ToAction())), (1, Gen.Fresh(() => new ClearEntities().ToAction())), #endregion #region Components (20, Gen.Fresh(() => new AddComponent<ComponentA, IComponentA>(typeof(IComponentC)).ToAction())), (20, Gen.Fresh(() => new AddComponent<ComponentB, IComponentC>(typeof(IComponentA)).ToAction())), (20, Gen.Fresh(() => new AddComponent<ComponentC<Unit>, IComponentB>(typeof(ComponentC<>)).ToAction())), (20, Gen.Fresh(() => new AddComponent<ComponentC<int>, IComponentB>(typeof(ComponentC<>)).ToAction())), (15, Gen.Fresh(() => new RemoveComponent<ComponentA>().ToAction())), (15, Gen.Fresh(() => new RemoveComponent<ComponentB>().ToAction())), (15, Gen.Fresh(() => new RemoveComponent<ComponentC<Unit>>().ToAction())), (15, Gen.Fresh(() => new RemoveComponent<ComponentC<int>>().ToAction())), (15, Gen.Fresh(() => new RemoveComponent(typeof(IComponentA)).ToAction())), (15, Gen.Fresh(() => new RemoveComponent(typeof(IComponentB)).ToAction())), (15, Gen.Fresh(() => new RemoveComponent(typeof(IComponentC)).ToAction())), (15, Gen.Fresh(() => new RemoveComponent(typeof(ComponentC<>)).ToAction())), (5, Gen.Fresh(() => new EnableComponent<ComponentA>().ToAction())), (5, Gen.Fresh(() => new EnableComponent<ComponentB>().ToAction())), (5, Gen.Fresh(() => new EnableComponent<ComponentC<Unit>>().ToAction())), (5, Gen.Fresh(() => new EnableComponent<ComponentC<int>>().ToAction())), (5, Gen.Fresh(() => new EnableComponent(typeof(IComponentA)).ToAction())), (5, Gen.Fresh(() => new EnableComponent(typeof(IComponentB)).ToAction())), (5, Gen.Fresh(() => new EnableComponent(typeof(IComponentC)).ToAction())), (5, Gen.Fresh(() => new EnableComponent(typeof(ComponentC<>)).ToAction())), (5, Gen.Fresh(() => new DisableComponent<ComponentA>().ToAction())), (5, Gen.Fresh(() => new DisableComponent<ComponentB>().ToAction())), (5, Gen.Fresh(() => new DisableComponent<ComponentC<Unit>>().ToAction())), (5, Gen.Fresh(() => new DisableComponent<ComponentC<int>>().ToAction())), (5, Gen.Fresh(() => new DisableComponent(typeof(IComponentA)).ToAction())), (5, Gen.Fresh(() => new DisableComponent(typeof(IComponentB)).ToAction())), (5, Gen.Fresh(() => new DisableComponent(typeof(IComponentC)).ToAction())), (5, Gen.Fresh(() => new DisableComponent(typeof(ComponentC<>)).ToAction())), (4, Gen.Fresh(() => new CopyComponents().ToAction())), (2, Gen.Fresh(() => new CopyComponent<ComponentA>().ToAction())), (2, Gen.Fresh(() => new CopyComponent<ComponentB>().ToAction())), (2, Gen.Fresh(() => new CopyComponent<ComponentC<Unit>>().ToAction())), (2, Gen.Fresh(() => new CopyComponent<ComponentC<int>>().ToAction())), (2, Gen.Fresh(() => new CopyComponent<IComponentA>().ToAction())), (2, Gen.Fresh(() => new CopyComponent<IComponentB>().ToAction())), (2, Gen.Fresh(() => new CopyComponent<IComponentC>().ToAction())), (2, Gen.Fresh(() => new CopyComponent<IComponent>().ToAction())), (2, Gen.Fresh(() => new CopyComponent(typeof(ComponentB)).ToAction())), (2, Gen.Fresh(() => new CopyComponent(typeof(ComponentC<>)).ToAction())), (2, Gen.Fresh(() => new CopyComponent(typeof(IComponentC)).ToAction())), (2, Gen.Fresh(() => new CopyComponent(typeof(IComponent)).ToAction())), (5, Gen.Fresh(() => new TrimComponents().ToAction())), (1, Gen.Fresh(() => new ClearComponent<ComponentA>().ToAction())), (1, Gen.Fresh(() => new ClearComponent<ComponentB>().ToAction())), (1, Gen.Fresh(() => new ClearComponent<ComponentC<Unit>>().ToAction())), (1, Gen.Fresh(() => new ClearComponent<ComponentC<int>>().ToAction())), (1, Gen.Fresh(() => new ClearComponent(typeof(IComponentA)).ToAction())), (1, Gen.Fresh(() => new ClearComponent(typeof(IComponentB)).ToAction())), (1, Gen.Fresh(() => new ClearComponent(typeof(IComponentC)).ToAction())), (1, Gen.Fresh(() => new ClearComponent(typeof(ComponentC<>)).ToAction())), (1, Gen.Fresh(() => new ClearComponents().ToAction())), #endregion #region Families (25, Gen.Fresh(() => new AdoptEntity().ToAction())), (25, Gen.Fresh(() => new RejectEntity().ToAction())), #endregion #region Groups (1, Gen.Fresh(() => new GetGroup<Read<ComponentA>>().ToAction())), (1, Gen.Fresh(() => new GetGroup<All<Read<ComponentB>, Write<ComponentC<Unit>>>>().ToAction())), (1, Gen.Fresh(() => new GetGroup<Maybe<Read<ComponentA>>>().ToAction())), (1, Gen.Fresh(() => new GetGroup<Read<ComponentC<int>>>(typeof(ProviderA)).ToAction())), (1, Gen.Fresh(() => new GetGroup<QueryA>().ToAction())), (1, Gen.Fresh(() => new GetGroup<QueryB>().ToAction())), (1, Gen.Fresh(() => new GetGroup<QueryC>().ToAction())), (1, Gen.Fresh(() => new GetEntityGroup(typeof(ProviderB)).ToAction())), (1, Gen.Fresh(() => new GetEntityGroup(typeof(ProviderC)).ToAction())), (1, Gen.Fresh(() => new GetPointerGroup(typeof(ProviderA)).ToAction())), (1, Gen.Fresh(() => new GetPointerGroup().ToAction())), (1, Gen.Fresh(() => new GetGroup<Any<Write<ComponentC<Unit>>, Read<ComponentB>>>().ToAction())), #endregion #region Messages (1, Gen.Fresh(() => new EmitMessage<MessageA>().ToAction())), (1, Gen.Fresh(() => new EmitMessage<MessageB>().ToAction())), (1, Gen.Fresh(() => new EmitMessage<MessageC<string>>().ToAction())), #endregion #region Injectables (1, Gen.Fresh(() => new Inject(_injectables).ToAction())), (1, Gen.Fresh(() => new Inject<Components<ComponentA>>().ToAction())), (1, Gen.Fresh(() => new Inject<Components<ComponentB>.Read>().ToAction())), (1, Gen.Fresh(() => new Inject<Components<ComponentC<int>>.Write>().ToAction())), (1, Gen.Fresh(() => new Inject<Emitter<MessageA>>().ToAction())), (1, Gen.Fresh(() => new Inject<Reaction<MessageB>>().ToAction())), (1, Gen.Fresh(() => new Inject<Receiver<MessageC<string>>>().ToAction())), (1, Gen.Fresh(() => new Inject<Group<Entity>>().ToAction())), (1, Gen.Fresh(() => new Inject<Resource<ResourceA>>().ToAction())), (1, Gen.Fresh(() => new Inject<Resource<ResourceB>.Read>().ToAction())), (1, Gen.Fresh(() => new Inject<Injectable>().ToAction())), #endregion #region Systems (2, Gen.Fresh(() => new RunSystem<MessageA, MessageB>().ToAction())), (2, Gen.Fresh(() => new RunSystem<MessageB, MessageC<Unit>>().ToAction())), (2, Gen.Fresh(() => new RunSystem<MessageC<int>, MessageC<uint>>().ToAction())), (2, Gen.Fresh(() => new RunEachSystem<MessageA, MessageB, ComponentA, ComponentB>().ToAction())), (2, Gen.Fresh(() => new RunEachSystem<MessageB, MessageC<Unit>, ComponentB, ComponentC<Unit>>().ToAction())), (2, Gen.Fresh(() => new RunEachSystem<MessageC<int>, MessageC<uint>, ComponentC<Unit>, ComponentC<int>>().ToAction())), #endregion #region Queryables (1, Gen.Fresh(() => new Query(_queryables).ToAction())), #endregion #region Resolvables (5, Gen.Fresh(() => new Resolve().ToAction())) #endregion // Add non generic component actions ); var sequence = generator.ToSequence( random => (new World(), new Model(random)), (world, model) => PropertyUtility.All(Tests(world, model))); IEnumerable<(bool test, string label)> Tests(World world, Model model) { var entities = world.Entities(); var families = world.Families(); var components = world.Components(); #region World yield return (World.Instances().Contains(world), "World.Instances().Contains()"); yield return (World.TryInstance(world.Equals, out _), "World.TryInstance"); #endregion #region Entities yield return (entities.Count == model.Entities.Count, "Entities.Count"); yield return (entities.All(_ => _), "Entities.All()"); yield return (entities.All(model.Entities.Contains), "model.Entities.Contains()"); yield return (model.Entities.All(entities.Has), "entities.Has()"); yield return (entities.Distinct().SequenceEqual(entities), "entities.Distinct()"); #endregion #region Components IEnumerable<(bool test, string label)> WithInclude(States include) { yield return (components.Get(include).Count() == components.Count(include), $"Components.Get({include}).Count() == Components.Count({include})"); yield return (components.Get(include).Any() == components.Has(include), $"Components.Get({include}).Any() == Components.Has({include})"); yield return (components.Count(include) > 0 == components.Has(include), $"Components.Count({include}) > 0 == Components.Has({include})"); yield return (components.Count<IComponent>(include) >= entities.Count(entity => components.Has<IComponent>(entity, include)), $"components.Count(IComponent, {include}) >= entities.Components"); yield return (components.Count(typeof(IComponent), include) >= entities.Count(entity => components.Has(entity, typeof(IComponent), include)), $"components.Count(IComponent, {include}) >= entities.Components"); yield return (components.Count(include) == components.Count<IComponent>(include), $"components.Count({include}) == components.Count<IComponent>({include})"); yield return (components.Count<IComponent>(include) == components.Count(typeof(IComponent), include), $"Components.Count<IComponent>({include}) == Components.Count(IComponent, {include})"); yield return (entities.All(entity => components.Get(entity, include).All(component => components.Has(entity, component.GetType(), include))), $"entities.All(components.Has({include}))"); yield return (entities.All(entity => components.Get(entity, include).All(component => components.TryGet(entity, component.GetType(), out _, include))), $"entities.All(components.TryGet({include}))"); yield return (entities.All(entity => components.Get(entity, include).Count() == components.Count(entity, include)), $"entities.All(components.Get({include}).Count() == components.Count(Enabled))"); yield return (entities.Sum(entity => components.Count(entity, include)) == components.Count(include), $"entities.Sum({include}) == components.Count({include})"); } foreach (var pair in WithInclude(States.All)) yield return pair; foreach (var pair in WithInclude(States.None)) yield return pair; foreach (var pair in WithInclude(States.Enabled)) yield return pair; foreach (var pair in WithInclude(States.Disabled)) yield return pair; yield return (entities.All(entity => components.Get(entity, States.Enabled).None(component => components.Enable(entity, component.GetType()))), "entities.None(components.Enable())"); yield return (entities.All(entity => components.Get(entity, States.Disabled).None(component => components.Disable(entity, component.GetType()))), "entities.None(components.Disable())"); yield return (entities.All(entity => components.Get(entity).Count() == model.Components[entity].Count), "components.Get(entity).Count()"); yield return (entities.All(entity => components.Count(entity) == model.Components[entity].Count), "components.Count(entity)"); yield return (entities.All(entity => components.Get(entity).All(component => model.Components[entity].Contains(component.GetType()))), "model.Components.ContainsKey()"); yield return (model.Components.All(pair => pair.Value.All(type => components.Has(pair.Key, type))), "components.Has()"); #endregion #region Families var allFamilies = families.Roots().SelectMany(root => families.Family(root, From.Top)).ToArray(); yield return (entities.All(entity => families.Parent(entity) || families.Roots().Contains(entity)), "entities.All(Parent(entity) || families.Roots().Contains(entity))"); yield return (families.Roots().None(root => families.Parent(root)), "families.Roots().None(Parent(root))"); yield return (entities.All(entity => families.Parent(entity) == families.Ancestors(entity).FirstOrDefault()), "entities.All(families.Parent(entity) == families.Ancestors(entity).First())"); yield return (allFamilies.Except(entities).None(), "allFamilies.Except(entities).None()"); yield return (allFamilies.Distinct().SequenceEqual(allFamilies), "allFamilies.Distinct().SequenceEquals(allFamilies)"); yield return (entities.All(entity => families.Siblings(entity).All(sibling => families.Parent(sibling) == families.Parent(entity))), "families.Siblings(entity).All(Parent(sibling) == Parent(entity))"); yield return (entities.All(entity => families.Family(entity).Contains(entity)), "families.Family(entity).Contains(entity)"); #endregion #region Groups yield return (world.Groups().Count <= 30, "world.Groups().Count <= 30"); #endregion } var parallel = #if DEBUG 1; #else Environment.ProcessorCount; #endif var result = sequence.ToArbitrary().ToProperty(seed).Check("Tests", parallel, count: count, size: size); if (!result.success) { while (true) { Console.WriteLine(); Console.WriteLine($"'R' to restart, 'O' to replay orginal, 'S' to replay shrunk, 'X' to exit."); var line = Console.ReadLine(); Console.WriteLine(); switch (line) { case "r": case "R": Run(count, size); return; case "o": case "O": result.original.ToProperty(result.seed).QuickCheck("Replay Original"); break; case "s": case "S": result.shrunk.ToProperty(result.seed).QuickCheck("Replay Shrunk"); break; case "x": case "X": return; default: if (int.TryParse(line, out var random)) { Run(count, size, random); return; } break; } } } } } }
56.731266
229
0.56379
[ "MIT" ]
outerminds/Entia
Entia.Test/Tests.cs
21,957
C#
using System; using System.Collections; using System.Linq; using Cysharp.Threading.Tasks; using NSubstitute; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Mirage.Tests.Runtime.ClientServer { public class SampleBehaviorWithRpc : NetworkBehaviour { public event Action<NetworkIdentity> onSendNetworkIdentityCalled; public event Action<GameObject> onSendGameObjectCalled; public event Action<NetworkBehaviour> onSendNetworkBehaviourCalled; public event Action<SampleBehaviorWithRpc> onSendNetworkBehaviourDerivedCalled; public event Action<Weaver.Extra.SomeData> onSendTypeFromAnotherAssemblyCalled; [ClientRpc] public void SendNetworkIdentity(NetworkIdentity value) { onSendNetworkIdentityCalled?.Invoke(value); } [ClientRpc] public void SendGameObject(GameObject value) { onSendGameObjectCalled?.Invoke(value); } [ClientRpc] public void SendNetworkBehaviour(NetworkBehaviour value) { onSendNetworkBehaviourCalled?.Invoke(value); } [ClientRpc] public void SendNetworkBehaviourDerived(SampleBehaviorWithRpc value) { onSendNetworkBehaviourDerivedCalled?.Invoke(value); } [ServerRpc] public void SendNetworkIdentityToServer(NetworkIdentity value) { onSendNetworkIdentityCalled?.Invoke(value); } [ServerRpc] public void SendGameObjectToServer(GameObject value) { onSendGameObjectCalled?.Invoke(value); } [ServerRpc] public void SendNetworkBehaviourToServer(NetworkBehaviour value) { onSendNetworkBehaviourCalled?.Invoke(value); } [ServerRpc] public void SendNetworkBehaviourDerivedToServer(SampleBehaviorWithRpc value) { onSendNetworkBehaviourDerivedCalled?.Invoke(value); } [ClientRpc] public void SendTypeFromAnotherAssembly(Weaver.Extra.SomeData someData) { onSendTypeFromAnotherAssemblyCalled?.Invoke(someData); } } public class NetworkBehaviorRPCTest : ClientServerSetup<SampleBehaviorWithRpc> { [UnityTest] public IEnumerator SendNetworkIdentity() => UniTask.ToCoroutine(async () => { Action<NetworkIdentity> callback = Substitute.For<Action<NetworkIdentity>>(); clientComponent.onSendNetworkIdentityCalled += callback; serverComponent.SendNetworkIdentity(serverIdentity); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(clientIdentity); }); [UnityTest] public IEnumerator SendNetworkBehavior() => UniTask.ToCoroutine(async () => { Action<NetworkBehaviour> callback = Substitute.For<Action<NetworkBehaviour>>(); clientComponent.onSendNetworkBehaviourCalled += callback; serverComponent.SendNetworkBehaviour(serverComponent); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(clientComponent); }); [UnityTest] public IEnumerator SendNetworkBehaviorChild() => UniTask.ToCoroutine(async () => { Action<SampleBehaviorWithRpc> callback = Substitute.For<Action<SampleBehaviorWithRpc>>(); clientComponent.onSendNetworkBehaviourDerivedCalled += callback; serverComponent.SendNetworkBehaviourDerived(serverComponent); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(clientComponent); }); [UnityTest] public IEnumerator SendGameObject() => UniTask.ToCoroutine(async () => { Action<GameObject> callback = Substitute.For<Action<GameObject>>(); clientComponent.onSendGameObjectCalled += callback; serverComponent.SendGameObject(serverPlayerGO); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(clientPlayerGO); }); [Test] public void SendInvalidGO() { Action<GameObject> callback = Substitute.For<Action<GameObject>>(); clientComponent.onSendGameObjectCalled += callback; // this object does not have a NI, so this should error out Assert.Throws<InvalidOperationException>(() => { serverComponent.SendGameObject(serverGo); }); } [UnityTest] public IEnumerator SendNullNetworkIdentity() => UniTask.ToCoroutine(async () => { Action<NetworkIdentity> callback = Substitute.For<Action<NetworkIdentity>>(); clientComponent.onSendNetworkIdentityCalled += callback; serverComponent.SendNetworkIdentity(null); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(null); }); [UnityTest] public IEnumerator SendNullNetworkBehavior() => UniTask.ToCoroutine(async () => { Action<NetworkBehaviour> callback = Substitute.For<Action<NetworkBehaviour>>(); clientComponent.onSendNetworkBehaviourCalled += callback; serverComponent.SendNetworkBehaviour(null); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(null); }); [UnityTest] public IEnumerator SendNullNetworkBehaviorChild() => UniTask.ToCoroutine(async () => { Action<SampleBehaviorWithRpc> callback = Substitute.For<Action<SampleBehaviorWithRpc>>(); clientComponent.onSendNetworkBehaviourDerivedCalled += callback; serverComponent.SendNetworkBehaviourDerived(null); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(null); }); [UnityTest] public IEnumerator SendNullGameObject() => UniTask.ToCoroutine(async () => { Action<GameObject> callback = Substitute.For<Action<GameObject>>(); clientComponent.onSendGameObjectCalled += callback; serverComponent.SendGameObject(null); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(null); }); [UnityTest] public IEnumerator SendNetworkIdentityToServer() => UniTask.ToCoroutine(async () => { Action<NetworkIdentity> callback = Substitute.For<Action<NetworkIdentity>>(); serverComponent.onSendNetworkIdentityCalled += callback; clientComponent.SendNetworkIdentityToServer(clientIdentity); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(serverIdentity); }); [UnityTest] public IEnumerator SendNetworkBehaviorToServer() => UniTask.ToCoroutine(async () => { Action<NetworkBehaviour> callback = Substitute.For<Action<NetworkBehaviour>>(); serverComponent.onSendNetworkBehaviourCalled += callback; clientComponent.SendNetworkBehaviourToServer(clientComponent); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(serverComponent); }); [UnityTest] public IEnumerator SendNetworkBehaviorChildToServer() => UniTask.ToCoroutine(async () => { Action<SampleBehaviorWithRpc> callback = Substitute.For<Action<SampleBehaviorWithRpc>>(); serverComponent.onSendNetworkBehaviourDerivedCalled += callback; clientComponent.SendNetworkBehaviourDerivedToServer(clientComponent); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(serverComponent); }); [UnityTest] public IEnumerator SendTypeFromAnotherAssembly() => UniTask.ToCoroutine(async () => { Action<Weaver.Extra.SomeData> callback = Substitute.For<Action<Weaver.Extra.SomeData>>(); clientComponent.onSendTypeFromAnotherAssemblyCalled += callback; var someData = new Weaver.Extra.SomeData { usefulNumber = 13 }; serverComponent.SendTypeFromAnotherAssembly(someData); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(someData); }); [UnityTest] public IEnumerator SendGameObjectToServer() => UniTask.ToCoroutine(async () => { Action<GameObject> callback = Substitute.For<Action<GameObject>>(); serverComponent.onSendGameObjectCalled += callback; clientComponent.SendGameObjectToServer(clientPlayerGO); await UniTask.WaitUntil(() => callback.ReceivedCalls().Any()); callback.Received().Invoke(serverPlayerGO); }); [Test] public void SendInvalidGOToServer() { Action<GameObject> callback = Substitute.For<Action<GameObject>>(); serverComponent.onSendGameObjectCalled += callback; // this object does not have a NI, so this should error out Assert.Throws<InvalidOperationException>(() => { clientComponent.SendGameObjectToServer(clientGo); }); } } }
38.618474
101
0.645383
[ "MIT" ]
Uchiha1391/Mirage
Assets/Tests/Runtime/ClientServer/NetworkBehaviorRpcTest.cs
9,616
C#
using ApprovalWorkflow.Abstractions; namespace ApprovalWorkflow.Resolvers { public class PositionUserResolver : UserResolverBase { public PositionUserResolver(IApplicationDbContextFactory applicationDbContextFactory) : base(applicationDbContextFactory) { } public override Task<IEnumerable<IUser>> ResolveAsync(Guid id, CancellationToken cancellationToken) { throw new NotImplementedException(); } } }
27.166667
107
0.701431
[ "MIT" ]
vintorezsr/approval-workflow
src/ApprovalWorkflow/Resolvers/PositionUserResolver.cs
491
C#
using Shouldly; using Stryker.Core.Exceptions; using Stryker.Core.Options.Inputs; using Xunit; namespace Stryker.Core.UnitTest.Options.Inputs { public class ThresholdLowInputTests : TestBase { [Fact] public void ShouldHaveHelpText() { var target = new ThresholdLowInput(); target.HelpText.ShouldBe(@"Minimum acceptable mutation score. Must be less than or equal to threshold high and more than or equal to threshold break. | default: '60' | allowed: 0 - 100"); } [Theory] [InlineData(-1)] [InlineData(101)] public void MustBeBetween0and100(int thresholdLow) { var ex = Assert.Throws<InputException>(() => { var options = new ThresholdLowInput { SuppliedInput = thresholdLow }.Validate(@break: 0, high: 100); }); ex.Message.ShouldBe("Threshold low must be between 0 and 100."); } [Fact] public void MustBeLessthanOrEqualToThresholdHigh() { var ex = Assert.Throws<InputException>(() => { var options = new ThresholdLowInput { SuppliedInput = 61 }.Validate(@break: 60, high: 60); }); ex.Message.ShouldBe("Threshold low must be less than or equal to threshold high. Current low: 61, high: 60."); } [Fact] public void MustBeMoreThanThresholdBreak() { var ex = Assert.Throws<InputException>(() => { var options = new ThresholdLowInput { SuppliedInput = 59 }.Validate(@break: 60, high: 60); }); ex.Message.ShouldBe("Threshold low must be more than or equal to threshold break. Current low: 59, break: 60."); } [Fact] public void CanBeEqualToThresholdBreak() { var input = 60; var options = new ThresholdLowInput { SuppliedInput = input }.Validate(@break: 60, high: 100); options.ShouldBe(input); } [Fact] public void CanBeEqualToThresholdHigh() { var input = 60; var options = new ThresholdLowInput { SuppliedInput = input }.Validate(@break: 0, high: 60); options.ShouldBe(input); } [Fact] public void ShouldAllow0() { var input = 0; var options = new ThresholdLowInput { SuppliedInput = input }.Validate(@break: 0, high: 100); options.ShouldBe(input); } [Fact] public void ShouldAllow100() { var input = 100; var options = new ThresholdLowInput { SuppliedInput = input }.Validate(@break: 0, high: 100); options.ShouldBe(input); } [Fact] public void ShouldBeDefaultValueWhenNull() { var input = new ThresholdLowInput { SuppliedInput = null }; var options = input.Validate(@break: 0, high: 80); options.ShouldBe(input.Default.Value); } } }
33.922222
199
0.566983
[ "Apache-2.0" ]
AlexNDRmac/stryker-net
src/Stryker.Core/Stryker.Core.UnitTest/Options/Inputs/ThresholdLowInputTests.cs
3,053
C#
using System.Linq; using EssentialUIKit.Themes; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace EssentialUIKit.AppLayout { [Preserve(AllMembers = true)] public static class Extensions { public static void ApplyDarkTheme(this ResourceDictionary resources) { if (resources != null) { var mergedDictionaries = resources.MergedDictionaries; var lightTheme = mergedDictionaries.OfType<LightTheme>().FirstOrDefault(); if (lightTheme != null) { mergedDictionaries.Remove(lightTheme); } mergedDictionaries.Add(new DarkTheme()); AppSettings.Instance.IsDarkTheme = true; } } public static void ApplyLightTheme(this ResourceDictionary resources) { if (resources != null) { var mergedDictionaries = resources.MergedDictionaries; var darkTheme = mergedDictionaries.OfType<DarkTheme>().FirstOrDefault(); if (darkTheme != null) { mergedDictionaries.Remove(darkTheme); } mergedDictionaries.Add(new LightTheme()); AppSettings.Instance.IsDarkTheme = false; } } public static void ApplyColorSet(int index) { switch (index) { case 0: ApplyColorSet1(); break; case 1: ApplyColorSet2(); break; case 2: ApplyColorSet3(); break; case 3: ApplyColorSet4(); break; case 4: ApplyColorSet5(); break; } } public static void ApplyColorSet1() { Application.Current.Resources["PrimaryColor"] = Color.FromHex("#f54e5e"); Application.Current.Resources["PrimaryDarkColor"] = Color.FromHex("#d0424f"); Application.Current.Resources["PrimaryDarkenColor"] = Color.FromHex("#ab3641"); Application.Current.Resources["PrimaryLighterColor"] = Color.FromHex("#edcacd"); Application.Current.Resources["PrimaryLight"] = Color.FromHex("#ffe8f4"); Application.Current.Resources["PrimaryGradient"] = Color.FromHex("e83f94"); } public static void ApplyColorSet2() { Application.Current.Resources["PrimaryColor"] = Color.FromHex("#2f72e4"); Application.Current.Resources["PrimaryDarkColor"] = Color.FromHex("#1a5ac6"); Application.Current.Resources["PrimaryDarkenColor"] = Color.FromHex("#174fb0"); Application.Current.Resources["PrimaryLighterColor"] = Color.FromHex("#73a0ed"); Application.Current.Resources["PrimaryLight"] = Color.FromHex("#cdddf9"); Application.Current.Resources["PrimaryGradient"] = Color.FromHex("#00acff"); } public static void ApplyColorSet3() { Application.Current.Resources["PrimaryColor"] = Color.FromHex("#5d4cf7"); Application.Current.Resources["PrimaryDarkColor"] = Color.FromHex("#4b3ae1"); Application.Current.Resources["PrimaryDarkenColor"] = Color.FromHex("#3829ba"); Application.Current.Resources["PrimaryLighterColor"] = Color.FromHex("#b5aefb"); Application.Current.Resources["PrimaryLight"] = Color.FromHex("#eae8fe"); Application.Current.Resources["PrimaryGradient"] = Color.FromHex("#aa9cfc"); } public static void ApplyColorSet4() { Application.Current.Resources["PrimaryColor"] = Color.FromHex("#06846a"); Application.Current.Resources["PrimaryDarkColor"] = Color.FromHex("#056c56"); Application.Current.Resources["PrimaryDarkenColor"] = Color.FromHex("#045343"); Application.Current.Resources["PrimaryLighterColor"] = Color.FromHex("#98f0de"); Application.Current.Resources["PrimaryLight"] = Color.FromHex("#ebf9f7"); Application.Current.Resources["PrimaryGradient"] = Color.FromHex("#0ed342"); } public static void ApplyColorSet5() { Application.Current.Resources["PrimaryColor"] = Color.FromHex("#d54008"); Application.Current.Resources["PrimaryDarkColor"] = Color.FromHex("#a43106"); Application.Current.Resources["PrimaryDarkenColor"] = Color.FromHex("#862805"); Application.Current.Resources["PrimaryLighterColor"] = Color.FromHex("#fa9e7c"); Application.Current.Resources["PrimaryLight"] = Color.FromHex("#fee7de"); Application.Current.Resources["PrimaryGradient"] = Color.FromHex("#ff6374"); } } }
42.982609
92
0.585677
[ "MIT" ]
MohanlalGo/essential-ui-kit-for-xamarin.forms
EssentialUIKit/AppLayout/Utils.cs
4,945
C#
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace demoazurefunction { public static class DemoAzureFunction { [FunctionName("DemoAzureFunction")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string name = req.Query["name"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); name = name ?? data?.name; string responseMessage = string.IsNullOrEmpty(name) ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response." : $"Hello, {name}. This HTTP triggered function executed successfully."; return new OkObjectResult(responseMessage); } } }
36.583333
156
0.661352
[ "MIT" ]
MCKLMT/demoazurefunction
AzureFunction/DemoAzureFunction.cs
1,317
C#
using Bytes2you.Validation; using IzgodnoKupi.Data.Contracts; using IzgodnoKupi.Data.Model; using IzgodnoKupi.Data.Model.Enums; using IzgodnoKupi.Services.Contracts; using Microsoft.EntityFrameworkCore; using System.Linq; namespace IzgodnoKupi.Services { public class BagService : IBagService { private readonly ISaveContext context; private readonly IEfRepository<Order> ordersRepo; public BagService(IEfRepository<Order> ordersRepo, ISaveContext context) { Guard.WhenArgument(ordersRepo, "ordersRepo").IsNull().Throw(); Guard.WhenArgument(context, "context").IsNull().Throw(); this.ordersRepo = ordersRepo; this.context = context; } public decimal TotalAmount(string id) { var result = this.ordersRepo.All .Where(c => c.UserId == id) .Include(x => x.OrderItems) .FirstOrDefault(c => c.OrderStatus == OrderStatus.NotCompleted); if (result == null) { return 0m; } return result.TotalAmountInclTax; } public int Count(string id) { var result = this.ordersRepo.All .Where(c => c.UserId == id) .Include(x => x.OrderItems) .FirstOrDefault(c => c.OrderStatus == OrderStatus.NotCompleted); if (result == null) { return 0; } return result.OrderItems.Count; } } }
29.254545
88
0.55376
[ "MIT" ]
Camyul/Izgodno-Kupi
IzgodnoKupi/IzgodnoKupi.Services/BagService.cs
1,611
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.RecoveryServices.Latest { [Obsolete(@"The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-nextgen:recoveryservices:getReplicationMigrationItem'.")] public static class GetReplicationMigrationItem { /// <summary> /// Migration item. /// Latest API Version: 2018-07-10. /// </summary> public static Task<GetReplicationMigrationItemResult> InvokeAsync(GetReplicationMigrationItemArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetReplicationMigrationItemResult>("azure-nextgen:recoveryservices/latest:getReplicationMigrationItem", args ?? new GetReplicationMigrationItemArgs(), options.WithVersion()); } public sealed class GetReplicationMigrationItemArgs : Pulumi.InvokeArgs { /// <summary> /// Fabric unique name. /// </summary> [Input("fabricName", required: true)] public string FabricName { get; set; } = null!; /// <summary> /// Migration item name. /// </summary> [Input("migrationItemName", required: true)] public string MigrationItemName { get; set; } = null!; /// <summary> /// Protection container name. /// </summary> [Input("protectionContainerName", required: true)] public string ProtectionContainerName { get; set; } = null!; /// <summary> /// The name of the resource group where the recovery services vault is present. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the recovery services vault. /// </summary> [Input("resourceName", required: true)] public string ResourceName { get; set; } = null!; public GetReplicationMigrationItemArgs() { } } [OutputType] public sealed class GetReplicationMigrationItemResult { /// <summary> /// Resource Id /// </summary> public readonly string Id; /// <summary> /// Resource Location /// </summary> public readonly string? Location; /// <summary> /// Resource Name /// </summary> public readonly string Name; /// <summary> /// The migration item properties. /// </summary> public readonly Outputs.MigrationItemPropertiesResponse Properties; /// <summary> /// Resource Type /// </summary> public readonly string Type; [OutputConstructor] private GetReplicationMigrationItemResult( string id, string? location, string name, Outputs.MigrationItemPropertiesResponse properties, string type) { Id = id; Location = location; Name = name; Properties = properties; Type = type; } } }
31.962264
228
0.606257
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/RecoveryServices/Latest/GetReplicationMigrationItem.cs
3,388
C#
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using GOAP.Framework.Internal; using GOAP.Helper; namespace GOAP.Framework { [Serializable] abstract public class PEParameter { [SerializeField] private string _name; [SerializeField] private string WSVariableID; [NonSerialized] private IWorldState _worldState; [NonSerialized] private WSVariable variable_reference; private Operator _myOperator = new Operator(); public object value { get { return objectValue; } set { objectValue = value; } } abstract protected object objectValue { get; set; } abstract public Type variableType { get; } //TODO:CHECK LATER public PEParameter() { } public string name { get { if (variable_reference != null) { if (_name != variable_reference.name) _name = variable_reference.name; return _name; } if (!string.IsNullOrEmpty(_name)) { return _name; } return null; } set { if (_name != value) { _name = value; } } } public IWorldState worldState { get { return _worldState; } set { if (_worldState != value) { if (_worldState != null) { _worldState.onVariableAdded -= OnWSVariableAdded; _worldState.onVariableRemoved -= OnWSVariableRemoved; } if (value != null) { value.onVariableAdded += OnWSVariableAdded; value.onVariableRemoved += OnWSVariableRemoved; } _worldState = value; variableReference = value != null ? ResolveReference(_worldState, true) : null; } } } void OnWSVariableAdded(WSVariable variable) { if (variable.name == this.name && variable.CanConvertTo(variableType)) variableReference = variable; } void OnWSVariableRemoved(WSVariable variable) { if (variable == variableReference) variableReference = null; } public WSVariable variableReference { get { if (isValid) return variable_reference; return null; } set { if (variableReference != value) { variable_reference = value; name = variable_reference != null ? variable_reference.name : null; } } } public bool isValid { get { if (variable_reference == null || string.IsNullOrEmpty(name)) { return false; } return true; } } public bool isNone { get { return name == string.Empty; } } public string operatorSymbol { get { return _myOperator.symbol; } } public Operator myOperator { get { return _myOperator; } } public bool DoOperator() { return true; } private WSVariable ResolveReference(IWorldState target_world_state, bool use_id) { string target_name = name; if (target_name != null && target_name.Contains("/")) { string[] split = target_name.Split('/'); } WSVariable ret = null; if (target_world_state == null) return null; if (use_id && WSVariableID != null) ret = target_world_state.GetVariableByID(WSVariableID); if (ret == null && !string.IsNullOrEmpty(target_name)) { ret = target_world_state.GetVariable(target_name, variableType); } return ret; } } [Serializable] public class PEParameter<T> : PEParameter { [SerializeField] private T _value; protected override object objectValue { get { return value; } set { this.value = (T)value; } } new public T value { get { return _value; } set { _value = value; } } public override Type variableType { get { return typeof(T); } } public T GetValue() { return value; } public void SetValue(T new_value) { value = new_value; } } [Serializable] public class PEMethod { [SerializeField] private string _name; [SerializeField] private string _WSMethodID; [SerializeField] private bool _value; [SerializeField] private List<WSParameter> _arguments = new List<WSParameter>(); [NonSerialized] private WSFunctionVariable _methodReference = null; [NonSerialized] private IWorldState _worldState; private Operator _myOperator = new Operator(); public string name { get { if (_methodReference != null) { if (_name != _methodReference.name) _name = _methodReference.name; return _name; } if (!string.IsNullOrEmpty(_name)) { return _name; } return null; } set { if (_name != value) { _name = value; } } } public Operator myOperator { get { return _myOperator; } } public WSFunctionVariable methodReference { get { return _methodReference; } set { if(_methodReference!=value) { _methodReference = value; var parameters = _methodReference.methodInfo.GetParameters(); if (parameters.Length != arguments.Count) { GenerateParameters(parameters); } else { if(!ParametersEquals(parameters)) { GenerateParameters(parameters); } } } } } void GenerateParameters(ParameterInfo[] parameters) { arguments.Clear(); foreach (ParameterInfo parameter in parameters) { var data_type = typeof(WSParameter<>).RHelperGenericType(new Type[] { parameter.ParameterType }); var newData = (WSParameter)Activator.CreateInstance(data_type); _arguments.Add(newData); } } bool ParametersEquals(ParameterInfo[] parameters) { for(int i =0;i< parameters.Length;i++) { if(!parameters[i].ParameterType.Equals(arguments[i].variableType)) { return false; } } return true; } protected bool objectValue { get { return value; } set { this.value = value; } } public bool value { get { return _value; } set { _value = value; } } public bool isValid { get { if (methodReference == null || string.IsNullOrEmpty(name)) { return false; } return true; } } public IWorldState worldState { get { return _worldState; } set { if (_worldState != value) { if (_worldState != null) { _worldState.onFunctionVariableAdded -= OnWSFunctionVariableAdded; _worldState.onFunctionVariableRemoved -= OnWSFunctionVariableRemoved; } if (value != null) { value.onFunctionVariableAdded += OnWSFunctionVariableAdded; value.onFunctionVariableRemoved += OnWSFunctionVariableRemoved; } _worldState = value; methodReference = value != null ? ResolveReference(_worldState, true) : null; foreach(var item in arguments) { item.worldState = _worldState; } } } } public List<WSParameter> arguments { get { return _arguments; } } private WSVariableParameter target { get { return methodReference.target; } } void OnWSFunctionVariableAdded(WSFunctionVariable method) { if (method.name == this.name) methodReference = method; } void OnWSFunctionVariableRemoved(WSFunctionVariable method) { if (method == methodReference) methodReference = null; } public bool InvokeMethod() { return (bool)_methodReference.methodInfo.Invoke(target, GetArguments()); } private WSFunctionVariable ResolveReference(IWorldState targetWorldState, bool use_id) { string targetName = name; if (targetName != null && targetName.Contains("/")) { string[] split = targetName.Split('/'); } WSFunctionVariable ret = null; if (targetWorldState == null) return null; if (use_id && _WSMethodID != null) ret = targetWorldState.GetFunctionVariableByID(_WSMethodID); if (ret == null && !string.IsNullOrEmpty(targetName)) { ret = targetWorldState.GetFunctionVariable(targetName); } return ret; } private WSVariable ResolveVariableReference(IWorldState targetWorldState, bool use_id,int index) { string targetName = name; if (targetName != null && targetName.Contains("/")) { string[] split = targetName.Split('/'); } WSVariable ret = null; if (targetWorldState == null) return null; if (use_id && _WSMethodID != null) ret = targetWorldState.GetVariableByID(_WSMethodID); if (ret == null && !string.IsNullOrEmpty(targetName)) { ret = targetWorldState.GetVariable(targetName); } return ret; } public bool IsMethodValid() { return value == InvokeMethod(); } public object[] GetArguments() { if (arguments.Count < 0) return null; object[] param = new object[arguments.Count]; for(int i = 0;i<arguments.Count;i++) { param[i] = arguments[i].value; } return param; } } }
27.0375
113
0.431499
[ "MIT" ]
Jergar92/TFP-GOAP
Assets/GOAPFramework/Scripts/GOAP/WorldState/PEParameter.cs
12,980
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace GameLauncher { static class Program { /// <summary> /// 해당 응용 프로그램의 주 진입점입니다. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
21.347826
65
0.600815
[ "MIT" ]
pwerty/PoreLauncher
GameLauncher/Program.cs
525
C#
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GameController : MonoBehaviour { public GameObject hazard; public Vector3 spawnValues; public int hazardCount; public float spawnWait; public float startWait; public float waveWait; public GameObject scoreLabel; public Text scoreLabelText; public int score; void Start() { scoreLabelText = scoreLabel.GetComponent<Text>(); score = 0; UpdateScore (); StartCoroutine(SpawnWaves ()); } public void AddScore (int newScoreValue) { score += newScoreValue; UpdateScore (); } void UpdateScore () { scoreLabelText.text = "Score: " + score; } IEnumerator SpawnWaves() { yield return new WaitForSeconds (startWait); while(true) { for (int i = 0; i < hazardCount; i++) { Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z); Quaternion spawnRotation = Quaternion.identity; Instantiate (hazard, spawnPosition, spawnRotation); yield return new WaitForSeconds (spawnWait); } yield return new WaitForSeconds (waveWait); } } }
20.285714
117
0.715669
[ "MIT" ]
dimitardanailov/space-shooter-tutorial
Assets/Scripts/GameController.cs
1,138
C#
using System.Collections.Generic; namespace Typewriter.CodeModel.Collections { public class ParameterCollectionImpl : ItemCollectionImpl<Parameter>, ParameterCollection { public ParameterCollectionImpl(IEnumerable<Parameter> values) : base(values) { } protected override IEnumerable<string> GetAttributeFilter(Parameter item) { foreach (var attribute in item.Attributes) { yield return attribute.Name; yield return attribute.FullName; } } protected override IEnumerable<string> GetItemFilter(Parameter item) { yield return item.Name; yield return item.FullName; } } }
28.730769
93
0.625167
[ "Apache-2.0" ]
Ackhuman/Typewriter
src/Typewriter/CodeModel/Collections/ParameterCollectionImpl.cs
749
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.IO; using Microsoft.Xml; namespace System.ServiceModel.Channels { internal abstract class BufferedMessageWriter { private int[] _sizeHistory; private int _sizeHistoryIndex; private const int sizeHistoryCount = 4; private const int expectedSizeVariance = 256; private BufferManagerOutputStream _stream; public BufferedMessageWriter() { _stream = new BufferManagerOutputStream(SRServiceModel.MaxSentMessageSizeExceeded); InitMessagePredicter(); } protected abstract XmlDictionaryWriter TakeXmlWriter(Stream stream); protected abstract void ReturnXmlWriter(XmlDictionaryWriter writer); public ArraySegment<byte> WriteMessage(Message message, BufferManager bufferManager, int initialOffset, int maxSizeQuota) { int effectiveMaxSize; // make sure that maxSize has room for initialOffset without overflowing, since // the effective buffer size is message size + initialOffset if (maxSizeQuota <= int.MaxValue - initialOffset) effectiveMaxSize = maxSizeQuota + initialOffset; else effectiveMaxSize = int.MaxValue; int predictedMessageSize = PredictMessageSize(); if (predictedMessageSize > effectiveMaxSize) predictedMessageSize = effectiveMaxSize; else if (predictedMessageSize < initialOffset) predictedMessageSize = initialOffset; try { _stream.Init(predictedMessageSize, maxSizeQuota, effectiveMaxSize, bufferManager); _stream.Skip(initialOffset); XmlDictionaryWriter writer = TakeXmlWriter(_stream); OnWriteStartMessage(writer); message.WriteMessage(writer); OnWriteEndMessage(writer); writer.Flush(); ReturnXmlWriter(writer); int size; byte[] buffer = _stream.ToArray(out size); RecordActualMessageSize(size); return new ArraySegment<byte>(buffer, initialOffset, size - initialOffset); } finally { _stream.Clear(); } } protected virtual void OnWriteStartMessage(XmlDictionaryWriter writer) { } protected virtual void OnWriteEndMessage(XmlDictionaryWriter writer) { } private void InitMessagePredicter() { _sizeHistory = new int[4]; for (int i = 0; i < sizeHistoryCount; i++) _sizeHistory[i] = 256; } private int PredictMessageSize() { int max = 0; for (int i = 0; i < sizeHistoryCount; i++) if (_sizeHistory[i] > max) max = _sizeHistory[i]; return max + expectedSizeVariance; } private void RecordActualMessageSize(int size) { _sizeHistory[_sizeHistoryIndex] = size; _sizeHistoryIndex = (_sizeHistoryIndex + 1) % sizeHistoryCount; } } }
35.072165
129
0.605526
[ "MIT" ]
Bencargs/wcf
src/dotnet-svcutil/lib/src/FrameworkFork/System.ServiceModel/System/ServiceModel/Channels/BufferedMessageWriter.cs
3,402
C#
using System.Reflection; 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("SampleWeb")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("SampleWeb")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [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("aeaa2b05-e3d1-4cbc-8390-34e44143a645")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38
84
0.747368
[ "Apache-2.0" ]
DamianEdwards/dotnet
Sample.Mvc/Properties/AssemblyInfo.cs
1,333
C#
using System; using System.Reflection; namespace DataAPI.Areas.HelpPage.ModelDescriptions { public interface IModelDocumentationProvider { string GetDocumentation(MemberInfo member); string GetDocumentation(Type type); } }
21
51
0.746032
[ "Apache-2.0" ]
mathias1902/InfoShopping
InfoShopping/DataAPI/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs
252
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; using UnityEngine.UI; using Random = UnityEngine.Random; using TMPro; namespace SupremumStudio { public class QuizView : MonoBehaviour { public TextMeshProUGUI QuestionText; public Text[] Answer; public Button[] AnswerButton; public Quiz Quiz; public Animator VictorineZone; public float TimeForQuestion, CurrentTime, DeltaTime; public bool QuestionIsOn = false; public bool? IsCorrectAnswer { get; private set; } public event Action<float> CorrectAnswer; public event Action InCorrectAnswer; public GameObject TextTable; private Color Red = new Color(0.6862745f, 0f, 0f, 1f); private Color Orange = new Color(1, 0.4117647f, 0, 1f); private Color Green = new Color(0.01176471f, 0.6862745f, 0.01176471f, 1f); private Color Standart = new Color(0, 0, 0, 0.7843137f); public Slider Timer; public void SetSliderMaxValue() { Timer.maxValue = 550; Timer.value = TimeForQuestion * 100; } public void SetSliderValue() { Timer.value = TimeForQuestion * 100; } public void ResetSliderValue() { Timer.value = 550; } public void AnimationOn() { VictorineZone.SetTrigger("on"); } public void IsCorrectAnswerFalse() { IsCorrectAnswer = null; } //public void AnimationOff() //{ // Quiz.VictorineZone.SetTrigger("off"); //} private void Start() { SetSliderMaxValue(); Quiz.QuestionChanged += Quiz_QuestionChanged; TimeForQuestion = 5.5f; Quiz.ReadQuestions(); //SetQuestion(); // Можно использовать из другого класса foreach (var item in AnswerButton) // TODO: not work in for { item.onClick.AddListener(() => { if (item.GetComponentInChildren<Text>().text == Quiz.currentAnswer) //TODO: переосмыслить { CorrectAnswer(SendScore()); //AnimationOff(); IsCorrectAnswer = true; //QuestinIsTrueOff(); //ResetTime(); //item.GetComponentInChildren<Image>().color = Color.yellow; item.GetComponentInChildren<Image>().color = Orange; } else { InCorrectAnswer(); // AnimationOff(); IsCorrectAnswer = false; //QuestinIsTrueOff(); //ResetTime(); item.GetComponentInChildren<Image>().color = Orange; } }); } } private void Quiz_QuestionChanged() { //AnimationOn(); var data = Quiz.GetQuestionData(); SetQuiz(data.Item1, data.Item2); //IsCorrectAnswer = null; } public void ResetColors() { for (int i = 0; i <= 2; i++) { AnswerButton[i].GetComponentInChildren<Image>().color = Standart; } TextTable.GetComponentInChildren<Image>().color = Standart; } public void SetColorGreen() { foreach (var item in AnswerButton) // TODO: not work in for { if (item.GetComponentInChildren<Text>().text == Quiz.currentAnswer) //TODO: переосмыслить { item.GetComponentInChildren<Image>().color = Green; } } } public void SetColorRed() { foreach (var item in AnswerButton) // TODO: not work in for { if (item.GetComponentInChildren<Text>().text != Quiz.currentAnswer && item.GetComponentInChildren<Image>().color == Orange) //TODO: переосмыслить { item.GetComponentInChildren<Image>().color = Red; } } } public void RedText() { TextTable.GetComponentInChildren<Image>().color = Red; } public void ResetTime() { TimeForQuestion = 5.5f; CurrentTime = 0; } public void QuestinIsTrueOn() { QuestionIsOn = true; } public void QuestinIsTrueOff() { QuestionIsOn = false; } public void CalcTime() { TimeForQuestion -= Time.deltaTime; //CurrentTime += Time.deltaTime; DeltaTime = TimeForQuestion /*- CurrentTime*/; if (DeltaTime < 0) { DeltaTime = 0; } } public float SendScore() { return DeltaTime; } private void Update() { //print(TimeForQuestion); //print(CurrentTime); //print(DeltaTime); if (QuestionIsOn == true) { CalcTime(); SetSliderValue(); } } //private void ReadQuestion() //{ // var JsonQuestion = Resources.Load<TextAsset>("Questions/Question"); // прочитать файл // questions = Newtonsoft.Json.JsonConvert.DeserializeObject<List<QuestionModel>>(JsonQuestion.ToString()); // распознать его // countQuestionFile = questions.Count; // Debug.Log("Count Question: " + countQuestionFile); // Shuffle(questions); // перемешать вопросы //} //private void SetQuestion() //{ // SetQuiz(questions[CurrentQuestion].TextQuestion, questions[CurrentQuestion].Answer); // currentAnswer = questions[CurrentQuestion].Answer[0]; //} //public void NextQuestion() //{ // AnimationOn(); // CurrentQuestion++; // SetQuestion(); //} public void SetQuiz(string questionText, string[] answer) { QuestionText.text = questionText; // установить вопрос for (int i = 0; i < answer.Length; i++) { Answer[i].text = answer[i]; // установить ответы } Shuffle(Answer); } public void Shuffle(Text[] answer) { for (int i = 0; i < answer.Length; i++) { int r = Random.Range(0, answer.Length); var t = answer[i].text; answer[i].text = answer[r].text; answer[r].text = t; } } //public void Shuffle(List<QuestionModel> model) //{ // for (int i = 0; i < model.Count; i++) // { // int r = Random.Range(0, model.Count); // var t = model[i]; // model[i] = model[r]; // model[r] = t; // } //} //private void OnDisable() //{ // foreach (var item in AnswerButton) // { // item.onClick.RemoveAllListeners(); // отписаться от всех событий // } //} } }
29.748031
161
0.491795
[ "MIT" ]
NikolayRomanow/DodoPizzaGame
Assets/Scripts/Runner/Fix/QuizView.cs
7,727
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using Steeltoe.Common.Reflection; using Steeltoe.Connector.Services; using System; using System.Reflection; namespace Steeltoe.Connector.Redis; public class RedisServiceConnectorFactory { private readonly RedisServiceInfo _info; private readonly RedisCacheConnectorOptions _config; private readonly RedisCacheConfigurer _configurer = new (); /// <summary> /// Initializes a new instance of the <see cref="RedisServiceConnectorFactory"/> class. /// Factory for creating Redis connections with either Microsoft.Extensions.Caching.Redis or StackExchange.Redis /// </summary> /// <param name="sinfo">Service Info</param> /// <param name="config">Service Configuration</param> /// <param name="connectionType">Redis connection Type</param> /// <param name="optionsType">Options Type used to establish connection</param> /// <param name="initalizer">Method used to open connection</param> public RedisServiceConnectorFactory(RedisServiceInfo sinfo, RedisCacheConnectorOptions config, Type connectionType, Type optionsType, MethodInfo initalizer) { _info = sinfo; _config = config ?? throw new ArgumentNullException(nameof(config), "Cache connector options must be provided"); ConnectorType = connectionType; OptionsType = optionsType; Initializer = initalizer; } /// <summary> /// Get the connection string from Configuration sources /// </summary> /// <returns>Connection String</returns> public string GetConnectionString() { var connectionOptions = _configurer.Configure(_info, _config); return connectionOptions.ToString(); } protected Type ConnectorType { get; set; } protected Type OptionsType { get; set; } protected MethodInfo Initializer { get; set; } /// <summary> /// Open the Redis connection /// </summary> /// <param name="provider">IServiceProvider</param> /// <returns>Initialized Redis connection</returns> public virtual object Create(IServiceProvider provider) { var connectionOptions = _configurer.Configure(_info, _config); var result = Initializer == null ? CreateConnection(connectionOptions.ToMicrosoftExtensionObject(OptionsType)) : CreateConnectionByMethod(connectionOptions.ToStackExchangeObject(OptionsType)); return result; } private object CreateConnection(object options) { return ReflectionHelpers.CreateInstance(ConnectorType, new[] { options }); } private object CreateConnectionByMethod(object options) { return Initializer.Invoke(ConnectorType, new[] { options, null }); } }
37.230769
160
0.711777
[ "Apache-2.0" ]
SteeltoeOSS/steeltoe
src/Connectors/src/ConnectorBase/Redis/RedisServiceConnectorFactory.cs
2,904
C#
using System; using System.Linq; using Microsoft.ML.Data; using Microsoft.ML.LightGBM; using Microsoft.ML.SamplesUtils; using static Microsoft.ML.LightGBM.Options; namespace Microsoft.ML.Samples.Dynamic.Trainers.MulticlassClassification { class LightGbmWithOptions { // This example requires installation of additional nuget package <a href="https://www.nuget.org/packages/Microsoft.ML.LightGBM/">Microsoft.ML.LightGBM</a>. public static void Example() { // Create a general context for ML.NET operations. It can be used for exception tracking and logging, // as a catalog of available operations and as the source of randomness. var mlContext = new MLContext(seed: 0); // Create in-memory examples as C# native class. var examples = DatasetUtils.GenerateRandomMulticlassClassificationExamples(1000); // Convert native C# class to IDataView, a consumble format to ML.NET functions. var dataView = mlContext.Data.LoadFromEnumerable(examples); //////////////////// Data Preview //////////////////// // Label Features // AA 0.7262433,0.8173254,0.7680227,0.5581612,0.2060332,0.5588848,0.9060271,0.4421779,0.9775497,0.2737045 // BB 0.4919063,0.6673147,0.8326591,0.6695119,1.182151,0.230367,1.06237,1.195347,0.8771811,0.5145918 // CC 1.216908,1.248052,1.391902,0.4326252,1.099942,0.9262842,1.334019,1.08762,0.9468155,0.4811099 // DD 0.7871246,1.053327,0.8971719,1.588544,1.242697,1.362964,0.6303943,0.9810045,0.9431419,1.557455 // Create a pipeline. // - Convert the string labels into key types. // - Apply LightGbm multiclass trainer with advanced options. var pipeline = mlContext.Transforms.Conversion.MapValueToKey("LabelIndex", "Label") .Append(mlContext.MulticlassClassification.Trainers.LightGbm(new Options { LabelColumnName = "LabelIndex", FeatureColumnName = "Features", Booster = new DartBooster.Options { DropRate = 0.15, XgboostDartMode = false } })) .Append(mlContext.Transforms.Conversion.MapValueToKey("PredictedLabelIndex", "PredictedLabel")) .Append(mlContext.Transforms.CopyColumns("Scores", "Score")); // Split the static-typed data into training and test sets. Only training set is used in fitting // the created pipeline. Metrics are computed on the test. var split = mlContext.MulticlassClassification.TrainTestSplit(dataView, testFraction: 0.5); // Train the model. var model = pipeline.Fit(split.TrainSet); // Do prediction on the test set. var dataWithPredictions = model.Transform(split.TestSet); // Evaluate the trained model using the test set. var metrics = mlContext.MulticlassClassification.Evaluate(dataWithPredictions, label: "LabelIndex"); // Check if metrics are reasonable. Console.WriteLine($"Macro accuracy: {metrics.MacroAccuracy:F4}, Micro accuracy: {metrics.MicroAccuracy:F4}."); // Console output: // Macro accuracy: 0.8619, Micro accuracy: 0.8611. // IDataView with predictions, to an IEnumerable<DatasetUtils.MulticlassClassificationExample>. var nativePredictions = mlContext.Data.CreateEnumerable<DatasetUtils.MulticlassClassificationExample>(dataWithPredictions, false).ToList(); // Get schema object out of the prediction. It contains metadata such as the mapping from predicted label index // (e.g., 1) to its actual label (e.g., "AA"). // The metadata can be used to get all the unique labels used during training. var labelBuffer = new VBuffer<ReadOnlyMemory<char>>(); dataWithPredictions.Schema["PredictedLabelIndex"].GetKeyValues(ref labelBuffer); // nativeLabels is { "AA" , "BB", "CC", "DD" } var nativeLabels = labelBuffer.DenseValues().ToArray(); // nativeLabels[nativePrediction.PredictedLabelIndex - 1] is the original label indexed by nativePrediction.PredictedLabelIndex. // Show prediction result for the 3rd example. var nativePrediction = nativePredictions[2]; // Console output: // Our predicted label to this example is AA with probability 0.8986. Console.WriteLine($"Our predicted label to this example is {nativeLabels[(int)nativePrediction.PredictedLabelIndex - 1]} " + $"with probability {nativePrediction.Scores[(int)nativePrediction.PredictedLabelIndex - 1]:F4}."); // Scores and nativeLabels are two parallel attributes; that is, Scores[i] is the probability of being nativeLabels[i]. // Console output: // The probability of being class AA is 0.8986. // The probability of being class BB is 0.0961. // The probability of being class CC is 0.0050. // The probability of being class DD is 0.0003. for (int i = 0; i < nativeLabels.Length; ++i) Console.WriteLine($"The probability of being class {nativeLabels[i]} is {nativePrediction.Scores[i]:F4}."); } } }
57.639175
196
0.626185
[ "MIT" ]
endintiers/machinelearning
docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/MulticlassClassification/LightGbmWithOptions.cs
5,593
C#
namespace Arianrhod { public enum Direction { Up, Right, Down, Left, } }
11.6
25
0.448276
[ "MIT" ]
sai-maple/Arianrhod
Assets/Arianrhod/Scripts/Common/Enums/Direction.cs
116
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } } }
15.52381
44
0.59816
[ "Apache-2.0" ]
zhouweiaccp/mvc5
MvcApplication/Controllers/HomeController.cs
328
C#