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
namespace SoftLegion.Common.Core.Paging { public class Pager { public int PageNumber { get; set; } public int PageSize { get; set; } public int RecordsCount { get; set; } public int TotalRecordsCount { get; set; } public int PagesCount { get; set; } } }
23.615385
50
0.596091
[ "MIT" ]
SoftLegion/SoftLegion-Tools
SoftLegion.Common/Core/Paging/Pager.cs
307
C#
// //----------------------------------------------------------------------- // // <copyright file="EWMASpec.cs" company="Akka.NET Project"> // // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // // </copyright> // //----------------------------------------------------------------------- using System; using System.Linq; using Akka.Cluster.Metrics.Serialization; using Akka.Cluster.Metrics.Tests.Helpers; using Akka.TestKit; using FluentAssertions; using Xunit; namespace Akka.Cluster.Metrics.Tests { public class EWMASpec : AkkaSpec { public EWMASpec() : base(ClusterMetricsTestConfig.ClusterConfiguration) { } [Fact] public void EWMA_should_be_same_for_constant_values() { var e = new NodeMetrics.Types.EWMA(100, 0.18) + 100 + 100 + 100; e.Value.Should().BeApproximately(100, 0.001); } [Fact] public void EWMA_should_calculate_correct_ewma_for_normal_decay() { var e0 = new NodeMetrics.Types.EWMA(1000, 2.0 / (1 + 10)); e0.Value.Should().BeApproximately(1000, 0.01); var e1 = e0 + 10.0; e1.Value.Should().BeApproximately(820.0, 0.01); var e2 = e1 + 10.0; e2.Value.Should().BeApproximately (672.73, 0.01); var e3 = e2 + 10.0; e3.Value.Should().BeApproximately(552.23, 0.01); var e4 = e3 + 10.0; e4.Value.Should().BeApproximately(453.64, 0.01); var en = Enumerable.Range(1, 100).Aggregate(e0, (e, _) => e + 10.0); en.Value.Should().BeApproximately(10.0, 0.1); } [Fact] public void EWMA_should_calculate_for_alpha_1_0_and_max_bias_towards_latest_value() { var e0 = new NodeMetrics.Types.EWMA(100, 1.0); e0.Value.Should().BeApproximately(100, 0.01); var e1 = e0 + 1; e1.Value.Should().BeApproximately(1, 0.01); var e2 = e1 + 57; e2.Value.Should().BeApproximately(57, 0.01); var e3 = e2 + 10; e3.Value.Should().BeApproximately(10, 0.01); } [Fact] public void EWMA_should_calculate_alpha_from_half_life_and_collect_interval() { // according to http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average var expectedAlpha = 0.1; // alpha = 2.0 / (1 + N) var n = 19; var halfLife = n / 2.8854; var collectInterval = 1.Seconds(); var halfLifeDuration = TimeSpan.FromSeconds(halfLife); NodeMetrics.Types.EWMA.GetAlpha(halfLifeDuration, collectInterval).Should().BeApproximately(expectedAlpha, 0.001); } [Fact] public void EWMA_should_calculate_same_alpha_from_short_halflife() { var alpha = NodeMetrics.Types.EWMA.GetAlpha(1.Milliseconds(), 3.Seconds()); alpha.Should().BeInRange(0, 1); alpha.Should().BeApproximately(1, 0.001); } [Fact] public void EWMA_should_calculate_same_alpha_from_long_halflife() { var alpha = NodeMetrics.Types.EWMA.GetAlpha(1.Days(), 3.Seconds()); alpha.Should().BeInRange(0, 1); alpha.Should().BeApproximately(0, 0.001); } // TODO: Port one more test with real MetricsCollector implementation } }
37.946237
126
0.565316
[ "Apache-2.0" ]
hueifeng/akka.net
src/contrib/cluster/Akka.Cluster.Metrics.Tests/EWMASpec.cs
3,529
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Levels : MonoBehaviour { [SerializeField] private GameObject m_Canvas; [SerializeField] private GameObject m_Prefab; [SerializeField] private Vector2 m_Start; [SerializeField] private Vector2 m_End; [SerializeField] private Vector2Int m_Grid; private int m_Levels = (int)Scenes.LevelLast - (int)Scenes.Level1 + 1; private void Start() { int lvl = 1; for (uint y = 0; y < m_Grid.y; y++) for (uint x = 0; x < m_Grid.x; x++, lvl++) { if (lvl > m_Levels) return; GameObject obj = Instantiate(m_Prefab, m_Canvas.transform); obj.GetComponent<RectTransform>().anchoredPosition = new Vector2(Mathf.Lerp(m_Start.x, m_End.x, (float)x / m_Grid.x), Mathf.Lerp(m_Start.y, m_End.y, (float)y / m_Grid.y)); obj.transform.Find("LevelButton").Find("Number").GetComponent<Text>().text = lvl.ToString(); obj.transform.Find("Time").GetComponent<Text>().text = GetTime(lvl).ToString("n2"); AddListener(obj.transform.Find("LevelButton").gameObject, lvl); } } private float GetTime(int lvl) => PlayerPrefs.GetFloat($"Level{lvl}.Time", float.NaN); private void AddListener(GameObject obj, int lvl) => obj.GetComponent<Button>().onClick.AddListener(() => GameManager.Instance.GotoLevel(lvl - 1)); }
33.365854
175
0.702485
[ "MIT" ]
TeddyTelanoff/BlingBlang
Assets/Scripts/Levels.cs
1,370
C#
using System.ComponentModel.DataAnnotations; namespace Contas.Infrastructure.CrossCutting.Identity.Models.ManageViewModels { public class IndexViewModel { public string Username { get; set; } public bool IsEmailConfirmed { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Phone] [Display(Name = "Phone number")] public string PhoneNumber { get; set; } public string StatusMessage { get; set; } } }
23.272727
77
0.632813
[ "MIT" ]
myrp-alexandre/ContasAPI
src/Contas.Infrastructure.CrossCutting.Identity/Models/ManageViewModels/IndexViewModel.cs
514
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Efs { [Serializable] [EfsFile("/nv/item_files/rfnv/00023245", true, 0xE1FF)] [Attributes(9)] public class CdmaC3Bc01xRxSwitchpoints { [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic0Active { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic0Swpt1Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt1FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt1RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt1FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt1RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic0Swpt2Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt2FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt2RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt2FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt2RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic0Swpt3Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt3FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt3RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt3FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt3RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic0Swpt4Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt4FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt4RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt4FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic0Swpt4RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic1Active { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic1Swpt1Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt1FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt1RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt1FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt1RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic1Swpt2Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt2FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt2RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt2FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt2RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic1Swpt3Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt3FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt3RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt3FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt3RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic1Swpt4Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt4FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt4RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt4FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic1Swpt4RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic2Active { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic2Swpt1Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt1FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt1RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt1FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt1RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic2Swpt2Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt2FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt2RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt2FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt2RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic2Swpt3Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt3FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt3RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt3FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt3RiseHold { get; set; } [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Ic2Swpt4Type { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt4FallOrHyst { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt4RiseOrBackoff { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt4FallHold { get; set; } [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Ic2Swpt4RiseHold { get; set; } } }
29.510574
60
0.499898
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Efs/CdmaC3Bc01xRxSwitchpointsI.cs
9,768
C#
using System; using Sirenix.OdinInspector; using Unit; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class EscMenuController : MonoBehaviour { [Title("Reference")] public GameObject escMenu; public GameObject musicButton; public AudioSource backgroundAudio; public AudioSource definedAudio; public UnitRelationshipGUIDrawer relationshipDrawer; public PusherGUIController pusherController; private bool _toggle = false; private bool _musicToggle = true; private Color _musicButtonColor; public void OpenMenu() { escMenu.SetActive(true); relationshipDrawer.canDraw = false; pusherController.canUse = false; } public void CloseMenu() { escMenu.SetActive(false); relationshipDrawer.canDraw = true; pusherController.canUse = true; } public void ToTitleScreen() { SceneManager.LoadScene("Title"); } public void ToggleMusic() { _musicToggle = !_musicToggle; if (!_musicToggle) { _musicButtonColor = musicButton.GetComponent<Image>().color; musicButton.GetComponent<Image>().color = _musicButtonColor.ModifiedAlpha(_musicButtonColor.a / 2); backgroundAudio.enabled = false; definedAudio.enabled = false; } else { musicButton.GetComponent<Image>().color = _musicButtonColor; backgroundAudio.enabled = true; definedAudio.enabled = true; } } private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { _toggle = !_toggle; if(_toggle) OpenMenu(); else CloseMenu(); } } }
24.013158
111
0.613699
[ "MIT" ]
yimingp/Eros-s-Desk
Assets/Scripts/EscMenuController.cs
1,827
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Follow : MonoBehaviour { public Transform target; void Start() { } // Update is called once per frame void Update() { transform.position = new Vector3(target.position.x, target.position.y, transform.position.z); } }
18.947368
101
0.661111
[ "MIT" ]
Loganou974/King-Kaf
King Kaf/Assets/Scripts/Follow.cs
362
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Kudu.Client; using Kudu.Client.Infrastructure; using Kudu.Contracts.Settings; using Kudu.Contracts.SourceControl; using Kudu.Core.Deployment; using Kudu.Core.Infrastructure; using Kudu.FunctionalTests.Infrastructure; using Kudu.TestHarness; using Kudu.TestHarness.Xunit; using Xunit; namespace Kudu.FunctionalTests { [KuduXunitTestClass] public class RepoWithMultipleProjectsShouldDeployTests : GitRepositoryManagementTests { [Fact] public void PushRepoWithMultipleProjectsShouldDeploy() { // Arrange string appName = "PushMultiProjects"; string verificationText = "Welcome to ASP.NET MVC!"; using (var repo = Git.Clone("Mvc3AppWithTestProject")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); Assert.NotNull(results[0].LastSuccessEndTime); KuduAssert.VerifyUrl(appManager.SiteUrl, verificationText); }); } } } [KuduXunitTestClass] public class SimpleWapWithInlineCommandTests : GitRepositoryManagementTests { // Has been disabled for ages. Commenting out attribute to avoid warning. Should probably just delete //[Fact(Skip = "Dangerous")] public void PushSimpleWapWithInlineCommand() { // Arrange string appName = "PushSimpleWapWithInlineCommand"; using (var repo = Git.Clone("CustomBuildScript")) { repo.WriteFile(".deployment", @" [config] command = msbuild SimpleWebApplication/SimpleWebApplication.csproj /t:pipelinePreDeployCopyAllFilesToOneFolder /p:_PackageTempDir=""%DEPLOYMENT_TARGET%"";AutoParameterizationWebConfigConnectionStrings=false;Configuration=Debug;SolutionDir=""%DEPLOYMENT_SOURCE%"""); Git.Commit(repo.PhysicalPath, "Custom build command added"); ApplicationManager.Run(appName, appManager => { // Act GitDeploymentResult deployResult = appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "DEBUG"); }); } } } [KuduXunitTestClass] public class SimpleWapWithCustomDeploymentScriptTests : GitRepositoryManagementTests { // Has been disabled for ages. Commenting out attribute to avoid warning. Should probably just delete //[Fact(Skip = "Dangerous")] public void PushSimpleWapWithCustomDeploymentScript() { // Arrange string appName = "WapWithCustomDeploymentScript"; using (var repo = Git.Clone("CustomBuildScript")) { repo.WriteFile(".deployment", @" [config] command = deploy.cmd"); Git.Commit(repo.PhysicalPath, "Custom build script added"); ApplicationManager.Run(appName, appManager => { // Act GitDeploymentResult deployResult = appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "DEBUG"); }); } } } [KuduXunitTestClass] public class SimpleWapWithFailingCustomDeploymentScriptTests : GitRepositoryManagementTests { [Fact] public void PushSimpleWapWithFailingCustomDeploymentScript() { // Arrange string appName = "WapWithFailingCustomDeploymentScript"; using (var repo = Git.Clone("CustomBuildScript")) { repo.WriteFile(".deployment", @" [config] command = deploy.cmd"); repo.WriteFile("deploy.cmd", "bogus"); Git.Commit(repo.PhysicalPath, "Updated the deploy file."); ApplicationManager.Run(appName, appManager => { // Act GitDeploymentResult deployResult = appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Failed, results[0].Status); KuduAssert.VerifyLogOutput(appManager, results[0].Id, ">bogus", "'bogus' is not recognized as an internal or external command"); }); } } } [KuduXunitTestClass] public class CommandSettingOverridesDotDeploymentFileTests : GitRepositoryManagementTests { [Fact] public async Task CommandSettingOverridesDotDeploymentFile() { // Arrange string appName = "CommandSettingOverridesDotDeploymentFile"; using (var repo = Git.Clone("CustomBuildScript")) { repo.WriteFile(".deployment", @" [config] command = deploy.cmd project = myproject"); repo.WriteFile("deploy.cmd", "bogus"); Git.Commit(repo.PhysicalPath, "Updated the deploy file."); await ApplicationManager.RunAsync(appName, async appManager => { // Act await appManager.SettingsManager.SetValue("COMMAND", "echo test from CommandSettingOverridesDotDeploymentFile & set project"); GitDeploymentResult deployResult = appManager.GitDeploy(repo.PhysicalPath); var results = (await appManager.DeploymentManager.GetResultsAsync()).ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyLogOutput(appManager, results[0].Id, "test from CommandSettingOverridesDotDeploymentFile", "myproject"); KuduAssert.VerifyLogOutputWithUnexpected(appManager, results[0].Id, ">bogus", "'bogus' is not recognized as an internal or external command"); }); } } } [KuduXunitTestClass] public class WarningsAsErrorsTests : GitRepositoryManagementTests { [Fact] public void WarningsAsErrors() { // Arrange string appName = "WarningsAsErrors"; using (var repo = Git.Clone("WarningsAsErrors")) { ApplicationManager.Run(appName, appManager => { // Act GitDeploymentResult deployResult = appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Failed, results[0].Status); Assert.Null(results[0].LastSuccessEndTime); KuduAssert.VerifyLogOutput(appManager, results[0].Id, "The variable 'x' is declared but never used"); Assert.True(deployResult.GitTrace.Contains("The variable 'x' is declared but never used")); Assert.True(deployResult.GitTrace.Contains("Error - Changes committed to remote repository but deployment to website failed")); }); } } } [KuduXunitTestClass] public class RepoWithProjectAndNoSolutionShouldDeployTests : GitRepositoryManagementTests { [Fact] public void PushRepoWithProjectAndNoSolutionShouldDeploy() { // Arrange string appName = "PushRepoWithProjNoSln"; string verificationText = "Kudu Deployment Testing: Mvc3Application_NoSolution"; using (var repo = Git.Clone("Mvc3Application_NoSolution")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, verificationText); }); } } } [KuduXunitTestClass] public class RepositoryWithNoDeployableProjectsTreatsAsWebsiteTests : GitRepositoryManagementTests { [Fact] public void PushRepositoryWithNoDeployableProjectsTreatsAsWebsite() { // Arrange string appName = "PushNoDeployableProj"; using (var repo = Git.Clone("NoDeployableProjects")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyLogOutput(appManager, results[0].Id, "no deployable projects. Deploying files instead"); }); } } } [KuduXunitTestClass] public class WapBuildsReleaseModeTests : GitRepositoryManagementTests { [Fact] public void WapBuildsReleaseMode() { // Arrange string appName = "WapBuildsRelease"; using (var repo = Git.Clone("ConditionalCompilation")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, null, "RELEASE MODE", "Context.IsDebuggingEnabled: False"); }); } } } [KuduXunitTestClass] public class WebsiteWithIISExpressWorksTests : GitRepositoryManagementTests { [Fact] public void WebsiteWithIISExpressWorks() { // Arrange string appName = "WebsiteWithIISExpressWorks"; using (var repo = Git.Clone("waws")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "Home"); }); } } } [KuduXunitTestClass] public class AppChangesShouldTriggerBuildTests : GitRepositoryManagementTests { [Fact] public void PushAppChangesShouldTriggerBuild() { // Arrange string repositoryName = "Mvc3Application"; string appName = "PushAppChanges"; string verificationText = "Welcome to ASP.NET MVC!"; using (var repo = Git.Clone(repositoryName)) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); Git.Revert(repo.PhysicalPath); appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, verificationText); }); } } } [KuduXunitTestClass] public class AppNameWithSignalRWorksTests : GitRepositoryManagementTests { // This test was only interesting when we used signalR (routing issue), which we don't anymore //[Fact] public void AppNameWithSignalRWorks() { // Arrange string repositoryName = "Mvc3Application"; string appName = "signalroverflow"; string verificationText = "Welcome to ASP.NET MVC!"; using (var repo = Git.Clone(repositoryName)) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, verificationText); }); } } } [KuduXunitTestClass] public class DeletesToRepositoryArePropagatedForWapsTests : GitRepositoryManagementTests { [Fact] public void DeletesToRepositoryArePropagatedForWaps() { string repositoryName = "Mvc3Application"; string appName = "DeletesToRepoForWaps"; using (var repo = Git.Clone(repositoryName)) { ApplicationManager.Run(appName, appManager => { string deletePath = Path.Combine(repo.PhysicalPath, @"Mvc3Application\Controllers\AccountController.cs"); string projectPath = Path.Combine(repo.PhysicalPath, @"Mvc3Application\Mvc3Application.csproj"); // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl + "Account/LogOn", statusCode: HttpStatusCode.OK); File.Delete(deletePath); File.WriteAllText(projectPath, File.ReadAllText(projectPath).Replace(@"<Compile Include=""Controllers\AccountController.cs"" />", "")); Git.Commit(repo.PhysicalPath, "Deleted the filez"); appManager.GitDeploy(repo.PhysicalPath); results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[1].Status); KuduAssert.VerifyUrl(appManager.SiteUrl + "Account/LogOn", statusCode: HttpStatusCode.NotFound); }); } } } [KuduXunitTestClass] public class ShouldOverwriteModifiedFilesInRepoTests : GitRepositoryManagementTests { [Fact] public void PushShouldOverwriteModifiedFilesInRepo() { // Arrange string repositoryName = "Mvc3Application"; string appName = "PushOverwriteModified"; string verificationText = "The base color for this template is #5c87b2"; using (var repo = Git.Clone(repositoryName)) { ApplicationManager.Run(appName, appManager => { string path = @"Content/Site.css"; string url = appManager.SiteUrl + path; // Act appManager.GitDeploy(repo.PhysicalPath); KuduAssert.VerifyUrl(url, verificationText); appManager.VfsWebRootManager.WriteAllText(path, "Hello world!"); // Sleep a little since it's a remote call Thread.Sleep(500); KuduAssert.VerifyUrl(url, "Hello world!"); // Make an unrelated change (newline to the end of web.config) repo.AppendFile(@"Mvc3Application\Web.config", "\n"); Git.Commit(repo.PhysicalPath, "This is a test"); appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(url, verificationText); }); } } } [KuduXunitTestClass] public class GoingBackInTimeShouldOverwriteModifiedFilesInRepoTests : GitRepositoryManagementTests { [Fact] public void GoingBackInTimeShouldOverwriteModifiedFilesInRepo() { // Arrange string repositoryName = "Mvc3Application"; string appName = "GoBackOverwriteModified"; string verificationText = "The base color for this template is #5c87b2"; using (var repo = Git.Clone(repositoryName)) { string id = repo.CurrentId; ApplicationManager.Run(appName, appManager => { string url = appManager.SiteUrl + "/Content/Site.css"; // Act appManager.GitDeploy(repo.PhysicalPath); KuduAssert.VerifyUrl(url, verificationText); repo.AppendFile(@"Mvc3Application\Content\Site.css", "Say Whattttt!"); // Make a small changes and commit them to the local repo Git.Commit(repo.PhysicalPath, "This is a small changes"); // Push those changes appManager.GitDeploy(repo.PhysicalPath); // Make a server site change and verify it shows up appManager.VfsWebRootManager.WriteAllText("Content/Site.css", "Hello world!"); Thread.Sleep(500); KuduAssert.VerifyUrl(url, "Hello world!"); // Now go back in time appManager.DeploymentManager.DeployAsync(id).Wait(); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(url, verificationText); }); } } } [KuduXunitTestClass] public class DeletesToRepositoryArePropagatedForNonWapsTests : GitRepositoryManagementTests { [Fact] public void DeletesToRepositoryArePropagatedForNonWaps() { string appName = "DeleteForNonWaps"; using (var repo = Git.Clone("Bakery")) { ApplicationManager.Run(appName, appManager => { string deletePath = Path.Combine(repo.PhysicalPath, @"Content"); // Act appManager.GitDeploy(repo.PhysicalPath); // Assert var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl + "Content/Site.css", statusCode: HttpStatusCode.OK); Directory.Delete(deletePath, recursive: true); Git.Commit(repo.PhysicalPath, "Deleted all styles"); appManager.GitDeploy(repo.PhysicalPath); results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[1].Status); KuduAssert.VerifyUrl(appManager.SiteUrl + "Content/Site.css", statusCode: HttpStatusCode.NotFound); }); } } } [KuduXunitTestClass] public class FirstPushDeletesHostingStartHtmlFileTests : GitRepositoryManagementTests { [Fact] public void FirstPushDeletesHostingStartHtmlFile() { string appName = "FirstPushDelPrior"; using (var repo = Git.Clone("HelloWorld")) { ApplicationManager.Run(appName, appManager => { string url = appManager.SiteUrl + "hostingstart.html"; KuduAssert.VerifyUrl(url, KuduAssert.DefaultPageContent); // Act appManager.GitDeploy(repo.PhysicalPath); // Assert var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl); KuduAssert.VerifyUrl(url, statusCode: HttpStatusCode.NotFound); }); } } } [KuduXunitTestClass] public class PushingToNonMasterBranchNoOpsTests : GitRepositoryManagementTests { [Fact] public void PushingToNonMasterBranchNoOps() { string repositoryName = "PushingToNonMasterBranchNoOps"; string appName = "PushToNonMaster"; string cloneUrl = "https://github.com/KuduApps/RepoWithMultipleBranches.git"; using (var repo = Git.Clone(repositoryName, cloneUrl, noCache: true)) { Git.CheckOut(repo.PhysicalPath, "test"); ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath, "test", "test"); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(0, results.Count); KuduAssert.VerifyUrl(appManager.SiteUrl, KuduAssert.DefaultPageContent); }); } } } [KuduXunitTestClass] public class PushingConfiguredBranchTests : GitRepositoryManagementTests { [Fact] public void PushingConfiguredBranch() { string repositoryName = "PushingConfiguredBranch"; string appName = "PushingConfiguredBranch"; string cloneUrl = "https://github.com/KuduApps/RepoWithMultipleBranches.git"; using (var repo = Git.Clone(repositoryName, cloneUrl, noCache: true)) { Git.CheckOut(repo.PhysicalPath, "foo/bar"); ApplicationManager.Run(appName, appManager => { // Set the branch to test and push to that branch appManager.SettingsManager.SetValue("branch", "foo/bar").Wait(); appManager.GitDeploy(repo.PhysicalPath, "foo/bar", "foo/bar"); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); KuduAssert.VerifyUrl(appManager.SiteUrl, "foo/bar branch"); // Now push master, but without changing the deploy branch appManager.GitDeploy(repo.PhysicalPath, "master", "master"); results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Here, no new deployment should have happened Assert.Equal(1, results.Count); KuduAssert.VerifyUrl(appManager.SiteUrl, "foo/bar branch"); // Now change deploy branch to master and do a 'Deploy Latest' (i.e. no id) appManager.SettingsManager.SetValue("branch", "master").Wait(); appManager.DeploymentManager.DeployAsync(id: null).Wait(); results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Now, we should have a second deployment with master bit Assert.Equal(2, results.Count); KuduAssert.VerifyUrl(appManager.SiteUrl, "Master branch"); }); } } } [KuduXunitTestClass] public class PushingNonMasterBranchToMasterBranchShouldDeployTests : GitRepositoryManagementTests { [Fact] public void PushingNonMasterBranchToMasterBranchShouldDeploy() { string repositoryName = "PushingNonMasterBranchToMasterBranchShouldDeploy"; string appName = "PushNonMasterToMaster"; string cloneUrl = "https://github.com/KuduApps/RepoWithMultipleBranches.git"; using (var repo = Git.Clone(repositoryName, cloneUrl, noCache: true)) { Git.CheckOut(repo.PhysicalPath, "test"); ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath, "test", "master"); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); KuduAssert.VerifyUrl(appManager.SiteUrl, "Test branch"); }); } } } [KuduXunitTestClass] public class CloneFromEmptyRepoAndPushShouldDeployTests : GitRepositoryManagementTests { [Fact] public void CloneFromEmptyRepoAndPushShouldDeploy() { string repositoryName = "CloneFromEmptyRepoAndPushShouldDeploy"; string appName = "CloneEmptyAndPush"; ApplicationManager.Run(appName, appManager => { // Act using (var repo = Git.Clone(repositoryName, appManager.GitUrl)) { // Add a file repo.WriteFile("hello.txt", "Wow"); Git.Commit(repo.PhysicalPath, "Added hello.txt"); string helloUrl = appManager.SiteUrl + "/hello.txt"; appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); KuduAssert.VerifyUrl(helloUrl, "Wow"); } }); } } [KuduXunitTestClass] public class PushThenCloneTests : GitRepositoryManagementTests { [Fact] public void PushThenClone() { string repositoryName = "Bakery"; string appName = "PushThenClone"; using (var repo = Git.Clone(repositoryName)) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); using (var clonedRepo = Git.Clone(repositoryName, appManager.GitUrl)) { Assert.True(clonedRepo.FileExists("Default.cshtml")); } }); } } } [KuduXunitTestClass] public class CloneFromNewRepoShouldHaveBeEmptyTests : GitRepositoryManagementTests { [Fact] public void CloneFromNewRepoShouldHaveBeEmpty() { string repositoryName = "CloneFromNewRepoShouldHaveFile"; string appName = "CloneNew"; ApplicationManager.Run(appName, appManager => { using (var repo = Git.Clone(repositoryName, appManager.GitUrl)) { Assert.False(repo.FileExists("index.html")); } }); } } [KuduXunitTestClass] public class ClonesInParallelTests : GitRepositoryManagementTests { [Fact] public void ClonesInParallel() { string appName = "ClonesInParallel"; ApplicationManager.Run(appName, appManager => { var t1 = Task.Factory.StartNew(() => DoClone("PClone1", appManager)); var t2 = Task.Factory.StartNew(() => DoClone("PClone2", appManager)); var t3 = Task.Factory.StartNew(() => DoClone("PClone3", appManager)); Task.WaitAll(t1, t2, t3); }); } private static void DoClone(string repositoryName, ApplicationManager appManager) { using (var repo = Git.Clone(repositoryName, appManager.GitUrl)) { Assert.False(repo.FileExists("index.html")); } } } [KuduXunitTestClass] public class GoingBackInTimeDeploysOldFilesTests : GitRepositoryManagementTests { [Fact] public void GoingBackInTimeDeploysOldFiles() { string appName = "GoBackDeployOld"; using (var repo = Git.Clone("HelloWorld")) { string originalCommitId = repo.CurrentId; ApplicationManager.Run(appName, appManager => { // Deploy the app appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(1, results.Count); KuduAssert.VerifyUrl(appManager.SiteUrl); // Add a file File.WriteAllText(Path.Combine(repo.PhysicalPath, "hello.txt"), "Wow"); Git.Commit(repo.PhysicalPath, "Added hello.txt"); string helloUrl = appManager.SiteUrl + "/hello.txt"; // Deploy those changes appManager.GitDeploy(repo.PhysicalPath); results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[1].Status); KuduAssert.VerifyUrl(helloUrl, "Wow"); // Go back to the first deployment appManager.DeploymentManager.DeployAsync(originalCommitId).Wait(); results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); KuduAssert.VerifyUrl(helloUrl, statusCode: HttpStatusCode.NotFound); Assert.Equal(2, results.Count); }); } } } [KuduXunitTestClass] public class NpmSiteInstallsPackagesTests : GitRepositoryManagementTests { [Fact] public void NpmSiteInstallsPackages() { string appName = "NpmInstallsPkg"; using (var repo = Git.Clone("NpmSite")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); Assert.True(appManager.VfsWebRootManager.Exists("node_modules/express")); }); } } } [KuduXunitTestClass] public class FailedNpmFailsDeploymentTests : GitRepositoryManagementTests { [Fact] public void FailedNpmFailsDeployment() { string appName = "FailedNpm"; using (var repo = Git.Clone("NpmSite")) { ApplicationManager.Run(appName, appManager => { // Replace the express dependency with something that doesn't exist // using Guid so that even if cache is used, lookup will still fail var madeUpPackageName = $"kudu{Guid.NewGuid()}"; repo.Replace("package.json", "express", madeUpPackageName); Git.Commit(repo.PhysicalPath, "Added fake package to package.json"); // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Failed, results[0].Status); KuduAssert.VerifyLogOutput(appManager, results[0].Id, $"'{madeUpPackageName}' is not in the npm registry."); }); } } } [KuduXunitTestClass] public class CustomNodeScriptTests : GitRepositoryManagementTests { [Fact] public void CustomNodeScript() { // Arrange string repositoryName = "VersionPinnedNodeJsAppCustom"; string appName = "VersionPinnedNodeJsAppCustom"; using (var repo = Git.Clone(repositoryName)) { ApplicationManager.Run(appName, appManager => { // Act GitDeploymentResult deployResult = appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "v0.8.2"); KuduAssert.VerifyLogOutput(appManager, results[0].Id, "custom deployment success"); }); } } } [KuduXunitTestClass] public class NodeHelloWorldNoConfigTests : GitRepositoryManagementTests { [Fact] public void NodeHelloWorldNoConfig() { string appName = "NodeConfig"; using (var repo = Git.Clone("NodeHelloWorldNoConfig")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); // Make sure a web.config file got created at deployment time Assert.True(appManager.VfsWebRootManager.Exists("web.config")); // Make sure the web.config file doesn't exist on the repository after the deployment finished Assert.False(appManager.VfsManager.Exists("site\\repository\\web.config")); }); } } } [KuduXunitTestClass] public class NodeWithSolutionsUnderNodeModulesShouldBeDeployedTests : GitRepositoryManagementTests { [Fact] public void NodeWithSolutionsUnderNodeModulesShouldBeDeployed() { string appName = "NodeWithSolutionsUnderNodeModulesShouldBeDeployed"; using (var repo = Git.Clone("NodeWithSolutions")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); var log = GetLog(appManager, results[0].Id); Assert.Contains("Handling node.js deployment", log); }); } } } [KuduXunitTestClass] public class RedeployNodeSiteTests : GitRepositoryManagementTests { [Fact] public void RedeployNodeSite() { string appName = "RedeployNodeSite"; using (var repo = Git.Clone("NodeHelloWorldNoConfig")) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); var log1 = GetLog(appManager, results[0].Id); Assert.Contains("Using the following command to generate deployment script", log1); string id = results[0].Id; repo.Replace("server.js", "world", "world2"); Git.Commit(repo.PhysicalPath, "Made a small change"); appManager.GitDeploy(repo.PhysicalPath); results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[1].Status); appManager.DeploymentManager.DeployAsync(id).Wait(); results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); Assert.Equal(DeployStatus.Success, results[1].Status); var log2 = GetLog(appManager, results[0].Id); var log3 = GetLog(appManager, results[1].Id); Assert.Contains("Using cached version of deployment script", log2); Assert.Contains("Using cached version of deployment script", log3); }); } } } [KuduXunitTestClass] public class GetResultsTests : GitRepositoryManagementTests { [Fact] public void GetResults() { // Arrange string repositoryName = "Mvc3Application"; string appName = "RsltMaxItemXcldFailed"; using (var repo = Git.Clone(repositoryName)) { ApplicationManager.Run(appName, appManager => { string homeControllerPath = Path.Combine(repo.PhysicalPath, @"Mvc3Application\Controllers\HomeController.cs"); // Act, Initial Commit appManager.GitDeploy(repo.PhysicalPath); // Assert var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "Welcome to ASP.NET MVC! - Change1"); // Act, Change 2 File.WriteAllText(homeControllerPath, File.ReadAllText(homeControllerPath).Replace(" - Change1", " - Change2")); Git.Commit(repo.PhysicalPath, "Change 2!"); appManager.GitDeploy(repo.PhysicalPath); // Assert results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(2, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); Assert.Equal(DeployStatus.Success, results[1].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "Welcome to ASP.NET MVC! - Change2"); // Act, Invalid Change build-break change and commit File.WriteAllText(homeControllerPath, File.ReadAllText(homeControllerPath).Replace("Index()", "Index;")); Git.Commit(repo.PhysicalPath, "Invalid Change!"); appManager.GitDeploy(repo.PhysicalPath); // Assert results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); Assert.Equal(3, results.Count); Assert.Equal(DeployStatus.Failed, results[0].Status); Assert.Equal(DeployStatus.Success, results[1].Status); Assert.Equal(DeployStatus.Success, results[2].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, "Welcome to ASP.NET MVC! - Change2"); }); } } } [KuduXunitTestClass] public class RepoWithPublicSubModuleTestTests : GitRepositoryManagementTests { [Fact] public void RepoWithPublicSubModuleTest() { // Arrange string repositoryName = "RepoWithPublicSubModule"; string appName = "RepoWithPublicSubModule"; string cloneUrl = "https://github.com/KuduApps/RepoWithPublicSubModule.git"; using (var repo = Git.Clone(repositoryName, cloneUrl, noCache: true)) { ApplicationManager.Run(appName, appManager => { // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl + "default.htm", "Hello from RepoWithPublicSubModule!"); KuduAssert.VerifyUrl(appManager.SiteUrl + "PublicSubModule/default.htm", "Hello from PublicSubModule!"); }); } } } [KuduXunitTestClass] public class RepoWithPrivateSubModuleTestTests : GitRepositoryManagementTests { [Fact] public void RepoWithPrivateSubModuleTest() { // Arrange string appName = "RepoWithPrivateSubModule"; string id_rsa; IDictionary<string, string> environmentVariables = SshHelper.PrepareSSHEnv(out id_rsa); if (String.IsNullOrEmpty(id_rsa)) { return; } using (var repo = Git.Clone("RepoWithPrivateSubModule", environments: environmentVariables)) { ApplicationManager.Run(appName, appManager => { appManager.SSHKeyManager.SetPrivateKey(id_rsa); // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl + "default.htm", "Hello from RepoWithPrivateSubModule!"); KuduAssert.VerifyUrl(appManager.SiteUrl + "PrivateSubModule/default.htm", "Hello from PrivateSubModule!"); }); } } } [KuduXunitTestClass] public class HangProcessTestTests : GitRepositoryManagementTests { [Fact] [KuduXunitTest(PrivateOnly = true)] public void HangProcessTest() { // Arrange string appName = "HangProcess"; using (var repo = Git.Clone("HangProcess")) { ApplicationManager.Run(appName, appManager => { // Act // Set IdleTimeout to 10s meaning there must be activity every 10s // Otherwise process and its child will be terminated appManager.SettingsManager.SetValue(SettingsKeys.CommandIdleTimeout, "10").Wait(); // This HangProcess repo spew out activity at 2s, 4s, 6s and 30s respectively // we should receive the one < 10s and terminate otherwise. string trace; try { GitDeploymentResult result = appManager.GitDeploy(repo.PhysicalPath, retries: 1); trace = result.GitTrace; } catch (CommandLineException ex) { trace = ex.Message; } Assert.Contains("remote: Sleep(2000)", trace); Assert.Contains("remote: Sleep(4000)", trace); Assert.Contains("remote: Sleep(6000)", trace); Assert.DoesNotContain("remote: Sleep(60000)", trace); Assert.Contains("remote: Command 'starter.cmd simplesleep.exe ...' was aborted due to no output nor CPU activity for", trace); Assert.False(Process.GetProcesses().Any(p => p.ProcessName.Equals("simplesleep", StringComparison.OrdinalIgnoreCase)), "SimpleSleep should have been terminated!"); }); } } } [KuduXunitTestClass] public class WaitForUserInputProcessTestTests : GitRepositoryManagementTests { [Fact] public void WaitForUserInputProcessTest() { // Arrange string appName = "WaitForUserInput"; using (var repo = Git.Clone("WaitForUserInput")) { ApplicationManager.Run(appName, appManager => { // Act // Set IdleTimeout to 10s meaning there must be activity every 10s // Otherwise process and its child will be terminated appManager.SettingsManager.SetValue(SettingsKeys.CommandIdleTimeout, "10").Wait(); // This WaitForUserInput do set /P waiting for input GitDeploymentResult result = appManager.GitDeploy(repo.PhysicalPath, retries: 1); string trace = result.GitTrace; Assert.Contains("remote: Insert your input:", trace); Assert.Contains("remote: Command 'starter.cmd waitforinput.ba ...' was aborted due to no output nor CPU activity for", trace); }); } } } [KuduXunitTestClass] public class HookForbiddenForSomeScmTypesTests : GitRepositoryManagementTests { [Fact] public void HookForbiddenForSomeScmTypes() { string bitbucketPayload = @"{ ""canon_url"": ""https://github.com"", ""commits"": [ { ""author"": ""davidebbo"", ""branch"": ""master"", ""files"": [ { ""file"": ""Mvc3Application/Views/Home/Index.cshtml"", ""type"": ""modified"" } ], ""message"": ""Blah2\n"", ""node"": ""e550351c5188"", ""parents"": [ ""297fcc65308c"" ], ""raw_author"": ""davidebbo <david.ebbo@microsoft.com>"", ""raw_node"": ""ea1c6d7ea669c816dd5f86206f7b47b228fdcacd"", ""revision"": null, ""size"": -1, ""timestamp"": ""2012-09-20 03:11:20"", ""utctimestamp"": ""2012-09-20 01:11:20+00:00"" } ], ""repository"": { ""absolute_url"": ""/KuduApps/SimpleWebApplication"", ""fork"": false, ""is_private"": false, ""name"": ""Mvc3Application"", ""owner"": ""davidebbo"", ""scm"": ""git"", ""slug"": ""mvc3application"", ""website"": """" }, ""user"": ""davidebbo"" }"; string githubPayload = @"{ ""after"": ""7e2a599e2d28665047ec347ab36731c905c95e8b"", ""before"": ""7e2a599e2d28665047ec347ab36731c905c95e8b"", ""commits"": [ { ""added"": [], ""author"": { ""email"": ""prkrishn@hotmail.com"", ""name"": ""Pranav K"", ""username"": ""pranavkm"" }, ""id"": ""43acf30efa8339103e2bed5c6da1379614b00572"", ""message"": ""Changes from master again"", ""modified"": [ ""Hello.txt"" ], ""timestamp"": ""2012-12-17T17:32:15-08:00"" } ], ""compare"": ""https://github.com/KuduApps/GitHookTest/compare/7e2a599e2d28...7e2a599e2d28"", ""created"": false, ""deleted"": false, ""forced"": false, ""head_commit"": { ""added"": [ "".gitignore"", ""SimpleWebApplication.sln"", ""SimpleWebApplication/About.aspx"", ""SimpleWebApplication/About.aspx.cs"", ""SimpleWebApplication/About.aspx.designer.cs"", ""SimpleWebApplication/Account/ChangePassword.aspx"", ""SimpleWebApplication/Account/ChangePassword.aspx.cs"", ""SimpleWebApplication/Account/ChangePassword.aspx.designer.cs"", ""SimpleWebApplication/Account/ChangePasswordSuccess.aspx"", ""SimpleWebApplication/Account/ChangePasswordSuccess.aspx.cs"", ""SimpleWebApplication/Account/ChangePasswordSuccess.aspx.designer.cs"", ""SimpleWebApplication/Account/Login.aspx"", ""SimpleWebApplication/Account/Login.aspx.cs"", ""SimpleWebApplication/Account/Login.aspx.designer.cs"", ""SimpleWebApplication/Account/Register.aspx"", ""SimpleWebApplication/Account/Register.aspx.cs"", ""SimpleWebApplication/Account/Register.aspx.designer.cs"", ""SimpleWebApplication/Account/Web.config"", ""SimpleWebApplication/Default.aspx"", ""SimpleWebApplication/Default.aspx.cs"", ""SimpleWebApplication/Default.aspx.designer.cs"", ""SimpleWebApplication/Global.asax"", ""SimpleWebApplication/Global.asax.cs"", ""SimpleWebApplication/Properties/AssemblyInfo.cs"", ""SimpleWebApplication/Scripts/jquery-1.4.1-vsdoc.js"", ""SimpleWebApplication/Scripts/jquery-1.4.1.js"", ""SimpleWebApplication/Scripts/jquery-1.4.1.min.js"", ""SimpleWebApplication/SimpleWebApplication.csproj"", ""SimpleWebApplication/Site.Master"", ""SimpleWebApplication/Site.Master.cs"", ""SimpleWebApplication/Site.Master.designer.cs"", ""SimpleWebApplication/Styles/Site.css"", ""SimpleWebApplication/Web.Debug.config"", ""SimpleWebApplication/Web.Release.config"", ""SimpleWebApplication/Web.config"" ], ""author"": { ""email"": ""david.ebbo@microsoft.com"", ""name"": ""davidebbo"", ""username"": ""davidebbo"" }, ""committer"": { ""email"": ""david.ebbo@microsoft.com"", ""name"": ""davidebbo"", ""username"": ""davidebbo"" }, ""distinct"": false, ""id"": ""7e2a599e2d28665047ec347ab36731c905c95e8b"", ""message"": ""Initial"", ""modified"": [], ""removed"": [], ""timestamp"": ""2011-11-21T23:07:42-08:00"", ""url"": ""https://github.com/KuduApps/GitHookTest/commit/7e2a599e2d28665047ec347ab36731c905c95e8b"" }, ""pusher"": { ""name"": ""none"" }, ""ref"": ""refs/heads/master"", ""repository"": { ""created_at"": ""2012-06-28T00:07:55-07:00"", ""description"": """", ""fork"": false, ""forks"": 1, ""has_downloads"": true, ""has_issues"": true, ""has_wiki"": true, ""language"": ""ASP"", ""name"": ""GitHookTest"", ""open_issues"": 0, ""organization"": ""KuduApps"", ""owner"": { ""email"": ""kuduapps@hotmail.com"", ""name"": ""KuduApps"" }, ""private"": false, ""pushed_at"": ""2012-06-28T00:11:48-07:00"", ""size"": 188, ""url"": ""https://github.com/KuduApps/SimpleWebApplication"", ""watchers"": 1 } }"; // Arrange string appName = "ScmTypeTest"; ApplicationManager.Run(appName, appManager => { // Default value test try { // for private kudu, the setting is LocalGit string value = appManager.SettingsManager.GetValue(SettingsKeys.ScmType).Result; Assert.Equal("LocalGit", value); } catch (AggregateException ex) { // for public kudu, the setting does not exist var notFoundException = ex.InnerExceptions.OfType<HttpUnsuccessfulRequestException>().First(); Assert.Equal(HttpStatusCode.NotFound, notFoundException.ResponseMessage.StatusCode); } // Make sure it's disabled for None and Tfs* ScmTypes EnsureDeployDisabled(appManager, ScmType.None, null, githubPayload); EnsureDeployDisabled(appManager, ScmType.Tfs, "Bitbucket.org", bitbucketPayload); EnsureDeployDisabled(appManager, ScmType.TfsGit, "Bitbucket.org", bitbucketPayload); }); } private void EnsureDeployDisabled(ApplicationManager appManager, string scmType, string userAgent, string payload) { appManager.SettingsManager.SetValue(SettingsKeys.ScmType, scmType).Wait(); HttpClient client = CreateClient(appManager); var post = new Dictionary<string, string> { { "payload", payload } }; if (userAgent != null) { client.DefaultRequestHeaders.Add("User-Agent", userAgent); } HttpResponseMessage response = client.PostAsync("deploy", new FormUrlEncodedContent(post)).Result; Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); } } [KuduXunitTestClass] public class SpecificDeploymentConfigurationTests : GitRepositoryManagementTests { [Fact] public void SpecificDeploymentConfiguration() { VerifyDeploymentConfiguration("SpecificDeployConfig", "WebApplication1", "This is the application I want deployed"); } } [KuduXunitTestClass] public class Tests : GitRepositoryManagementTests { [Fact] public void SpecificDeploymentConfigurationForProjectFile() { VerifyDeploymentConfiguration("DeployConfigForProj", "WebApplication1/WebApplication1.csproj", "This is the application I want deployed"); } } [KuduXunitTestClass] public class SpecificDeploymentConfigurationForWebsiteTests : GitRepositoryManagementTests { [Fact] public void SpecificDeploymentConfigurationForWebsite() { VerifyDeploymentConfiguration("DeployConfigForWeb", "WebSite1", "This is a website!"); } } [KuduXunitTestClass] public class SpecificDeploymentConfigurationForWebsiteWithSlashTests : GitRepositoryManagementTests { [Fact] public void SpecificDeploymentConfigurationForWebsiteWithSlash() { VerifyDeploymentConfiguration("DeployConfigWithSlash", "/WebSite1", "This is a website!"); } [Fact] public void SpecificDeploymentConfigurationForWebsiteNotPartOfSolution() { VerifyDeploymentConfiguration("SpecificDeploymentConfigurationForWebsiteNotPartOfSolution", "WebSiteRemovedFromSolution", "This web site was removed from solution!"); } } [KuduXunitTestClass] public class SpecificDeploymentConfigurationForWebProjectNotPartOfSolutionTests : GitRepositoryManagementTests { [Fact] public void SpecificDeploymentConfigurationForWebProjectNotPartOfSolution() { VerifyDeploymentConfiguration("SpecificDeploymentConfigurationForWebProjectNotPartOfSolution", "MvcApplicationRemovedFromSolution", "This web project was removed from solution!"); } } [KuduXunitTestClass] public class SpecificDeploymentConfigurationForNonDeployableProjectFileTests : GitRepositoryManagementTests { [Fact] public void SpecificDeploymentConfigurationForNonDeployableProjectFile() { VerifyDeploymentConfiguration("SpecificDeploymentConfigurationForNonDeployableProjectFile", "MvcApplicationRemovedFromSolution.Tests/MvcApplicationRemovedFromSolution.Tests.csproj", KuduAssert.DefaultPageContent, DeployStatus.Failed); } } [KuduXunitTestClass] public class SpecificDeploymentConfigurationForNonDeployableProjectTests : GitRepositoryManagementTests { [Fact] public void SpecificDeploymentConfigurationForNonDeployableProject() { VerifyDeploymentConfiguration("SpecificDeploymentConfigurationForNonDeployableProject", "MvcApplicationRemovedFromSolution.Tests", KuduAssert.DefaultPageContent, DeployStatus.Failed, "is not a deployable project"); } } [KuduXunitTestClass] public class SpecificDeploymentConfigurationForDirectoryThatDoesNotExistTests : GitRepositoryManagementTests { [Fact] public void SpecificDeploymentConfigurationForDirectoryThatDoesNotExist() { VerifyDeploymentConfiguration("SpecificDeploymentConfigurationForDirectoryThatDoesNotExist", "IDoNotExist", KuduAssert.DefaultPageContent, DeployStatus.Failed); } } [KuduXunitTestClass] public class GitExeBasicTest : GitRepositoryManagementTests { [Fact] public async Task PushRepoWithMultipleProjectsShouldDeploy() { // Arrange string appName = "PushMultiProjects"; string verificationText = "Welcome to ASP.NET MVC!"; using (var repo = Git.Clone("Mvc3AppWithTestProject")) { await ApplicationManager.RunAsync(appName, async appManager => { await appManager.SettingsManager.SetValue("SCM_USE_LIBGIT2SHARP_REPOSITORY", "0"); // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(DeployStatus.Success, results[0].Status); Assert.NotNull(results[0].LastSuccessEndTime); KuduAssert.VerifyUrl(appManager.SiteUrl, verificationText); }); } } } public abstract class GitRepositoryManagementTests { internal static HttpClient CreateClient(ApplicationManager appManager) { HttpClientHandler handler = HttpClientHelper.CreateClientHandler(appManager.ServiceUrl, appManager.DeploymentManager.Credentials); return new HttpClient(handler) { BaseAddress = new Uri(appManager.ServiceUrl), Timeout = TimeSpan.FromMinutes(5) }; } internal static string GetLog(ApplicationManager appManager, string resultId) { var entries = appManager.DeploymentManager.GetLogEntriesAsync(resultId).Result; var allDetails = entries.Where(e => e.DetailsUrl != null) .SelectMany(e => appManager.DeploymentManager.GetLogEntryDetailsAsync(resultId, e.Id).Result); var allEntries = entries.Concat(allDetails); return String.Join("\n", allEntries.Select(entry => entry.Message)); } internal void VerifyDeploymentConfiguration(string siteName, string targetProject, string expectedText, DeployStatus expectedStatus = DeployStatus.Success, string expectedLog = null) { string name = siteName; using (var repo = Git.Clone("SpecificDeploymentConfiguration")) { ApplicationManager.Run(name, appManager => { string deploymentFile = Path.Combine(repo.PhysicalPath, @".deployment"); File.WriteAllText(deploymentFile, String.Format(@"[config] project = {0} ", targetProject)); Git.Commit(repo.PhysicalPath, "Updated configuration " + Guid.NewGuid()); // Act appManager.GitDeploy(repo.PhysicalPath); var results = appManager.DeploymentManager.GetResultsAsync().Result.ToList(); // Assert Assert.Equal(1, results.Count); Assert.Equal(expectedStatus, results[0].Status); KuduAssert.VerifyUrl(appManager.SiteUrl, expectedText); if (!String.IsNullOrEmpty(expectedLog)) { KuduAssert.VerifyLogOutput(appManager, results[0].Id, expectedLog); } }); } } } }
43.601389
3,443
0.571688
[ "Apache-2.0" ]
AzureMentor/kudu
Kudu.FunctionalTests/GitRepositoryManagementTests.cs
62,788
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstApplication.Models { public class Book { public string Title { get; set; } public string Author { get; set; } } }
17.133333
42
0.673152
[ "MIT" ]
denicos/android_andela
dotnetcore/FirstApplication/FirstApplication/Models/Book.cs
259
C#
using Mono.Cecil; using RuntimeNullables.Fody.Contexts; namespace RuntimeNullables.Fody.Extensions { internal static class MethodDefinitionExtensions { public static TypeDefinition? GetIteratorStateMachineType(this MethodDefinition method, WeavingContext weavingContext) { return method.GetConstructorArgValue<TypeReference>("System.Runtime.CompilerServices.IteratorStateMachineAttribute", weavingContext)?.Resolve(); } public static TypeDefinition? GetAsyncStateMachineType(this MethodDefinition method, WeavingContext weavingContext) { return method.GetConstructorArgValue<TypeReference>("System.Runtime.CompilerServices.AsyncStateMachineAttribute", weavingContext)?.Resolve(); } public static TypeDefinition? GetAsyncIteratorStateMachineType(this MethodDefinition method, WeavingContext weavingContext) { return method.GetConstructorArgValue<TypeReference>("System.Runtime.CompilerServices.AsyncIteratorStateMachineAttribute", weavingContext)?.Resolve(); } } }
46.291667
162
0.750675
[ "MIT" ]
Singulink/RuntimeNullables
Source/RuntimeNullables.Fody/Extensions/MethodDefinitionExtensions.cs
1,113
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.IoT.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoT.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for PutItemInput Object /// </summary> public class PutItemInputUnmarshaller : IUnmarshaller<PutItemInput, XmlUnmarshallerContext>, IUnmarshaller<PutItemInput, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> PutItemInput IUnmarshaller<PutItemInput, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public PutItemInput Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; PutItemInput unmarshalledObject = new PutItemInput(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("tableName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.TableName = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static PutItemInputUnmarshaller _instance = new PutItemInputUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static PutItemInputUnmarshaller Instance { get { return _instance; } } } }
33.097826
149
0.635796
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/PutItemInputUnmarshaller.cs
3,045
C#
namespace AonWeb.FluentHttp.HAL { public interface IHalBuilderFactory: IBuilderFactory<IHalBuilder> { } }
19.666667
69
0.737288
[ "MIT" ]
andrewescutia/fluent-http
AonWeb.FluentHttp.HAL/IHalBuilderFactory.cs
120
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Polly.Caching; using Statiq.Common; namespace Statiq.Core { /// <summary> /// This contains the pipeline execution context and other data /// needed to execute a pipeline and cache it's results. /// </summary> internal class PipelinePhase : IDisposable { private readonly IList<IModule> _modules; private readonly ILogger _logger; private bool _disposed; public PipelinePhase(IPipeline pipeline, string pipelineName, Phase phase, IList<IModule> modules, ILogger logger, params PipelinePhase[] dependencies) { Pipeline = pipeline; PipelineName = pipelineName; Phase = phase; _modules = modules ?? new List<IModule>(); _logger = logger.ThrowIfNull(nameof(logger)); Dependencies = dependencies ?? Array.Empty<PipelinePhase>(); } public IPipeline Pipeline { get; } public string PipelineName { get; } public Phase Phase { get; } /// <summary> /// Contains direct dependencies for this pipeline and phase. /// The first dependency should contain the input documents for this phase. /// </summary> public PipelinePhase[] Dependencies { get; set; } /// <summary> /// Holds the output documents from the previous execution of this phase. /// </summary> public ImmutableArray<IDocument> Outputs { get; private set; } = ImmutableArray<IDocument>.Empty; /// <summary> /// The first dependency always holds the input documents for this phase. /// </summary> /// <returns>The input documents for this phase.</returns> private ImmutableArray<IDocument> GetInputs() => Dependencies.Length == 0 ? ImmutableArray<IDocument>.Empty : Dependencies[0].Outputs; // This is the main execute method called by the engine public async Task ExecuteAsync( Engine engine, ConcurrentDictionary<string, PhaseResult[]> phaseResults, ConcurrentDictionary<PipelinePhase, ConcurrentBag<AnalyzerResult>> analyzerResults) { if (_disposed) { throw new ObjectDisposedException(nameof(PipelinePhase)); } // Raise the before event await engine.Events.RaiseAsync(new BeforePipelinePhaseExecution(engine.ExecutionId, PipelineName, Phase)); // Skip the phase if there are no modules DateTimeOffset startTime = DateTimeOffset.Now; long elapsedMilliseconds = -1; if (_modules.Count == 0) { Outputs = GetInputs(); _logger.LogDebug($"{PipelineName}/{Phase} » Pipeline contains no modules, skipping"); } else { // Execute the phase ImmutableArray<IDocument> inputs = GetInputs(); System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); _logger.LogInformation($"-> {PipelineName}/{Phase} » Starting {PipelineName} {Phase} phase execution... ({inputs.Length} input document(s), {_modules.Count} module(s))"); try { // Execute all modules in the pipeline with a new DI scope per phase IServiceScopeFactory serviceScopeFactory = engine.Services.GetRequiredService<IServiceScopeFactory>(); using (IServiceScope serviceScope = serviceScopeFactory.CreateScope()) { ExecutionContextData contextData = new ExecutionContextData( this, engine, phaseResults, serviceScope.ServiceProvider); Outputs = await Engine.ExecuteModulesAsync(contextData, null, _modules, inputs, _logger); stopwatch.Stop(); elapsedMilliseconds = stopwatch.ElapsedMilliseconds; _logger.LogInformation($"<- {PipelineName}/{Phase} » Finished {PipelineName} {Phase} phase execution ({Outputs.Length} output document(s), {elapsedMilliseconds} ms)"); } } catch (Exception ex) { Outputs = ImmutableArray<IDocument>.Empty; if (!(ex is OperationCanceledException)) { LoggedException executeModulesException = ex as LoggedException; if (executeModulesException is object) { ex = executeModulesException.InnerException; } _logger.LogDebug($"Exception while executing pipeline {PipelineName}/{Phase}: {ex}"); if (executeModulesException is object) { throw executeModulesException.InnerException; } } throw; } finally { stopwatch.Stop(); } } // Raise the after event await engine.Events.RaiseAsync(new AfterPipelinePhaseExecution(engine.ExecutionId, PipelineName, Phase, Outputs, elapsedMilliseconds < 0 ? 0 : elapsedMilliseconds)); // Run analyzers await RunAnalyzersAsync(engine, phaseResults, analyzerResults); // Record the results if execution actually ran if (elapsedMilliseconds >= 0) { PhaseResult phaseResult = new PhaseResult(PipelineName, Phase, Outputs, startTime, elapsedMilliseconds); phaseResults.AddOrUpdate( phaseResult.PipelineName, _ => { PhaseResult[] results = new PhaseResult[4]; results[(int)phaseResult.Phase] = phaseResult; return results; }, (_, results) => { if (results[(int)phaseResult.Phase] is object) { // Sanity check, we should never hit this throw new InvalidOperationException($"Results for phase {phaseResult.Phase} have already been added"); } results[(int)phaseResult.Phase] = phaseResult; return results; }); } } // Outputs should be set before making this call private async Task RunAnalyzersAsync( Engine engine, ConcurrentDictionary<string, PhaseResult[]> phaseResults, ConcurrentDictionary<PipelinePhase, ConcurrentBag<AnalyzerResult>> analyzerResults) { // We need to create an execution context so the async static instance is set for analyzers IServiceScopeFactory serviceScopeFactory = engine.Services.GetRequiredService<IServiceScopeFactory>(); using (IServiceScope serviceScope = serviceScopeFactory.CreateScope()) { ExecutionContextData contextData = new ExecutionContextData( this, engine, phaseResults, serviceScope.ServiceProvider); ExecutionContext executionContext = new ExecutionContext(contextData, null, null, Outputs); // Run analyzers for this pipeline and phase, don't check log level here since each document could override it ConcurrentBag<AnalyzerResult> results = new ConcurrentBag<AnalyzerResult>(); KeyValuePair<string, IAnalyzer>[] analyzerItems = engine.AnalyzerCollection .Where(analyzerItem => analyzerItem.Value.PipelinePhases?.Any(pipelinePhase => pipelinePhase.Key.Equals(PipelineName, StringComparison.OrdinalIgnoreCase) && pipelinePhase.Value == Phase) == true) .ToArray(); if (analyzerItems.Length > 0) { _logger.LogInformation($"{PipelineName}/{Phase} » Running {analyzerItems.Length} analyzers ({string.Join(", ", analyzerItems.Select(x => x.Key))})"); await analyzerItems .ParallelForEachAsync(async analyzerItem => { AnalyzerContext analyzerContext = new AnalyzerContext(contextData, Outputs, analyzerItem, results); await analyzerItem.Value.AnalyzeAsync(analyzerContext); }); } // Add the results before the error check so the exact results can be reported later if (!analyzerResults.TryAdd(this, results)) { // Sanity check, should never get here throw new InvalidOperationException($"Analyzer results for pipeline {PipelineName} already added"); } // Throw if any results are above error if (results.Any(x => x.LogLevel != LogLevel.None && x.LogLevel >= LogLevel.Error)) { throw new ExecutionException("One or more analyzers produced error results, see analyzer report following execution"); } } } public void Dispose() { if (_disposed) { throw new ObjectDisposedException(nameof(Pipeline)); } _disposed = true; DisposeModules(_modules); } private static void DisposeModules(IEnumerable<IModule> modules) { foreach (IModule module in modules) { (module as IDisposable)?.Dispose(); if (module is IEnumerable<IModule> childModules) { DisposeModules(childModules); } } } } }
45.450216
215
0.563292
[ "MIT" ]
JimBobSquarePants/Statiq.Framework
src/core/Statiq.Core/Execution/PipelinePhase.cs
10,505
C#
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System.IO; using System.Reflection; using NUnit.Compatibility; namespace NUnit.Framework.Internal { [TestFixture] public class AssemblyHelperTests { private static readonly string THIS_ASSEMBLY_PATH = "nunit.framework.tests.dll"; private static readonly string THIS_ASSEMBLY_NAME = "nunit.framework.tests"; [Test] public void GetNameForAssembly() { var assemblyName = AssemblyHelper.GetAssemblyName(this.GetType().GetTypeInfo().Assembly); Assert.That(assemblyName.Name, Is.EqualTo(THIS_ASSEMBLY_NAME).IgnoreCase); } [Test] public void GetPathForAssembly() { string path = AssemblyHelper.GetAssemblyPath(this.GetType().GetTypeInfo().Assembly); Assert.That(Path.GetFileName(path), Is.EqualTo(THIS_ASSEMBLY_PATH).IgnoreCase); Assert.That(File.Exists(path)); } // The following tests are only useful to the extent that the test cases // match what will actually be provided to the method in production. // As currently used, NUnit's codebase can only use the file: schema, // since we don't load assemblies from anything but files. The URIs // provided can be absolute file paths or UNC paths. // Local paths - Windows Drive [TestCase(@"file:///C:/path/to/assembly.dll", @"C:\path\to\assembly.dll")] [TestCase(@"file:///C:/my path/to my/assembly.dll", @"C:/my path/to my/assembly.dll")] [TestCase(@"file:///C:/dev/C#/assembly.dll", @"C:\dev\C#\assembly.dll")] [TestCase(@"file:///C:/dev/funnychars?:=/assembly.dll", @"C:\dev\funnychars?:=\assembly.dll")] // Local paths - Linux or Windows absolute without a drive [TestCase(@"file:///path/to/assembly.dll", @"/path/to/assembly.dll")] [TestCase(@"file:///my path/to my/assembly.dll", @"/my path/to my/assembly.dll")] [TestCase(@"file:///dev/C#/assembly.dll", @"/dev/C#/assembly.dll")] [TestCase(@"file:///dev/funnychars?:=/assembly.dll", @"/dev/funnychars?:=/assembly.dll")] // Windows drive specified as if it were a server - odd case, sometimes seen [TestCase(@"file://C:/path/to/assembly.dll", @"C:\path\to\assembly.dll")] [TestCase(@"file://C:/my path/to my/assembly.dll", @"C:\my path\to my\assembly.dll")] [TestCase(@"file://C:/dev/C#/assembly.dll", @"C:\dev\C#\assembly.dll")] [TestCase(@"file://C:/dev/funnychars?:=/assembly.dll", @"C:\dev\funnychars?:=\assembly.dll")] // UNC format with server and path [TestCase(@"file://server/path/to/assembly.dll", @"//server/path/to/assembly.dll")] [TestCase(@"file://server/my path/to my/assembly.dll", @"//server/my path/to my/assembly.dll")] [TestCase(@"file://server/dev/C#/assembly.dll", @"//server/dev/C#/assembly.dll")] [TestCase(@"file://server/dev/funnychars?:=/assembly.dll", @"//server/dev/funnychars?:=/assembly.dll")] // [TestCase(@"http://server/path/to/assembly.dll", "//server/path/to/assembly.dll")] public void GetAssemblyPathFromCodeBase(string uri, string expectedPath) { string localPath = AssemblyHelper.GetAssemblyPathFromCodeBase(uri); Assert.That(localPath, Is.SamePath(expectedPath)); } } }
52.707692
111
0.638938
[ "MIT" ]
304NotModified/nunit
src/NUnitFramework/tests/Internal/AssemblyHelperTests.cs
3,426
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis { internal static class StackGuard { public const int MaxUncheckedRecursionDepth = 20; public static void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > MaxUncheckedRecursionDepth) { RuntimeHelpers.EnsureSufficientExecutionStack(); } } // TODO (DevDiv workitem 966425): Replace exception name test with a type test once the type // is available in the PCL public static bool IsInsufficientExecutionStackException(Exception ex) { return ex.GetType().Name == "InsufficientExecutionStackException"; } } }
34.107143
161
0.680628
[ "MIT" ]
1Crazymoney/cs2cpp
CoreSource/InternalUtilities/StackGuard.cs
957
C#
namespace Nexmo.Api.Voice.EventWebhooks { [System.Obsolete("The Nexmo.Api.Voice.EventWebhooks.Unanswered class is obsolete. " + "References to it should be switched to the new Vonage.Voice.EventWebhooks.Unanswered class.")] public class Unanswered : CallStatusEvent { } }
33.333333
106
0.72
[ "Apache-2.0" ]
Cereal-Killa/vonage-dotnet-sdk
Vonage/LegacyNexmoLibrary/Voice/EventWebhooks/Unanswered.cs
302
C#
using System; using System.Collections; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Crypto.Parameters { public abstract class ECKeyParameters : AsymmetricKeyParameter { private static readonly string[] algorithms = { "EC", "ECDSA", "ECDH", "ECDHC", "ECGOST3410", "ECMQV" }; private readonly string algorithm; private readonly ECDomainParameters parameters; private readonly DerObjectIdentifier publicKeyParamSet; protected ECKeyParameters( string algorithm, bool isPrivate, ECDomainParameters parameters) : base(isPrivate) { if (algorithm == null) throw new ArgumentNullException("algorithm"); if (parameters == null) throw new ArgumentNullException("parameters"); this.algorithm = VerifyAlgorithmName(algorithm); this.parameters = parameters; } protected ECKeyParameters( string algorithm, bool isPrivate, DerObjectIdentifier publicKeyParamSet) : base(isPrivate) { if (algorithm == null) throw new ArgumentNullException("algorithm"); if (publicKeyParamSet == null) throw new ArgumentNullException("publicKeyParamSet"); this.algorithm = VerifyAlgorithmName(algorithm); this.parameters = LookupParameters(publicKeyParamSet); this.publicKeyParamSet = publicKeyParamSet; } public string AlgorithmName { get { return algorithm; } } public ECDomainParameters Parameters { get { return parameters; } } public DerObjectIdentifier PublicKeyParamSet { get { return publicKeyParamSet; } } public override bool Equals( object obj) { if (obj == this) return true; ECDomainParameters other = obj as ECDomainParameters; if (other == null) return false; return Equals(other); } protected bool Equals( ECKeyParameters other) { return parameters.Equals(other.parameters) && base.Equals(other); } public override int GetHashCode() { return parameters.GetHashCode() ^ base.GetHashCode(); } internal ECKeyGenerationParameters CreateKeyGenerationParameters( SecureRandom random) { if (publicKeyParamSet != null) { return new ECKeyGenerationParameters(publicKeyParamSet, random); } return new ECKeyGenerationParameters(parameters, random); } internal static string VerifyAlgorithmName(string algorithm) { string upper = Platform.ToUpperInvariant(algorithm); if (Array.IndexOf(algorithms, algorithm, 0, algorithms.Length) < 0) throw new ArgumentException("unrecognised algorithm: " + algorithm, "algorithm"); return upper; } internal static ECDomainParameters LookupParameters( DerObjectIdentifier publicKeyParamSet) { if (publicKeyParamSet == null) throw new ArgumentNullException("publicKeyParamSet"); X9ECParameters x9 = ECKeyPairGenerator.FindECCurveByOid(publicKeyParamSet); if (x9 == null) throw new ArgumentException("OID is not a valid public key parameter set", "publicKeyParamSet"); return new ECDomainParameters(x9); } } }
30.875
112
0.602733
[ "MIT" ]
0x070696E65/Symnity
Assets/Plugins/Symnity/Pulgins/crypto/src/crypto/parameters/ECKeyParameters.cs
3,952
C#
// <copyright file="Currency.cs" company="Andrey Pudov"> // Copyright (c) Andrey Pudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See LICENSE.txt in the project root for license information. // </copyright> namespace InvestmentAnalysis.Portfolio { /// <summary> /// ISO 4217 Current currency and funds code list /// </summary> public enum Currency { /// <summary> /// Invalid value of currency. /// </summary> Invalid = 0, /// <summary> /// 2 United Arab Emirates dirham United Arab Emirates /// </summary> AED = 784, /// <summary> /// 2 Afghan afghani Afghanistan /// </summary> AFN = 971, /// <summary> /// 2 Albanian lek Albania /// </summary> ALL = 008, /// <summary> /// 2 Armenian dram Armenia /// </summary> AMD = 051, /// <summary> /// 2 Netherlands Antillean guilder Curaçao (CW), Sint Maarten (SX) /// </summary> ANG = 532, /// <summary> /// 2 Angolan kwanza Angola /// </summary> AOA = 973, /// <summary> /// 2 Argentine peso Argentina /// </summary> ARS = 032, /// <summary> /// 2 Australian dollar Australia, Christmas Island (CX), Cocos (Keeling) Islands (CC), Heard Island and McDonald Islands (HM), Kiribati (KI), Nauru (NR), Norfolk Island (NF), Tuvalu (TV) /// </summary> AUD = 036, /// <summary> /// 2 Aruban florin Aruba /// </summary> AWG = 533, /// <summary> /// 2 Azerbaijani manat Azerbaijan /// </summary> AZN = 944, /// <summary> /// 2 Bosnia and Herzegovina convertible mark Bosnia and Herzegovina /// </summary> BAM = 977, /// <summary> /// 2 Barbados dollar Barbados /// </summary> BBD = 052, /// <summary> /// 2 Bangladeshi taka Bangladesh /// </summary> BDT = 050, /// <summary> /// 2 Bulgarian lev Bulgaria /// </summary> BGN = 975, /// <summary> /// 3 Bahraini dinar Bahrain /// </summary> BHD = 048, /// <summary> /// 0 Burundian franc Burundi /// </summary> BIF = 108, /// <summary> /// 2 Bermudian dollar Bermuda /// </summary> BMD = 060, /// <summary> /// 2 Brunei dollar Brunei /// </summary> BND = 096, /// <summary> /// 2 Boliviano Bolivia /// </summary> BOB = 068, /// <summary> /// 2 Bolivian Mvdol (funds code) Bolivia /// </summary> BOV = 984, /// <summary> /// 2 Brazilian real Brazil /// </summary> BRL = 986, /// <summary> /// 2 Bahamian dollar Bahamas /// </summary> BSD = 044, /// <summary> /// 2 Bhutanese ngultrum Bhutan /// </summary> BTN = 064, /// <summary> /// 2 Botswana pula Botswana /// </summary> BWP = 072, /// <summary> /// 2 Belarusian ruble Belarus /// </summary> BYN = 933, /// <summary> /// 2 Belize dollar Belize /// </summary> BZD = 084, /// <summary> /// 2 Canadian dollar Canada /// </summary> CAD = 124, /// <summary> /// 2 Congolese franc Democratic Republic of the Congo /// </summary> CDF = 976, /// <summary> /// 2 WIR Euro (complementary currency) Switzerland /// </summary> CHE = 947, /// <summary> /// 2 Swiss franc Switzerland, Liechtenstein (LI) /// </summary> CHF = 756, /// <summary> /// 2 WIR Franc (complementary currency) Switzerland /// </summary> CHW = 948, /// <summary> /// 4 Unidad de Fomento (funds code) Chile /// </summary> CLF = 990, /// <summary> /// 0 Chilean peso Chile /// </summary> CLP = 152, /// <summary> /// 2 Renminbi (Chinese) yuan China /// </summary> CNY = 156, /// <summary> /// 2 Colombian peso Colombia /// </summary> COP = 170, /// <summary> /// 2 Unidad de Valor Real (UVR) (funds code) Colombia /// </summary> COU = 970, /// <summary> /// 2 Costa Rican colon Costa Rica /// </summary> CRC = 188, /// <summary> /// 2 Cuban convertible peso Cuba /// </summary> CUC = 931, /// <summary> /// 2 Cuban peso Cuba /// </summary> CUP = 192, /// <summary> /// 2 Cape Verde escudo Cabo Verde /// </summary> CVE = 132, /// <summary> /// 2 Czech koruna Czechia /// </summary> CZK = 203, /// <summary> /// 0 Djiboutian franc Djibouti /// </summary> DJF = 262, /// <summary> /// 2 Danish krone Denmark, Faroe Islands (FO), Greenland (GL) /// </summary> DKK = 208, /// <summary> /// 2 Dominican peso Dominican Republic /// </summary> DOP = 214, /// <summary> /// 2 Algerian dinar Algeria /// </summary> DZD = 012, /// <summary> /// 2 Egyptian pound Egypt /// </summary> EGP = 818, /// <summary> /// 2 Eritrean nakfa Eritrea /// </summary> ERN = 232, /// <summary> /// 2 Ethiopian birr Ethiopia /// </summary> ETB = 230, /// <summary> /// 2 Euro Åland Islands (AX), European Union (EU), Andorra (AD), Austria (AT), Belgium (BE), Cyprus (CY), Estonia (EE), Finland (FI), France (FR), French Southern and Antarctic Lands (TF), Germany (DE), Greece (GR), Guadeloupe (GP), Ireland (IE), Italy (IT), Latvia (LV), Lithuania (LT), Luxembourg (LU), Malta (MT), French Guiana (GF), Martinique (MQ), Mayotte (YT), Monaco (MC), Montenegro (ME), Netherlands (NL), Portugal (PT), Réunion (RE), Saint Barthélemy (BL), Saint Martin (MF), Saint Pierre and Miquelon (PM), San Marino (SM), Slovakia (SK), Slovenia (SI), Spain (ES), Holy See (VA) /// </summary> EUR = 978, /// <summary> /// 2 Fiji dollar Fiji /// </summary> FJD = 242, /// <summary> /// 2 Falkland Islands pound Falkland Islands (pegged to GBP 1:1) /// </summary> FKP = 238, /// <summary> /// 2 Pound sterling United Kingdom, British Indian Ocean Territory (IO) (also uses USD), the Isle of Man (IM, see Manx pound), Jersey (JE, see Jersey pound), and Guernsey (GG, see Guernsey pound) /// </summary> GBP = 826, /// <summary> /// 2 Georgian lari Georgia /// </summary> GEL = 981, /// <summary> /// 2 Ghanaian cedi Ghana /// </summary> GHS = 936, /// <summary> /// 2 Gibraltar pound Gibraltar (pegged to GBP 1:1) /// </summary> GIP = 292, /// <summary> /// 2 Gambian dalasi Gambia /// </summary> GMD = 270, /// <summary> /// 0 Guinean franc Guinea /// </summary> GNF = 324, /// <summary> /// 2 Guatemalan quetzal Guatemala /// </summary> GTQ = 320, /// <summary> /// 2 Guyanese dollar Guyana /// </summary> GYD = 328, /// <summary> /// 2 Hong Kong dollar Hong Kong /// </summary> HKD = 344, /// <summary> /// 2 Honduran lempira Honduras /// </summary> HNL = 340, /// <summary> /// 2 Croatian kuna Croatia /// </summary> HRK = 191, /// <summary> /// 2 Haitian gourde Haiti /// </summary> HTG = 332, /// <summary> /// 2 Hungarian forint Hungary /// </summary> HUF = 348, /// <summary> /// 2 Indonesian rupiah Indonesia /// </summary> IDR = 360, /// <summary> /// 2 Israeli new shekel Israel, Palestinian Authority /// </summary> ILS = 376, /// <summary> /// 2 Indian rupee India, Bhutan /// </summary> INR = 356, /// <summary> /// 3 Iraqi dinar Iraq /// </summary> IQD = 368, /// <summary> /// 2 Iranian rial Iran /// </summary> IRR = 364, /// <summary> /// 0 Icelandic króna Iceland /// </summary> ISK = 352, /// <summary> /// 2 Jamaican dollar Jamaica /// </summary> JMD = 388, /// <summary> /// 3 Jordanian dinar Jordan /// </summary> JOD = 400, /// <summary> /// 0 Japanese yen Japan /// </summary> JPY = 392, /// <summary> /// 2 Kenyan shilling Kenya /// </summary> KES = 404, /// <summary> /// 2 Kyrgyzstani som Kyrgyzstan /// </summary> KGS = 417, /// <summary> /// 2 Cambodian riel Cambodia /// </summary> KHR = 116, /// <summary> /// 0 Comoro franc Comoros /// </summary> KMF = 174, /// <summary> /// 2 North Korean won North Korea /// </summary> KPW = 408, /// <summary> /// 0 South Korean won South Korea /// </summary> KRW = 410, /// <summary> /// 3 Kuwaiti dinar Kuwait /// </summary> KWD = 414, /// <summary> /// 2 Cayman Islands dollar Cayman Islands /// </summary> KYD = 136, /// <summary> /// 2 Kazakhstani tenge Kazakhstan /// </summary> KZT = 398, /// <summary> /// 2 Lao kip Laos /// </summary> LAK = 418, /// <summary> /// 2 Lebanese pound Lebanon /// </summary> LBP = 422, /// <summary> /// 2 Sri Lankan rupee Sri Lanka /// </summary> LKR = 144, /// <summary> /// 2 Liberian dollar Liberia /// </summary> LRD = 430, /// <summary> /// 2 Lesotho loti Lesotho /// </summary> LSL = 426, /// <summary> /// 3 Libyan dinar Libya /// </summary> LYD = 434, /// <summary> /// 2 Moroccan dirham Morocco, Western Sahara /// </summary> MAD = 504, /// <summary> /// 2 Moldovan leu Moldova /// </summary> MDL = 498, /// <summary> /// 2 Malagasy ariary Madagascar /// </summary> MGA = 969, /// <summary> /// 2 Macedonian denar North Macedonia /// </summary> MKD = 807, /// <summary> /// 2 Myanmar kyat Myanmar /// </summary> MMK = 104, /// <summary> /// 2 Mongolian tögrög Mongolia /// </summary> MNT = 496, /// <summary> /// 2 Macanese pataca Macau /// </summary> MOP = 446, /// <summary> /// 2 Mauritanian ouguiya Mauritania /// </summary> MRU = 929, /// <summary> /// 2 Mauritian rupee Mauritius /// </summary> MUR = 480, /// <summary> /// 2 Maldivian rufiyaa Maldives /// </summary> MVR = 462, /// <summary> /// 2 Malawian kwacha Malawi /// </summary> MWK = 454, /// <summary> /// 2 Mexican peso Mexico /// </summary> MXN = 484, /// <summary> /// 2 Mexican Unidad de Inversion (UDI) (funds code) Mexico /// </summary> MXV = 979, /// <summary> /// 2 Malaysian ringgit Malaysia /// </summary> MYR = 458, /// <summary> /// 2 Mozambican metical Mozambique /// </summary> MZN = 943, /// <summary> /// 2 Namibian dollar Namibia /// </summary> NAD = 516, /// <summary> /// 2 Nigerian naira Nigeria /// </summary> NGN = 566, /// <summary> /// 2 Nicaraguan córdoba Nicaragua /// </summary> NIO = 558, /// <summary> /// 2 Norwegian krone Norway, Svalbard and Jan Mayen (SJ), Bouvet Island (BV) /// </summary> NOK = 578, /// <summary> /// 2 Nepalese rupee Nepal /// </summary> NPR = 524, /// <summary> /// 2 New Zealand dollar New Zealand, Cook Islands (CK), Niue (NU), Pitcairn Islands (PN; see also Pitcairn Islands dollar), Tokelau (TK) /// </summary> NZD = 554, /// <summary> /// 3 Omani rial Oman /// </summary> OMR = 512, /// <summary> /// 2 Panamanian balboa Panama /// </summary> PAB = 590, /// <summary> /// 2 Peruvian sol Peru /// </summary> PEN = 604, /// <summary> /// 2 Papua New Guinean kina Papua New Guinea /// </summary> PGK = 598, /// <summary> /// 2 Philippine peso[14] Philippines /// </summary> PHP = 608, /// <summary> /// 2 Pakistani rupee Pakistan /// </summary> PKR = 586, /// <summary> /// 2 Polish złoty Poland /// </summary> PLN = 985, /// <summary> /// 0 Paraguayan guaraní Paraguay /// </summary> PYG = 600, /// <summary> /// 2 Qatari riyal Qatar /// </summary> QAR = 634, /// <summary> /// 2 Romanian leu Romania /// </summary> RON = 946, /// <summary> /// 2 Serbian dinar Serbia /// </summary> RSD = 941, /// <summary> /// 2 Russian ruble Russia /// </summary> RUB = 643, /// <summary> /// 0 Rwandan franc Rwanda /// </summary> RWF = 646, /// <summary> /// 2 Saudi riyal Saudi Arabia /// </summary> SAR = 682, /// <summary> /// 2 Solomon Islands dollar Solomon Islands /// </summary> SBD = 090, /// <summary> /// 2 Seychelles rupee Seychelles /// </summary> SCR = 690, /// <summary> /// 2 Sudanese pound Sudan /// </summary> SDG = 938, /// <summary> /// 2 Swedish krona/kronor Sweden /// </summary> SEK = 752, /// <summary> /// 2 Singapore dollar Singapore /// </summary> SGD = 702, /// <summary> /// 2 Saint Helena pound Saint Helena (SH-SH), Ascension Island (SH-AC), Tristan da Cunha /// </summary> SHP = 654, /// <summary> /// 2 Sierra Leonean leone Sierra Leone /// </summary> SLL = 694, /// <summary> /// 2 Somali shilling Somalia /// </summary> SOS = 706, /// <summary> /// 2 Surinamese dollar Suriname /// </summary> SRD = 968, /// <summary> /// 2 South Sudanese pound South Sudan /// </summary> SSP = 728, /// <summary> /// 2 São Tomé and Príncipe dobra São Tomé and Príncipe /// </summary> STN = 930, /// <summary> /// 2 Salvadoran colón El Salvador /// </summary> SVC = 222, /// <summary> /// 2 Syrian pound Syria /// </summary> SYP = 760, /// <summary> /// 2 Swazi lilangeni Eswatini /// </summary> SZL = 748, /// <summary> /// 2 Thai baht Thailand /// </summary> THB = 764, /// <summary> /// 2 Tajikistani somoni Tajikistan /// </summary> TJS = 972, /// <summary> /// 2 Turkmenistan manat Turkmenistan /// </summary> TMT = 934, /// <summary> /// 3 Tunisian dinar Tunisia /// </summary> TND = 788, /// <summary> /// 2 Tongan paʻanga Tonga /// </summary> TOP = 776, /// <summary> /// 2 Turkish lira Turkey /// </summary> TRY = 949, /// <summary> /// 2 Trinidad and Tobago dollar Trinidad and Tobago /// </summary> TTD = 780, /// <summary> /// 2 New Taiwan dollar Taiwan /// </summary> TWD = 901, /// <summary> /// 2 Tanzanian shilling Tanzania /// </summary> TZS = 834, /// <summary> /// 2 Ukrainian hryvnia Ukraine /// </summary> UAH = 980, /// <summary> /// 0 Ugandan shilling Uganda /// </summary> UGX = 800, /// <summary> /// 2 United States dollar United States, American Samoa (AS), Barbados (BB) (as well as Barbados Dollar), Bermuda (BM) (as well as Bermudian Dollar), British Indian Ocean Territory (IO) (also uses GBP), British Virgin Islands (VG), Caribbean Netherlands (BQ - Bonaire, Sint Eustatius and Saba), Ecuador (EC), El Salvador (SV), Guam (GU), Haiti (HT), Marshall Islands (MH), Federated States of Micronesia (FM), Northern Mariana Islands (MP), Palau (PW), Panama (PA) (as well as Panamanian Balboa), Puerto Rico (PR), Timor-Leste (TL), Turks and Caicos Islands (TC), U.S. Virgin Islands (VI), United States Minor Outlying Islands (UM) /// </summary> USD = 840, /// <summary> /// 2 United States dollar (next day) (funds code) United States /// </summary> USN = 997, /// <summary> /// 0 Uruguay Peso en Unidades Indexadas (URUIURUI) (funds code) Uruguay /// </summary> UYI = 940, /// <summary> /// 2 Uruguayan peso Uruguay /// </summary> UYU = 858, /// <summary> /// 4 Unidad previsional Uruguay /// </summary> UYW = 927, /// <summary> /// 2 Uzbekistan som Uzbekistan /// </summary> UZS = 860, /// <summary> /// 2 Venezuelan bolívar soberano Venezuela /// </summary> VES = 928, /// <summary> /// 0 Vietnamese đồng Vietnam /// </summary> VND = 704, /// <summary> /// 0 Vanuatu vatu Vanuatu /// </summary> VUV = 548, /// <summary> /// 2 Samoan tala Samoa /// </summary> WST = 882, /// <summary> /// 0 CFA franc BEAC Cameroon (CM), Central African Republic (CF), Republic of the Congo (CG), Chad (TD), Equatorial Guinea (GQ), Gabon (GA) /// </summary> XAF = 950, /// <summary> /// . Silver (one troy ounce) /// </summary> XAG = 961, /// <summary> /// . Gold (one troy ounce) /// </summary> XAU = 959, /// <summary> /// . European Composite Unit (EURCO) (bond market unit) /// </summary> XBA = 955, /// <summary> /// . European Monetary Unit (E.M.U.-6) (bond market unit) /// </summary> XBB = 956, /// <summary> /// . European Unit of Account 9 (E.U.A.-9) (bond market unit) /// </summary> XBC = 957, /// <summary> /// . European Unit of Account 17 (E.U.A.-17) (bond market unit) /// </summary> XBD = 958, /// <summary> /// 2 East Caribbean dollar Anguilla (AI), Antigua and Barbuda (AG), Dominica (DM), Grenada (GD), Montserrat (MS), Saint Kitts and Nevis (KN), Saint Lucia (LC), Saint Vincent and the Grenadines (VC) /// </summary> XCD = 951, /// <summary> /// . Special drawing rights International Monetary Fund /// </summary> XDR = 960, /// <summary> /// 0 CFA franc BCEAO Benin (BJ), Burkina Faso (BF), Côte d'Ivoire (CI), Guinea-Bissau (GW), Mali (ML), Niger (NE), Senegal (SN), Togo (TG) /// </summary> XOF = 952, /// <summary> /// . Palladium (one troy ounce) /// </summary> XPD = 964, /// <summary> /// 0 CFP franc (franc Pacifique) French territories of the Pacific Ocean: French Polynesia (PF), New Caledonia (NC), Wallis and Futuna (WF) /// </summary> XPF = 953, /// <summary> /// . Platinum (one troy ounce) /// </summary> XPT = 962, /// <summary> /// . SUCRE Unified System for Regional Compensation (SUCRE) /// </summary> XSU = 994, /// <summary> /// . Code reserved for testing /// </summary> XTS = 963, /// <summary> /// ADB Unit of Account African Development Bank /// </summary> XUA = 965, /// <summary> /// No currency /// </summary> XXX = 999, /// <summary> /// 2 Yemeni rial Yemen /// </summary> YER = 886, /// <summary> /// 2 South African rand Lesotho, Namibia, South Africa /// </summary> ZAR = 710, /// <summary> /// 2 Zambian kwacha Zambia /// </summary> ZMW = 967, /// <summary> /// 2 Zimbabwean dollar Zimbabwe /// </summary> ZWL = 932 } }
24.060241
640
0.452998
[ "Apache-2.0" ]
andreypudov/InvestmentAnalysis
src/InvestmentAnalysis.Portfolio/Currency.cs
21,992
C#
using System; using System.Runtime.CompilerServices; using Binaron.Serializer.Enums; using Binaron.Serializer.Extensions; using Binaron.Serializer.Infrastructure; namespace Binaron.Serializer.Accessors { internal static class MemberSetterHandlers { internal class BoolHandler : MemberSetterHandlerBase<ReaderState, bool> { public BoolHandler(MemberSetter<bool> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override bool HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsBool(reader); } internal class ByteHandler : MemberSetterHandlerBase<ReaderState, byte> { public ByteHandler(MemberSetter<byte> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override byte HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsByte(reader); } internal class CharHandler : MemberSetterHandlerBase<ReaderState, char> { public CharHandler(MemberSetter<char> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override char HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsChar(reader); } internal class DateTimeHandler : MemberSetterHandlerBase<ReaderState, DateTime> { public DateTimeHandler(MemberSetter<DateTime> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override DateTime HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsDateTime(reader); } internal class DecimalHandler : MemberSetterHandlerBase<ReaderState, decimal> { public DecimalHandler(MemberSetter<decimal> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override decimal HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsDecimal(reader); } internal class DoubleHandler : MemberSetterHandlerBase<ReaderState, double> { public DoubleHandler(MemberSetter<double> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override double HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsDouble(reader); } internal class ShortHandler : MemberSetterHandlerBase<ReaderState, short> { public ShortHandler(MemberSetter<short> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override short HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsShort(reader); } internal class IntHandler : MemberSetterHandlerBase<ReaderState, int> { public IntHandler(MemberSetter<int> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override int HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsInt(reader); } internal class LongHandler : MemberSetterHandlerBase<ReaderState, long> { public LongHandler(MemberSetter<long> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override long HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsLong(reader); } internal class SByteHandler : MemberSetterHandlerBase<ReaderState, sbyte> { public SByteHandler(MemberSetter<sbyte> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override sbyte HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsSByte(reader); } internal class FloatHandler : MemberSetterHandlerBase<ReaderState, float> { public FloatHandler(MemberSetter<float> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override float HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsFloat(reader); } internal class UShortHandler : MemberSetterHandlerBase<ReaderState, ushort> { public UShortHandler(MemberSetter<ushort> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override ushort HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsUShort(reader); } internal class UIntHandler : MemberSetterHandlerBase<ReaderState, uint> { public UIntHandler(MemberSetter<uint> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override uint HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsUInt(reader); } internal class ULongHandler : MemberSetterHandlerBase<ReaderState, ulong> { public ULongHandler(MemberSetter<ulong> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override ulong HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsULong(reader); } internal class StringHandler : MemberSetterHandlerBase<ReaderState, string> { public StringHandler(MemberSetter<string> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override string HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsString(reader); } internal class StructObjectHandler<T> : MemberSetterHandlerBase<ReaderState, object> where T : struct { public StructObjectHandler(MemberSetter<object> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override object HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsObject<T>(reader); } internal class ClassObjectHandler<T> : MemberSetterHandlerBase<ReaderState, object> where T : class { public ClassObjectHandler(MemberSetter<object> setter) : base(setter) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override object HandleInternal(ReaderState reader) => SelfUpgradingReader.ReadAsObject<T>(reader); } internal class ObjectHandler : MemberSetterHandlerBase<ReaderState, object> { private readonly IHandler handler; public ObjectHandler(MemberSetter<object> setter) : base(setter) { var memberType = setter.MemberInfo.GetMemberType(); handler = (IHandler) Activator.CreateInstance(typeof(Handler<>).MakeGenericType(memberType)); } private interface IHandler { [MethodImpl(MethodImplOptions.AggressiveInlining)] object Handle(ReaderState reader); } private class Handler<T> : IHandler { [MethodImpl(MethodImplOptions.AggressiveInlining)] public object Handle(ReaderState reader) { var valueType = (SerializedType) reader.Read<byte>(); switch (valueType) { case SerializedType.Null: return null; case SerializedType.CustomObject: var identifier = Deserializer.ReadValue(reader); return TypedDeserializer.ReadObject<T>(reader, identifier); case SerializedType.Object: return TypedDeserializer.ReadObject<T>(reader); case SerializedType.Dictionary: return TypedDeserializer.ReadDictionary<T>(reader); case SerializedType.List: return TypedDeserializer.ReadList<T>(reader); case SerializedType.Enumerable: return TypedDeserializer.ReadEnumerable<T>(reader); case SerializedType.String: return Reader.ReadString(reader); case SerializedType.Char: return Reader.ReadChar(reader); case SerializedType.Byte: return Reader.ReadByte(reader); case SerializedType.SByte: return Reader.ReadSByte(reader); case SerializedType.UShort: return Reader.ReadUShort(reader); case SerializedType.Short: return Reader.ReadShort(reader); case SerializedType.UInt: return Reader.ReadUInt(reader); case SerializedType.Int: return Reader.ReadInt(reader); case SerializedType.ULong: return Reader.ReadULong(reader); case SerializedType.Long: return Reader.ReadLong(reader); case SerializedType.Float: return Reader.ReadFloat(reader); case SerializedType.Double: return Reader.ReadDouble(reader); case SerializedType.Decimal: return Reader.ReadDecimal(reader); case SerializedType.Bool: return Reader.ReadBool(reader); case SerializedType.DateTime: return Reader.ReadDateTime(reader); default: throw new ArgumentOutOfRangeException(); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override object HandleInternal(ReaderState reader) => handler.Handle(reader); } } }
42.51938
122
0.581039
[ "MIT" ]
JTOne123/Binaron.Serializer
src/Binaron.Serializer/Accessors/MemberSetterHandlers.cs
10,970
C#
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Roslynator.CSharp.CSharpFactory; namespace Roslynator.CSharp.Refactorings { internal static class AddMissingCasesToSwitchStatementRefactoring { private const string Title = "Add missing cases"; public static void ComputeRefactoring( RefactoringContext context, SwitchStatementSyntax switchStatement, SemanticModel semanticModel) { ExpressionSyntax expression = switchStatement.Expression; if (expression?.IsMissing != false) return; SyntaxList<SwitchSectionSyntax> sections = switchStatement.Sections; ISymbol symbol = semanticModel.GetSymbol(expression, context.CancellationToken); if (symbol?.IsErrorType() != false) return; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, context.CancellationToken); if (typeSymbol?.TypeKind != TypeKind.Enum) return; if (!typeSymbol.ContainsMember<IFieldSymbol>()) return; if (sections.Any() && !ContainsOnlyDefaultSection(sections)) { if (context.Span.IsEmptyAndContainedInSpan(switchStatement.SwitchKeyword)) { ImmutableArray<ISymbol> members = typeSymbol.GetMembers(); if (members.Length == 0) return; var fieldsToValue = new Dictionary<object, IFieldSymbol>(members.Length); foreach (ISymbol member in members) { if (member.Kind == SymbolKind.Field) { var fieldSymbol = (IFieldSymbol)member; if (fieldSymbol.HasConstantValue) { object constantValue = fieldSymbol.ConstantValue; if (!fieldsToValue.ContainsKey(constantValue)) fieldsToValue.Add(constantValue, fieldSymbol); } } } foreach (SwitchSectionSyntax section in sections) { foreach (SwitchLabelSyntax label in section.Labels) { if (label is CaseSwitchLabelSyntax caseLabel) { ExpressionSyntax value = caseLabel.Value.WalkDownParentheses(); if (value?.IsMissing == false) { Optional<object> optional = semanticModel.GetConstantValue(value, context.CancellationToken); if (optional.HasValue && fieldsToValue.Remove(optional.Value) && fieldsToValue.Count == 0) { return; } } } } } Document document = context.Document; context.RegisterRefactoring( Title, ct => AddCasesAsync(document, switchStatement, fieldsToValue.Select(f => f.Value), ct), RefactoringDescriptors.AddMissingCasesToSwitchStatement); } } else if (context.IsRefactoringEnabled(RefactoringDescriptors.AddMissingCasesToSwitchStatement)) { Document document = context.Document; context.RegisterRefactoring( Title, ct => AddCasesAsync(document, switchStatement, semanticModel, ct), RefactoringDescriptors.AddMissingCasesToSwitchStatement); } } private static Task<Document> AddCasesAsync( Document document, SwitchStatementSyntax switchStatement, SemanticModel semanticModel, CancellationToken cancellationToken) { var enumTypeSymbol = semanticModel.GetTypeInfo(switchStatement.Expression, cancellationToken).ConvertedType as INamedTypeSymbol; TypeSyntax enumType = enumTypeSymbol.ToMinimalTypeSyntax(semanticModel, switchStatement.OpenBraceToken.FullSpan.End); cancellationToken.ThrowIfCancellationRequested(); SyntaxList<StatementSyntax> statements = SingletonList<StatementSyntax>(BreakStatement()); ImmutableArray<ISymbol> members = enumTypeSymbol.GetMembers(); var newSections = new List<SwitchSectionSyntax>(members.Length); foreach (ISymbol memberSymbol in members) { if (memberSymbol.Kind == SymbolKind.Field) newSections.Add(CreateSwitchSection(memberSymbol, enumType, statements)); } newSections.Add(SwitchSection( SingletonList<SwitchLabelSyntax>(DefaultSwitchLabel()), statements)); SwitchStatementSyntax newSwitchStatement = switchStatement .WithSections(newSections.ToSyntaxList()) .WithFormatterAnnotation(); return document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken); } private static Task<Document> AddCasesAsync( Document document, SwitchStatementSyntax switchStatement, IEnumerable<IFieldSymbol> fieldSymbols, CancellationToken cancellationToken) { SyntaxList<SwitchSectionSyntax> sections = switchStatement.Sections; TypeSyntax enumType = fieldSymbols.First().ContainingType.ToTypeSyntax().WithSimplifierAnnotation(); SyntaxList<StatementSyntax> statements = SingletonList<StatementSyntax>(BreakStatement()); cancellationToken.ThrowIfCancellationRequested(); SyntaxList<SwitchSectionSyntax> newSections = fieldSymbols .Select(fieldSymbol => CreateSwitchSection(fieldSymbol, enumType, statements)) .ToSyntaxList(); int insertIndex = sections.Count; if (sections.Last().ContainsDefaultLabel()) insertIndex--; SwitchStatementSyntax newSwitchStatement = switchStatement .WithSections(sections.InsertRange(insertIndex, newSections)) .WithFormatterAnnotation(); return document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken); } private static SwitchSectionSyntax CreateSwitchSection(ISymbol symbol, TypeSyntax enumType, SyntaxList<StatementSyntax> statements) { return SwitchSection( SingletonList<SwitchLabelSyntax>( CaseSwitchLabel( SimpleMemberAccessExpression( enumType, IdentifierName(symbol.Name)))), statements); } private static bool ContainsOnlyDefaultSection(SyntaxList<SwitchSectionSyntax> sections) { return sections .SingleOrDefault(shouldThrow: false)? .Labels .SingleOrDefault(shouldThrow: false)? .Kind() == SyntaxKind.DefaultSwitchLabel; } } }
40.365
156
0.57649
[ "Apache-2.0" ]
ProphetLamb-Organistion/Roslynator
src/Refactorings/CSharp/Refactorings/AddMissingCasesToSwitchStatementRefactoring.cs
8,075
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Foolproof { [AttributeUsage(AttributeTargets.Property)] public abstract class ModelAwareValidationAttribute : ValidationAttribute { public ModelAwareValidationAttribute() { } static ModelAwareValidationAttribute() { Register.All(); } public override bool IsValid(object value) { return true; } public override string FormatErrorMessage(string name) { if (string.IsNullOrEmpty(ErrorMessageResourceName) && string.IsNullOrEmpty(ErrorMessage)) ErrorMessage = DefaultErrorMessage; return base.FormatErrorMessage(name); } public virtual string DefaultErrorMessage { get { return "{0} is invalid."; } } public abstract bool IsValid(object value, object container); public virtual string ClientTypeName { get { return this.GetType().Name.Replace("Attribute", ""); } } protected virtual IEnumerable<KeyValuePair<string, object>> GetClientValidationParameters() { return new KeyValuePair<string, object>[0]; } public Dictionary<string, object> ClientValidationParameters { get { return GetClientValidationParameters().ToDictionary(kv => kv.Key.ToLower(), kv => kv.Value); } } } }
28.888889
112
0.611538
[ "MIT" ]
Vahalas/foolproof
Foolproof/Base Classes/ModelAwareValidationAttribute.cs
1,562
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Lette.ProjectEuler.Core.Runner { public class Solver : ISolver { private Action<Solution> _callback; private CancellationTokenSource _tokenSource; public async Task SolveAllAsync( IEnumerable<IProblem> problems, Action<Solution> callback, bool runParallel) { await Task.Run(() => SolveAll(problems, callback, runParallel)); } public void SolveAll(IEnumerable<IProblem> problems, Action<Solution> callback, bool runParallel) { _tokenSource = new CancellationTokenSource(); _callback = callback; var options = new ParallelOptions(); options.MaxDegreeOfParallelism = runParallel ? -1 : 1; Parallel.ForEach(problems, options, (problem, loopState) => { if (_tokenSource.IsCancellationRequested) { loopState.Stop(); } Solve(problem, _tokenSource.Token); }); } private void Solve(IProblem problem, CancellationToken token) { if (token.IsCancellationRequested) { return; } var stopwatch = new Stopwatch(); var metaData = problem.GetMetaData(); problem.SetCancellationToken(token); var canceled = false; Exception exception = null; long? result = null; try { // Use "Prepare" for loading initial data structures that are part of the problem definition, // and which should not - with a good conscience - be a part of the timed solution. problem.Prepare(); stopwatch.Reset(); stopwatch.Start(); result = problem.Solve(); } catch (OperationCanceledException) { canceled = true; } catch (Exception ex) { exception = ex; } finally { stopwatch.Stop(); } var solution = new Solution(); solution.Number = metaData.Number; solution.Description = metaData.Description; solution.ExpectedAnswer = metaData.Answer; solution.ProposedAnswer = result; solution.IsCanceled = canceled; solution.Exception = exception; solution.ElapsedTime = stopwatch.Elapsed; _callback(solution); } public void Cancel() { if (_tokenSource == null) { return; } if (_tokenSource.IsCancellationRequested) { return; } _tokenSource.Cancel(); } } }
29.12963
110
0.502543
[ "MIT" ]
Lette/Lette.ProjectEuler.Core
Lette.ProjectEuler.Core/Runner/Solver.cs
3,148
C#
version https://git-lfs.github.com/spec/v1 oid sha256:deda80f48113742cdc86686be453ded2924a4dad7b271316afc8d5f17e36c770 size 19605
32.5
75
0.884615
[ "MIT" ]
kenx00x/ahhhhhhhhhhhh
ahhhhhhhhhh/Library/PackageCache/com.unity.visualeffectgraph@7.1.8/Editor/Core/VFXLibrary.cs
130
C#
using System; using System.Windows; using System.Windows.Shell; using System.Windows.Threading; using TwitchLeecher.Core.Models; using TwitchLeecher.Gui.Services; namespace TwitchLeecher.Gui.Views { public partial class SearchWindow : Window { private IGuiService guiService; public SearchWindow(IGuiService guiService) { this.guiService = guiService; InitializeComponent(); WindowChrome windowChrome = new WindowChrome() { CaptionHeight = 51, CornerRadius = new CornerRadius(0), GlassFrameThickness = new Thickness(0), NonClientFrameEdges = NonClientFrameEdges.None, ResizeBorderThickness = new Thickness(0), UseAeroCaptionButtons = false }; WindowChrome.SetWindowChrome(this, windowChrome); this.cmbLoadLimit.ItemsSource = Preferences.GetLoadLimits(); this.Loaded += SearchRequestView_Loaded; } private void SearchRequestView_Loaded(object sender, System.Windows.RoutedEventArgs e) { try { this.txtUsername.Focus(); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.DataBind, new Action(() => { this.txtUsername.SelectAll(); })); } catch (Exception ex) { this.guiService.ShowAndLogException(ex); } } } }
28.833333
102
0.579961
[ "MIT" ]
dstftw/TwitchLeecher
TwitchLeecher/TwitchLeecher.Gui/Views/SearchWindow.xaml.cs
1,559
C#
namespace _08.Snowballs { using System; using System.Numerics; class Snowballs { static void Main(string[] args) { int count = int.Parse(Console.ReadLine()); int snow = 0; int time = 0; int quality = 0; BigInteger maxSum = -1; for (int i = 0; i < count; i++) { int currentSnow = int.Parse(Console.ReadLine()); int currentTime = int.Parse(Console.ReadLine()); int currentQuality = int.Parse(Console.ReadLine()); BigInteger currentSum = BigInteger.Pow((currentSnow / currentTime), currentQuality); if (currentSum > maxSum) { maxSum = currentSum; snow = currentSnow; time = currentTime; quality = currentQuality; } } Console.WriteLine($"{snow} : {time} = {maxSum} ({quality})"); } } }
27.891892
100
0.468992
[ "MIT" ]
grekssi/Softuni-Courses
SoftUni/01. .NET Courses/02. Technology Fundamentals - C#/03. Data Types and Variables/Exercises/08.Snowballs/Snowballs.cs
1,034
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CS_MovieTicketBookingApp.Master_Pages { public partial class MasterPage_Login_Admin { /// <summary> /// SUB_HEAD_LOGIN_ADMIN_CONTENTPLACEHOLDER control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder SUB_HEAD_LOGIN_ADMIN_CONTENTPLACEHOLDER; /// <summary> /// SMDS1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.SiteMapDataSource SMDS1; /// <summary> /// MAIN_MENU control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Menu MAIN_MENU; /// <summary> /// SUB_BODY_LOGIN_ADMIN_CONTENTPLACEHOLDER control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder SUB_BODY_LOGIN_ADMIN_CONTENTPLACEHOLDER; } }
36.519231
111
0.556082
[ "MIT" ]
AkshayBhanawala/ASP-MovieTicketBookSystem
CS_MovieTicketBookingApp/Master_Pages/MasterPage_Login_Admin.Master.designer.cs
1,901
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IIndexManager.cs" company="nGratis"> // The MIT License (MIT) // // Copyright (c) 2014 - 2021 Cahya Ong // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </copyright> // <author>Cahya Ong - cahya.ong@gmail.com</author> // <creation_timestamp>Saturday, 10 November 2018 5:41:54 AM UTC</creation_timestamp> // -------------------------------------------------------------------------------------------------------------------- namespace nGratis.AI.Kvasir.Core { using System; using Lucene.Net.Index; public interface IIndexManager : IDisposable { bool HasIndex(IndexKind indexKind); IndexReader FindIndexReader(IndexKind indexKind); IndexWriter FindIndexWriter(IndexKind indexKind); } }
45.666667
120
0.645464
[ "MIT" ]
cahyaong/ai.kvasir
Source/Kvasir.Core/IO/IIndexManager.cs
1,920
C#
 namespace LAB001 { partial class SignIn { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SignIn)); this.label1 = new System.Windows.Forms.Label(); this.nameLb = new System.Windows.Forms.Label(); this.passwordLb = new System.Windows.Forms.Label(); this.passwordConfirmLb = new System.Windows.Forms.Label(); this.name = new System.Windows.Forms.TextBox(); this.number = new System.Windows.Forms.TextBox(); this.password = new System.Windows.Forms.TextBox(); this.adminChk = new System.Windows.Forms.CheckBox(); this.Submit = new System.Windows.Forms.Button(); this.passwordConfirm = new System.Windows.Forms.TextBox(); this.numberLb = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("华文中宋", 26.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label1.ForeColor = System.Drawing.Color.DimGray; this.label1.Location = new System.Drawing.Point(614, 38); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(87, 40); this.label1.TabIndex = 100; this.label1.Text = "注册"; // // nameLb // this.nameLb.AutoSize = true; this.nameLb.BackColor = System.Drawing.Color.Transparent; this.nameLb.Font = new System.Drawing.Font("华文中宋", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.nameLb.ForeColor = System.Drawing.Color.DimGray; this.nameLb.Location = new System.Drawing.Point(390, 126); this.nameLb.Name = "nameLb"; this.nameLb.Size = new System.Drawing.Size(108, 27); this.nameLb.TabIndex = 101; this.nameLb.Text = "真实姓名"; // // passwordLb // this.passwordLb.AutoSize = true; this.passwordLb.BackColor = System.Drawing.Color.Transparent; this.passwordLb.Font = new System.Drawing.Font("华文中宋", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.passwordLb.ForeColor = System.Drawing.Color.DimGray; this.passwordLb.Location = new System.Drawing.Point(438, 349); this.passwordLb.Name = "passwordLb"; this.passwordLb.Size = new System.Drawing.Size(60, 27); this.passwordLb.TabIndex = 103; this.passwordLb.Text = "密码"; this.passwordLb.Click += new System.EventHandler(this.label3_Click); // // passwordConfirmLb // this.passwordConfirmLb.AutoSize = true; this.passwordConfirmLb.BackColor = System.Drawing.Color.Transparent; this.passwordConfirmLb.Font = new System.Drawing.Font("华文中宋", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.passwordConfirmLb.ForeColor = System.Drawing.Color.DimGray; this.passwordConfirmLb.Location = new System.Drawing.Point(390, 464); this.passwordConfirmLb.Name = "passwordConfirmLb"; this.passwordConfirmLb.Size = new System.Drawing.Size(108, 27); this.passwordConfirmLb.TabIndex = 104; this.passwordConfirmLb.Text = "确认密码"; this.passwordConfirmLb.Click += new System.EventHandler(this.label4_Click); // // name // this.name.BackColor = System.Drawing.Color.White; this.name.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.name.Location = new System.Drawing.Point(749, 128); this.name.Name = "name"; this.name.Size = new System.Drawing.Size(141, 30); this.name.TabIndex = 1; // // number // this.number.BackColor = System.Drawing.Color.White; this.number.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.number.Location = new System.Drawing.Point(749, 237); this.number.Name = "number"; this.number.Size = new System.Drawing.Size(141, 30); this.number.TabIndex = 2; // // password // this.password.BackColor = System.Drawing.Color.White; this.password.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.password.Location = new System.Drawing.Point(749, 351); this.password.Name = "password"; this.password.Size = new System.Drawing.Size(141, 30); this.password.TabIndex = 3; this.password.UseSystemPasswordChar = true; this.password.TextChanged += new System.EventHandler(this.textBox3_TextChanged); // // adminChk // this.adminChk.AutoSize = true; this.adminChk.BackColor = System.Drawing.Color.Transparent; this.adminChk.Font = new System.Drawing.Font("华文中宋", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.adminChk.Location = new System.Drawing.Point(736, 590); this.adminChk.Name = "adminChk"; this.adminChk.Size = new System.Drawing.Size(129, 27); this.adminChk.TabIndex = 5; this.adminChk.Text = "申请管理员"; this.adminChk.UseVisualStyleBackColor = false; this.adminChk.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged); // // Submit // this.Submit.BackColor = System.Drawing.Color.Transparent; this.Submit.Cursor = System.Windows.Forms.Cursors.Hand; this.Submit.FlatAppearance.BorderSize = 0; this.Submit.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent; this.Submit.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent; this.Submit.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.Submit.ForeColor = System.Drawing.Color.Transparent; this.Submit.Location = new System.Drawing.Point(579, 580); this.Submit.Name = "Submit"; this.Submit.Size = new System.Drawing.Size(122, 50); this.Submit.TabIndex = 6; this.Submit.UseVisualStyleBackColor = false; this.Submit.Click += new System.EventHandler(this.Submit_Click); // // passwordConfirm // this.passwordConfirm.BackColor = System.Drawing.Color.White; this.passwordConfirm.Font = new System.Drawing.Font("宋体", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.passwordConfirm.Location = new System.Drawing.Point(749, 466); this.passwordConfirm.Name = "passwordConfirm"; this.passwordConfirm.Size = new System.Drawing.Size(141, 30); this.passwordConfirm.TabIndex = 4; this.passwordConfirm.UseSystemPasswordChar = true; // // numberLb // this.numberLb.AutoSize = true; this.numberLb.BackColor = System.Drawing.Color.Transparent; this.numberLb.Font = new System.Drawing.Font("华文中宋", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.numberLb.ForeColor = System.Drawing.Color.DimGray; this.numberLb.Location = new System.Drawing.Point(400, 235); this.numberLb.Name = "numberLb"; this.numberLb.Size = new System.Drawing.Size(98, 27); this.numberLb.TabIndex = 102; this.numberLb.Text = "学/工号"; this.numberLb.Click += new System.EventHandler(this.label5_Click); // // SignIn // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = global::LAB001.Properties.Resources.signin; this.ClientSize = new System.Drawing.Size(1264, 681); this.Controls.Add(this.numberLb); this.Controls.Add(this.passwordConfirm); this.Controls.Add(this.Submit); this.Controls.Add(this.adminChk); this.Controls.Add(this.password); this.Controls.Add(this.number); this.Controls.Add(this.name); this.Controls.Add(this.passwordConfirmLb); this.Controls.Add(this.passwordLb); this.Controls.Add(this.nameLb); this.Controls.Add(this.label1); this.ForeColor = System.Drawing.Color.DimGray; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "SignIn"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "注册"; this.Load += new System.EventHandler(this.signin_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label nameLb; private System.Windows.Forms.Label passwordLb; private System.Windows.Forms.Label passwordConfirmLb; private System.Windows.Forms.TextBox name; private System.Windows.Forms.TextBox number; private System.Windows.Forms.TextBox password; private System.Windows.Forms.CheckBox adminChk; private System.Windows.Forms.Button Submit; private System.Windows.Forms.TextBox passwordConfirm; private System.Windows.Forms.Label numberLb; } }
51.522727
163
0.610587
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
GNAQ/dotnet-lecturelab1
LAB001/signin.Designer.cs
11,445
C#
using MvcTemplate.Components.Mvc; using MvcTemplate.Objects; using MvcTemplate.Resources.Form; using System; using System.Linq; using System.Web.Mvc; using Xunit; namespace MvcTemplate.Tests.Unit.Components.Mvc { public class DateValidatorTests { private DateValidator validator; private ModelMetadata metadata; public DateValidatorTests() { metadata = new DisplayNameMetadataProvider().GetMetadataForProperty(null, typeof(AccountView), "Username"); validator = new DateValidator(metadata, new ControllerContext()); } #region Validate(Object container) [Fact] public void Validate_ReturnsEmpty() { Assert.Empty(validator.Validate(null)); } #endregion #region GetClientValidationRules() [Fact] public void GetClientValidationRules_ReturnsDateValidationRule() { ModelClientValidationRule actual = validator.GetClientValidationRules().Single(); ModelClientValidationRule expected = new ModelClientValidationRule { ValidationType = "date", ErrorMessage = String.Format(Validations.Date, metadata.GetDisplayName()) }; Assert.Equal(expected.ValidationParameters, actual.ValidationParameters); Assert.Equal(expected.ValidationType, actual.ValidationType); Assert.Equal(expected.ErrorMessage, actual.ErrorMessage); } #endregion } }
29.5
119
0.660365
[ "MIT" ]
conglc/Asp-MVC-5
test/MvcTemplate.Tests/Unit/Components/Mvc/Validators/DateValidatorTests.cs
1,536
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.7 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace OSGeo.GDAL { using System; using System.Runtime.InteropServices; public class SWIGTYPE_p_int { private HandleRef swigCPtr; public SWIGTYPE_p_int(IntPtr cPtr, bool futureUse, object parent) { swigCPtr = new HandleRef(this, cPtr); } protected SWIGTYPE_p_int() { swigCPtr = new HandleRef(null, IntPtr.Zero); } public static HandleRef getCPtr(SWIGTYPE_p_int obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } } }
27.516129
83
0.581477
[ "BSD-3-Clause" ]
imincik/pkg-gdal
swig/csharp/gdal/SWIGTYPE_p_int.cs
853
C#
using OpenBots.Commands.Terminal.Library; using OpenBots.Core.Attributes.PropertyAttributes; using OpenBots.Core.Command; using OpenBots.Core.Enums; using OpenBots.Core.Infrastructure; using OpenBots.Core.Properties; using OpenBots.Core.Utilities.CommonUtilities; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using System.Windows.Forms; namespace OpenBots.Commands.BZTerminal { [Serializable] [Category("BlueZone Terminal Commands")] [Description("This command waits for text to appear on a targeted terminal screen.")] public class BZTerminalWaitForTextCommand : ScriptCommand { [Required] [DisplayName("BZ Terminal Instance Name")] [Description("Enter the unique instance that was specified in the **Create BZ Terminal Session** command.")] [SampleUsage("MyBZTerminalInstance")] [Remarks("Failure to enter the correct instance or failure to first call the **Create BZ Terminal Session** command will cause an error.")] [CompatibleTypes(new Type[] { typeof(BZTerminalContext) })] public string v_InstanceName { get; set; } [Required] [DisplayName("Text to Wait for")] [Description("Enter the text to wait for on the terminal.")] [SampleUsage("\"Hello, World!\" || vText")] [Remarks("")] [Editor("ShowVariableHelper", typeof(UIAdditionalHelperType))] [CompatibleTypes(new Type[] { typeof(string) })] public string v_TextToWaitFor { get; set; } [Required] [DisplayName("Timeout (Seconds)")] [Description("Specify how many seconds to wait before throwing an exception.")] [SampleUsage("30 || vSeconds")] [Remarks("")] [Editor("ShowVariableHelper", typeof(UIAdditionalHelperType))] [CompatibleTypes(new Type[] { typeof(int) })] public string v_Timeout { get; set; } public BZTerminalWaitForTextCommand() { CommandName = "BZTerminalWaitForTextCommand"; SelectionName = "BZ Wait For Text"; CommandEnabled = true; CommandIcon = Resources.command_system; v_InstanceName = "DefaultBZTerminal"; v_Timeout = "30"; } public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; string textToWaitFor = (string)await v_TextToWaitFor.EvaluateCode(engine); var timeout = (int)await v_Timeout.EvaluateCode(engine); var terminalContext = (BZTerminalContext)v_InstanceName.GetAppInstance(engine); if (terminalContext.BZTerminalObj == null || !terminalContext.BZTerminalObj.Connected) throw new Exception($"Terminal Instance {v_InstanceName} is not connected."); terminalContext.BZTerminalObj.WaitForText(textToWaitFor, 0, 0, timeout); } public override List<Control> Render(IfrmCommandEditor editor, ICommandControls commandControls) { base.Render(editor, commandControls); RenderedControls.AddRange(commandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); RenderedControls.AddRange(commandControls.CreateDefaultInputGroupFor("v_TextToWaitFor", this, editor)); RenderedControls.AddRange(commandControls.CreateDefaultInputGroupFor("v_Timeout", this, editor)); return RenderedControls; } public override string GetDisplayValue() { return base.GetDisplayValue() + $" [Text '{v_TextToWaitFor}' - Instance Name '{v_InstanceName}']"; } } }
38.367816
141
0.759437
[ "Apache-2.0" ]
arenabilgisayar/OpenBots.Studio
OpenBots.Commands/OpenBots.Commands.Terminal/OpenBots.Commands.BZTerminal/BZTerminalWaitForTextCommand.cs
3,340
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.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public abstract class Accept<T> : SocketTestHelperBase<T> where T : SocketHelperBase, new() { public Accept(ITestOutputHelper output) : base(output) { } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(Loopbacks))] public async Task Accept_Success(IPAddress listenAt) { using (Socket listen = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { int port = listen.BindToAnonymousPort(listenAt); listen.Listen(1); Task<Socket> acceptTask = AcceptAsync(listen); Assert.False(acceptTask.IsCompleted); using (Socket client = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, new IPEndPoint(listenAt, port)); Socket accept = await acceptTask; Assert.NotNull(accept); Assert.True(accept.Connected); Assert.Equal(client.LocalEndPoint, accept.RemoteEndPoint); Assert.Equal(accept.LocalEndPoint, client.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(2)] [InlineData(5)] public async Task Accept_ConcurrentAcceptsBeforeConnects_Success(int numberAccepts) { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Listen(listener, numberAccepts); var clients = new Socket[numberAccepts]; var servers = new Task<Socket>[numberAccepts]; try { for (int i = 0; i < numberAccepts; i++) { clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); servers[i] = AcceptAsync(listener); } foreach (Socket client in clients) { await ConnectAsync(client, listener.LocalEndPoint); } await Task.WhenAll(servers); Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status)); Assert.All(servers, s => Assert.NotNull(s.Result)); Assert.All(servers, s => Assert.True(s.Result.Connected)); } finally { foreach (Socket client in clients) { client?.Dispose(); } foreach (Task<Socket> server in servers) { if (server?.Status == TaskStatus.RanToCompletion) { server.Result.Dispose(); } } } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(2)] [InlineData(5)] public async Task Accept_ConcurrentAcceptsAfterConnects_Success(int numberAccepts) { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Listen(listener, numberAccepts); var clients = new Socket[numberAccepts]; var clientConnects = new Task[numberAccepts]; var servers = new Task<Socket>[numberAccepts]; try { for (int i = 0; i < numberAccepts; i++) { clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientConnects[i] = ConnectAsync(clients[i], listener.LocalEndPoint); } for (int i = 0; i < numberAccepts; i++) { servers[i] = AcceptAsync(listener); } await Task.WhenAll(clientConnects); Assert.All(clientConnects, c => Assert.Equal(TaskStatus.RanToCompletion, c.Status)); await Task.WhenAll(servers); Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status)); Assert.All(servers, s => Assert.NotNull(s.Result)); Assert.All(servers, s => Assert.True(s.Result.Connected)); } finally { foreach (Socket client in clients) { client?.Dispose(); } foreach (Task<Socket> server in servers) { if (server?.Status == TaskStatus.RanToCompletion) { server.Result.Dispose(); } } } } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public async Task Accept_WithTargetSocket_Success() { if (!SupportsAcceptIntoExistingSocket) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); Task<Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); } } [ActiveIssue(17209, TestPlatforms.AnyUnix)] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public async Task Accept_WithTargetSocket_ReuseAfterDisconnect_Success(bool reuseSocket) { if (!SupportsAcceptIntoExistingSocket) return; // APM mode fails currently. Issue: #22764 if (typeof(T) == typeof(SocketHelperApm)) return; using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Task<Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); } server.Disconnect(reuseSocket); Assert.False(server.Connected); if (reuseSocket) { using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Task<Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); } } else { SocketException se = await Assert.ThrowsAsync<SocketException>(() => AcceptAsync(listener, server)); Assert.Equal(SocketError.InvalidArgument, se.SocketErrorCode); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public void Accept_WithAlreadyBoundTargetSocket_Fails() { if (!SupportsAcceptIntoExistingSocket) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); server.BindToAnonymousPort(IPAddress.Loopback); Assert.Throws<InvalidOperationException>(() => { AcceptAsync(listener, server); }); } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public async Task Accept_WithInUseTargetSocket_Fails() { if (!SupportsAcceptIntoExistingSocket) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); Task<Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); Assert.Throws<InvalidOperationException>(() => { AcceptAsync(listener, server); }); } } [Fact] public async Task AcceptAsync_MultipleAcceptsThenDispose_AcceptsThrowAfterDispose() { if (UsesSync) { return; } for (int i = 0; i < 100; i++) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(2); Task accept1 = AcceptAsync(listener); Task accept2 = AcceptAsync(listener); listener.Dispose(); await Assert.ThrowsAnyAsync<Exception>(() => accept1); await Assert.ThrowsAnyAsync<Exception>(() => accept2); } } } [Fact] public async Task AcceptGetsCanceledByDispose() { // We try this a couple of times to deal with a timing race: if the Dispose happens // before the operation is started, we won't see a SocketException. SocketError? localSocketError = null; bool disposedException = false; for (int i = 0; i < 10 && !localSocketError.HasValue; i++) { var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task acceptTask = Task.Factory.StartNew(() => { AcceptAsync(listener).GetAwaiter().GetResult(); }, TaskCreationOptions.LongRunning); // Wait a little so the operation is started, then Dispose. await Task.Delay(100); Task disposeTask = Task.Factory.StartNew(() => { listener.Dispose(); }, TaskCreationOptions.LongRunning); Task timeoutTask = Task.Delay(30000); Assert.NotSame(timeoutTask, await Task.WhenAny(disposeTask, acceptTask, timeoutTask)); await disposeTask; try { await acceptTask; } catch (SocketException se) { localSocketError = se.SocketErrorCode; } catch (ObjectDisposedException) { disposedException = true; } if (UsesApm) { break; } } if (UsesApm) { Assert.Null(localSocketError); Assert.True(disposedException); } else { if (UsesSync) { Assert.Equal(SocketError.Interrupted, localSocketError); } else { Assert.Equal(SocketError.OperationAborted, localSocketError); } } } } public sealed class AcceptSync : Accept<SocketHelperArraySync> { public AcceptSync(ITestOutputHelper output) : base(output) {} } public sealed class AcceptSyncForceNonBlocking : Accept<SocketHelperSyncForceNonBlocking> { public AcceptSyncForceNonBlocking(ITestOutputHelper output) : base(output) {} } public sealed class AcceptApm : Accept<SocketHelperApm> { public AcceptApm(ITestOutputHelper output) : base(output) {} } public sealed class AcceptTask : Accept<SocketHelperTask> { public AcceptTask(ITestOutputHelper output) : base(output) {} } public sealed class AcceptEap : Accept<SocketHelperEap> { public AcceptEap(ITestOutputHelper output) : base(output) {} } }
38.25323
120
0.531883
[ "MIT" ]
zielmicha/corefx
src/System.Net.Sockets/tests/FunctionalTests/Accept.cs
14,804
C#
using System.Management.Automation; using Cognifide.PowerShell.Core.Extensions; using Cognifide.PowerShell.Core.Utility; using Sitecore.Data.Items; using Sitecore.Security.AccessControl; namespace Cognifide.PowerShell.Commandlets.Security.Items { [Cmdlet(VerbsCommon.Set, "ItemAcl", SupportsShouldProcess = true)] [OutputType(typeof (Item))] public class SetItemAclCommand : BaseLanguageAgnosticItemCommand { [Parameter(ParameterSetName = "Item from Path", Mandatory = true)] [Parameter(ParameterSetName = "Item from ID", Mandatory = true)] [Parameter(ParameterSetName = "Item from Pipeline", Mandatory = true)] public AccessRuleCollection AccessRules { get; set; } [Parameter] public SwitchParameter PassThru { get; set; } protected override void ProcessItem(Item item) { if (!this.CanAdmin(item)) { return; } if (ShouldProcess(item.GetProviderPath(), "Change access rights")) { item.Security.SetAccessRules(AccessRules); } if (PassThru) { WriteItem(item); } } } }
31.891892
78
0.642373
[ "MIT" ]
Krusen/Console
Cognifide.PowerShell/Commandlets/Security/Items/SetItemAclCommand.cs
1,182
C#
// This file is part of the DisCatSharp project, based off DSharpPlus. // // Copyright (c) 2021-2022 AITSYS // // 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 Newtonsoft.Json; namespace DisCatSharp.Entities { /// <summary> /// Represents information about a Discord voice server region. /// </summary> public class DiscordVoiceRegion { /// <summary> /// Gets the unique ID for the region. /// </summary> [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] public string Id { get; internal set; } /// <summary> /// Gets the name of the region. /// </summary> [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; internal set; } /// <summary> /// Gets an example server hostname for this region. /// </summary> [JsonProperty("sample_hostname", NullValueHandling = NullValueHandling.Ignore)] public string SampleHostname { get; internal set; } /// <summary> /// Gets an example server port for this region. /// </summary> [JsonProperty("sample_port", NullValueHandling = NullValueHandling.Ignore)] public int SamplePort { get; internal set; } /// <summary> /// Gets whether this region is the most optimal for the current user. /// </summary> [JsonProperty("optimal", NullValueHandling = NullValueHandling.Ignore)] public bool IsOptimal { get; internal set; } /// <summary> /// Gets whether this voice region is deprecated. /// </summary> [JsonProperty("deprecated", NullValueHandling = NullValueHandling.Ignore)] public bool IsDeprecated { get; internal set; } /// <summary> /// Gets whether this is a custom voice region. /// </summary> [JsonProperty("custom", NullValueHandling = NullValueHandling.Ignore)] public bool IsCustom { get; internal set; } /// <summary> /// Gets whether two <see cref="DiscordVoiceRegion"/>s are equal. /// </summary> /// <param name="region">The region to compare with.</param> public bool Equals(DiscordVoiceRegion region) => this == region; /// <summary> /// Whether two regions are equal. /// </summary> /// <param name="obj">A voice region.</param> public override bool Equals(object obj) => this.Equals(obj as DiscordVoiceRegion); /// <summary> /// Gets the hash code. /// </summary> public override int GetHashCode() => this.Id.GetHashCode(); /// <summary> /// Gets whether the two <see cref="DiscordVoiceRegion"/> objects are equal. /// </summary> /// <param name="left">First voice region to compare.</param> /// <param name="right">Second voice region to compare.</param> /// <returns>Whether the two voice regions are equal.</returns> public static bool operator ==(DiscordVoiceRegion left, DiscordVoiceRegion right) { var o1 = left as object; var o2 = right as object; return (o1 != null || o2 == null) && (o1 == null || o2 != null) && ((o1 == null && o2 == null) || left.Id == right.Id); } /// <summary> /// Gets whether the two <see cref="DiscordVoiceRegion"/> objects are not equal. /// </summary> /// <param name="left">First voice region to compare.</param> /// <param name="right">Second voice region to compare.</param> /// <returns>Whether the two voice regions are not equal.</returns> public static bool operator !=(DiscordVoiceRegion left, DiscordVoiceRegion right) => !(left == right); /// <summary> /// Initializes a new instance of the <see cref="DiscordVoiceRegion"/> class. /// </summary> internal DiscordVoiceRegion() { } } }
37.262295
122
0.695557
[ "Apache-2.0" ]
Aiko-IT-Systems/DSharpPlusNextGen
DisCatSharp/Entities/Voice/DiscordVoiceRegion.cs
4,546
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace FPLForecaster { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Page}/{action=Home}/{id?}"); }); //Populates general data such as fixtures, players, and teams DataService.Controller.GetGeneralData(); } } }
32.360656
144
0.590679
[ "MIT" ]
yannihilator/FPLForecaster
Startup.cs
1,974
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { #pragma warning disable CS8618 [JsiiByValue(fqn: "aws.Wafv2WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument")] public class Wafv2WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument : aws.IWafv2WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument { [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}", isOverride: true)] public string Name { get; set; } } }
39.4
297
0.790609
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/Wafv2WebAclRuleStatementNotStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument.cs
788
C#
// // Fingers Gestures // (c) 2015 Digital Ruby, LLC // http://www.digitalruby.com // Source code may be used for personal or commercial projects. // Source code may NOT be redistributed or sold. // using System; namespace DigitalRubyShared { /// <summary> /// Allows rotating an object with just one finger. Typically you would put this on a button /// with a rotation symbol and then when the user taps and drags off that button, something /// would then rotate. /// </summary> public class OneTouchRotateGestureRecognizer : RotateGestureRecognizer { /// <summary> /// Current angle - if AnglePointOverrideX and AnglePointOverrideY are set, these are used instead of the start touch location to determine the angle. /// </summary> /// <returns>Current angle</returns> protected override float CurrentAngle() { if (AnglePointOverrideX != float.MinValue && AnglePointOverrideY != float.MinValue && CurrentTrackedTouches.Count != 0) { GestureTouch t = CurrentTrackedTouches[0]; return (float)Math.Atan2(t.Y - AnglePointOverrideY, t.X - AnglePointOverrideX); } return (float)Math.Atan2(DistanceY, DistanceX); } /// <summary> /// Constructor - sets ThresholdUnits to 0.15f and AngleThreshold to 0.0f /// </summary> public OneTouchRotateGestureRecognizer() { MaximumNumberOfTouchesToTrack = 1; ThresholdUnits = 0.15f; AngleThreshold = 0.0f; } /// <summary> /// Normally angle is calculated against the start touch coordinate. This value allows using a different anchor for rotation purposes. /// </summary> public float AnglePointOverrideX = float.MinValue; /// <summary> /// Normally angle is calculated against the start touch coordinate. This value allows using a different anchor for rotation purposes. /// </summary> public float AnglePointOverrideY = float.MinValue; } }
38.428571
159
0.625929
[ "MIT" ]
FZarattini/Melting
Assets/FingersLite/Script/Gestures/OneTouchRotateGestureRecognizer.cs
2,154
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace BusterWood.Channels { /// <summary>A Select allows for receiving on one on many channels, in priority order</summary> public class Select { static readonly Task<bool> True = Task.FromResult(true); static readonly Task<bool> False = Task.FromResult(false); List<ICase> cases = new List<ICase>(); /// <summary>Adds a action to perform when a channel can be read</summary> /// <param name="ch">The channel to try to read from (which must also implement <see cref="ISelectable"/>)</param> /// <param name="action">the synchronous action to perform with the value that was read</param> public Select OnReceive<T>(IReceiver<T> ch, Action<T> action) { if (ch == null) throw new ArgumentNullException(nameof(ch)); if (action == null) throw new ArgumentNullException(nameof(action)); cases.Add(new ReceiveCase<T>(ch, action)); return this; } /// <summary>Adds a asynchronous action to perform when a channel can be read</summary> /// <param name="ch">The channel to try to read from (which must also implement <see cref="ISelectable"/>)</param> /// <param name="action">the asynchronous action to perform with the value that was read</param> public Select OnReceiveAsync<T>(IReceiver<T> ch, Func<T, Task> action) { if (ch == null) throw new ArgumentNullException(nameof(ch)); if (action == null) throw new ArgumentNullException(nameof(action)); cases.Add(new ReceiveAsyncCase<T>(ch, action)); return this; } /// <summary>Tries to reads from one (and only one) of the added channels. Does no action if the <paramref name="timeout"/> has been reached</summary> /// <returns>True if an action was performed, False if no action was performed and the timeout was reached</returns> public async Task<bool> ExecuteAsync(TimeSpan timeout) { if (timeout == System.Threading.Timeout.InfiniteTimeSpan || timeout == TimeSpan.MaxValue) { await ExecuteAsync(); return true; } var timedOut = false; var receiveTimeout = new ReceiveCase<DateTime>(Timeout.After(timeout), _ => timedOut = true); var idx = cases.Count; cases.Add(receiveTimeout); await ExecuteAsync(); cases.RemoveAt(idx); return !timedOut; } /// <summary>Reads from one (and only one) of the added channels and performs the associated action</summary> /// <returns>A task that completes when one channel has been read and the associated action performed</returns> public async Task ExecuteAsync() { if (cases.Count == 0) throw new InvalidOperationException("No cases have been added"); for (;;) { // try to execute any case that is ready foreach (var c in cases) { if (await c.TryExecuteAsync()) return; } // we must wait, no channels are ready var waiter = new Waiter(); foreach (var c in cases) c.AddWaiter(waiter); await waiter.Task; foreach (var c in cases) c.RemoveWaiter(waiter); } } interface ICase { Task<bool> TryExecuteAsync(); void AddWaiter(Waiter tcs); void RemoveWaiter(Waiter tcs); } class ReceiveAsyncCase<T> : ICase { readonly IReceiver<T> ch; readonly Func<T, Task> asyncAction; public ReceiveAsyncCase(IReceiver<T> ch, Func<T, Task> asyncAction) { this.ch = ch; this.asyncAction = asyncAction; if (!(ch is ISelectable)) throw new ArgumentException("receiver must implement " + nameof(ISelectable), nameof(ch)); } public Task<bool> TryExecuteAsync() { T val; return ch.TryReceive(out val) ? AsyncExcuteAction(val) : False; } async Task<bool> AsyncExcuteAction(T val) { await asyncAction(val); return true; } public void AddWaiter(Waiter tcs) { ((ISelectable)ch).AddWaiter(tcs); } public void RemoveWaiter(Waiter tcs) { ((ISelectable)ch).RemoveWaiter(tcs); } } class ReceiveCase<T> : ICase { readonly IReceiver<T> ch; readonly Action<T> action; public ReceiveCase(IReceiver<T> ch, Action<T> action) { this.ch = ch; this.action = action; if (!(ch is ISelectable)) throw new ArgumentException("receiver must implement " + nameof(ISelectable), nameof(ch)); } public Task<bool> TryExecuteAsync() { T val; if (ch.TryReceive(out val)) { action(val); return True; } return False; } public void AddWaiter(Waiter tcs) { ((ISelectable)ch).AddWaiter(tcs); } public void RemoveWaiter(Waiter tcs) { ((ISelectable)ch).RemoveWaiter(tcs); } } } public static class Extensions { public static async Task<bool> ExecuteAsync(this Select select, TimeSpan? timeout) { if (timeout != null) return await select.ExecuteAsync(timeout.Value); await select.ExecuteAsync(); return false; } } }
35.74269
159
0.538449
[ "Apache-2.0" ]
SammyEnigma/Goodies
Goodies/Channels/Select.cs
6,114
C#
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Threading; using Amazon.Glacier.Model; using Amazon.Glacier.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.Glacier { /// <summary> /// Implementation for accessing AmazonGlacier. /// /// <para>Amazon Glacier is a storage solution for "cold data."</para> <para>Amazon Glacier is an extremely low-cost storage service that /// provides secure, durable, and easy-to-use storage for data backup and archival. With Amazon Glacier, customers can store their data cost /// effectively for months, years, or decades. Amazon Glacier also enables customers to offload the administrative burdens of operating and /// scaling storage to AWS, so they don't have to worry about capacity planning, hardware provisioning, data replication, hardware failure and /// recovery, or time-consuming hardware migrations.</para> <para>Amazon Glacier is a great storage choice when low storage cost is paramount, /// your data is rarely retrieved, and retrieval latency of several hours is acceptable. If your application requires fast or frequent access to /// your data, consider using Amazon S3. For more information, go to Amazon Simple Storage Service (Amazon S3).</para> <para>You can store any /// kind of data in any format. There is no maximum limit on the total amount of data you can store in Amazon Glacier. </para> <para>If you are /// a first-time user of Amazon Glacier, we recommend that you begin by reading the following sections in the <i>Amazon Glacier Developer /// Guide</i> :</para> /// <ul> /// <li> <para> What is Amazon Glacier - This section of the Developer Guide describes the underlying data model, the operations it supports, /// and the AWS SDKs that you can use to interact with the service.</para> </li> /// <li> <para> Getting Started with Amazon Glacier - The Getting Started section walks you through the process of creating a vault, uploading /// archives, creating jobs to download archives, retrieving the job output, and deleting archives.</para> </li> /// /// </ul> /// </summary> public partial class AmazonGlacierClient : AmazonServiceClient, IAmazonGlacier { /// <summary> /// Specialize the initialize of the client. /// </summary> protected override void Initialize() { this.Config.SetUseNagleIfAvailable(true); this.Config.ResignRetries = true; base.Initialize(); } } }
52.177419
148
0.716229
[ "Apache-2.0" ]
SaschaHaertel/AmazonAWS
sdk/src/Services/Glacier/Custom/AmazonGlacierClient.Extensions.cs
3,237
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace IO.Swagger.Model { /// <summary> /// /// </summary> [DataContract] public class ManagementPermissionReference { /// <summary> /// Gets or Sets Enabled /// </summary> [DataMember(Name="enabled", EmitDefaultValue=false)] [JsonProperty(PropertyName = "enabled")] public bool? Enabled { get; set; } /// <summary> /// Gets or Sets Resource /// </summary> [DataMember(Name="resource", EmitDefaultValue=false)] [JsonProperty(PropertyName = "resource")] public string Resource { get; set; } /// <summary> /// Gets or Sets ScopePermissions /// </summary> [DataMember(Name="scopePermissions", EmitDefaultValue=false)] [JsonProperty(PropertyName = "scopePermissions")] public Dictionary<string, Object> ScopePermissions { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ManagementPermissionReference {\n"); sb.Append(" Enabled: ").Append(Enabled).Append("\n"); sb.Append(" Resource: ").Append(Resource).Append("\n"); sb.Append(" ScopePermissions: ").Append(ScopePermissions).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
29.311475
78
0.650447
[ "MIT" ]
chord-io/chord.io-service
Models/Keycloak/ManagementPermissionReference.cs
1,788
C#
namespace GenericsAnalyzer.CodeFixes.Test.PermittedTypeArguments { public abstract class InstanceTypeMemberRemoverCodeFixTests : PermittedTypeArgumentAnalyzerCodeFixTests<InstanceTypeMemberRemover> { } }
31
134
0.83871
[ "MIT" ]
AlFasGD/GenericsAnalyzer
GenericsAnalyzer.CodeFixes.Test/PermittedTypeArguments/InstanceTypeMemberRemoverCodeFixTests.cs
219
C#
// // DO NOT MODIFY! THIS IS AUTOGENERATED FILE! // namespace Xilium.CefGlue.Interop { using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; [StructLayout(LayoutKind.Sequential, Pack = libcef.ALIGN)] [SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")] internal unsafe struct cef_x509certificate_t { internal cef_base_ref_counted_t _base; internal IntPtr _get_subject; internal IntPtr _get_issuer; internal IntPtr _get_serial_number; internal IntPtr _get_valid_start; internal IntPtr _get_valid_expiry; internal IntPtr _get_derencoded; internal IntPtr _get_pemencoded; internal IntPtr _get_issuer_chain_size; internal IntPtr _get_derencoded_issuer_chain; internal IntPtr _get_pemencoded_issuer_chain; [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate void add_ref_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate int release_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate int has_one_ref_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate int has_at_least_one_ref_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate cef_x509cert_principal_t* get_subject_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate cef_x509cert_principal_t* get_issuer_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate cef_binary_value_t* get_serial_number_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate cef_time_t get_valid_start_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate cef_time_t get_valid_expiry_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate cef_binary_value_t* get_derencoded_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate cef_binary_value_t* get_pemencoded_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate UIntPtr get_issuer_chain_size_delegate(cef_x509certificate_t* self); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate void get_derencoded_issuer_chain_delegate(cef_x509certificate_t* self, UIntPtr* chainCount, cef_binary_value_t** chain); [UnmanagedFunctionPointer(libcef.CEF_CALLBACK)] #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif private delegate void get_pemencoded_issuer_chain_delegate(cef_x509certificate_t* self, UIntPtr* chainCount, cef_binary_value_t** chain); // AddRef private static IntPtr _p0; private static add_ref_delegate _d0; public static void add_ref(cef_x509certificate_t* self) { add_ref_delegate d; var p = self->_base._add_ref; if (p == _p0) { d = _d0; } else { d = (add_ref_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(add_ref_delegate)); if (_p0 == IntPtr.Zero) { _d0 = d; _p0 = p; } } d(self); } // Release private static IntPtr _p1; private static release_delegate _d1; public static int release(cef_x509certificate_t* self) { release_delegate d; var p = self->_base._release; if (p == _p1) { d = _d1; } else { d = (release_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(release_delegate)); if (_p1 == IntPtr.Zero) { _d1 = d; _p1 = p; } } return d(self); } // HasOneRef private static IntPtr _p2; private static has_one_ref_delegate _d2; public static int has_one_ref(cef_x509certificate_t* self) { has_one_ref_delegate d; var p = self->_base._has_one_ref; if (p == _p2) { d = _d2; } else { d = (has_one_ref_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(has_one_ref_delegate)); if (_p2 == IntPtr.Zero) { _d2 = d; _p2 = p; } } return d(self); } // HasAtLeastOneRef private static IntPtr _p3; private static has_at_least_one_ref_delegate _d3; public static int has_at_least_one_ref(cef_x509certificate_t* self) { has_at_least_one_ref_delegate d; var p = self->_base._has_at_least_one_ref; if (p == _p3) { d = _d3; } else { d = (has_at_least_one_ref_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(has_at_least_one_ref_delegate)); if (_p3 == IntPtr.Zero) { _d3 = d; _p3 = p; } } return d(self); } // GetSubject private static IntPtr _p4; private static get_subject_delegate _d4; public static cef_x509cert_principal_t* get_subject(cef_x509certificate_t* self) { get_subject_delegate d; var p = self->_get_subject; if (p == _p4) { d = _d4; } else { d = (get_subject_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_subject_delegate)); if (_p4 == IntPtr.Zero) { _d4 = d; _p4 = p; } } return d(self); } // GetIssuer private static IntPtr _p5; private static get_issuer_delegate _d5; public static cef_x509cert_principal_t* get_issuer(cef_x509certificate_t* self) { get_issuer_delegate d; var p = self->_get_issuer; if (p == _p5) { d = _d5; } else { d = (get_issuer_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_issuer_delegate)); if (_p5 == IntPtr.Zero) { _d5 = d; _p5 = p; } } return d(self); } // GetSerialNumber private static IntPtr _p6; private static get_serial_number_delegate _d6; public static cef_binary_value_t* get_serial_number(cef_x509certificate_t* self) { get_serial_number_delegate d; var p = self->_get_serial_number; if (p == _p6) { d = _d6; } else { d = (get_serial_number_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_serial_number_delegate)); if (_p6 == IntPtr.Zero) { _d6 = d; _p6 = p; } } return d(self); } // GetValidStart private static IntPtr _p7; private static get_valid_start_delegate _d7; public static cef_time_t get_valid_start(cef_x509certificate_t* self) { get_valid_start_delegate d; var p = self->_get_valid_start; if (p == _p7) { d = _d7; } else { d = (get_valid_start_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_valid_start_delegate)); if (_p7 == IntPtr.Zero) { _d7 = d; _p7 = p; } } return d(self); } // GetValidExpiry private static IntPtr _p8; private static get_valid_expiry_delegate _d8; public static cef_time_t get_valid_expiry(cef_x509certificate_t* self) { get_valid_expiry_delegate d; var p = self->_get_valid_expiry; if (p == _p8) { d = _d8; } else { d = (get_valid_expiry_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_valid_expiry_delegate)); if (_p8 == IntPtr.Zero) { _d8 = d; _p8 = p; } } return d(self); } // GetDEREncoded private static IntPtr _p9; private static get_derencoded_delegate _d9; public static cef_binary_value_t* get_derencoded(cef_x509certificate_t* self) { get_derencoded_delegate d; var p = self->_get_derencoded; if (p == _p9) { d = _d9; } else { d = (get_derencoded_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_derencoded_delegate)); if (_p9 == IntPtr.Zero) { _d9 = d; _p9 = p; } } return d(self); } // GetPEMEncoded private static IntPtr _pa; private static get_pemencoded_delegate _da; public static cef_binary_value_t* get_pemencoded(cef_x509certificate_t* self) { get_pemencoded_delegate d; var p = self->_get_pemencoded; if (p == _pa) { d = _da; } else { d = (get_pemencoded_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_pemencoded_delegate)); if (_pa == IntPtr.Zero) { _da = d; _pa = p; } } return d(self); } // GetIssuerChainSize private static IntPtr _pb; private static get_issuer_chain_size_delegate _db; public static UIntPtr get_issuer_chain_size(cef_x509certificate_t* self) { get_issuer_chain_size_delegate d; var p = self->_get_issuer_chain_size; if (p == _pb) { d = _db; } else { d = (get_issuer_chain_size_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_issuer_chain_size_delegate)); if (_pb == IntPtr.Zero) { _db = d; _pb = p; } } return d(self); } // GetDEREncodedIssuerChain private static IntPtr _pc; private static get_derencoded_issuer_chain_delegate _dc; public static void get_derencoded_issuer_chain(cef_x509certificate_t* self, UIntPtr* chainCount, cef_binary_value_t** chain) { get_derencoded_issuer_chain_delegate d; var p = self->_get_derencoded_issuer_chain; if (p == _pc) { d = _dc; } else { d = (get_derencoded_issuer_chain_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_derencoded_issuer_chain_delegate)); if (_pc == IntPtr.Zero) { _dc = d; _pc = p; } } d(self, chainCount, chain); } // GetPEMEncodedIssuerChain private static IntPtr _pd; private static get_pemencoded_issuer_chain_delegate _dd; public static void get_pemencoded_issuer_chain(cef_x509certificate_t* self, UIntPtr* chainCount, cef_binary_value_t** chain) { get_pemencoded_issuer_chain_delegate d; var p = self->_get_pemencoded_issuer_chain; if (p == _pd) { d = _dd; } else { d = (get_pemencoded_issuer_chain_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_pemencoded_issuer_chain_delegate)); if (_pd == IntPtr.Zero) { _dd = d; _pd = p; } } d(self, chainCount, chain); } } }
37.079772
145
0.593008
[ "MIT" ]
OutSystems/CefGlue
CefGlue/Interop/Classes.g/cef_x509certificate_t.g.cs
13,015
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FileExplorerApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FileExplorerApp")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.464286
98
0.710261
[ "MIT" ]
Embarcadero/ComparisonResearch
fileexplorer/wpf/FileExplorerApp/Properties/AssemblyInfo.cs
2,381
C#
using System; using System.Diagnostics; using System.Globalization; using Android.App; using Android.Content; using Android.Content.PM; using Android.Content.Res; using Android.OS; using Android.Views; using Android.Widget; using Java.Interop; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Compatibility; using Microsoft.Maui.Controls.Compatibility.ControlGallery; using Microsoft.Maui.Controls.Compatibility.ControlGallery.Android; using Microsoft.Maui.Controls.Compatibility.ControlGallery.Issues; using Microsoft.Maui.Controls.Compatibility.Platform.Android; using Microsoft.Maui.Controls.Compatibility.Platform.Android.AppLinks; using Microsoft.Maui.Graphics; using Microsoft.Maui.Platform; using AColor = Android.Graphics.Color; [assembly: Dependency(typeof(CacheService))] [assembly: Dependency(typeof(TestCloudService))] [assembly: ExportRenderer(typeof(DisposePage), typeof(DisposePageRenderer))] [assembly: ExportRenderer(typeof(DisposeLabel), typeof(DisposeLabelRenderer))] [assembly: ExportEffect(typeof(BorderEffect), "BorderEffect")] namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.Android { public partial class Activity1 { App _app; void AddNativeControls(NestedNativeControlGalleryPage page) { if (page.NativeControlsAdded) { return; } StackLayout sl = page.Layout; // Create and add a native TextView var textView = new TextView(this) { Text = "I am a native TextView", TextSize = 14 }; sl?.Children.Add(textView); // Create and add a native Button var button = new global::Android.Widget.Button(this) { Text = "Click to change TextView font size" }; float originalSize = textView.TextSize; button.Click += (sender, args) => { textView.TextSize = textView.TextSize == originalSize ? 24 : 14; }; sl?.Children.Add(button.ToView()); // Create a control which we know doesn't behave correctly with regard to measurement var difficultControl0 = new BrokenNativeControl(this) { Text = "This native control doesn't play nice with sizing, which is why it's all squished to one side." }; var difficultControl1 = new BrokenNativeControl(this) { Text = "Same control, but with a custom GetDesiredSize delegate to accomodate it's sizing problems." }; // Add a misbehaving control sl?.Children.Add(difficultControl0); // Add a misbehaving control with a custom delegate for GetDesiredSize sl?.Children.Add(difficultControl1, SizeBrokenControl); page.NativeControlsAdded = true; } static SizeRequest? SizeBrokenControl(NativeViewWrapperRenderer renderer, int widthConstraint, int heightConstraint) { global::Android.Views.View nativeView = renderer.Control; if ((widthConstraint == 0 && heightConstraint == 0) || nativeView == null) { return null; } int width = global::Android.Views.View.MeasureSpec.GetSize(widthConstraint); int widthSpec = global::Android.Views.View.MeasureSpec.MakeMeasureSpec(width * 2, global::Android.Views.View.MeasureSpec.GetMode(widthConstraint)); nativeView.Measure(widthSpec, heightConstraint); var size = new Size(nativeView.MeasuredWidth, nativeView.MeasuredHeight); return new SizeRequest(size); } void AddNativeBindings(NativeBindingGalleryPage page) { if (page.NativeControlsAdded) return; StackLayout sl = page.Layout; var textView = new TextView(this) { TextSize = 14, Text = "This will be text" }; var viewGroup = new LinearLayout(this); viewGroup.AddView(textView); var buttonColor = new global::Android.Widget.Button(this) { Text = "Change label Color" }; buttonColor.Click += (sender, e) => textView.SetTextColor(Colors.Blue.ToAndroid()); var colorPicker = new ColorPickerView(this, 200, 200); textView.SetBinding(nameof(textView.Text), new Binding("NativeLabel")); //this doesn't work because there's not TextColor property //textView.SetBinding("TextColor", new Binding("NativeLabelColor", converter: new ColorConverter())); colorPicker.SetBinding(nameof(colorPicker.SelectedColor), new Binding("NativeLabelColor", BindingMode.TwoWay, new ColorConverter()), "ColorPicked"); sl?.Children.Add(viewGroup); sl?.Children.Add(buttonColor.ToView()); sl?.Children.Add(colorPicker); page.NativeControlsAdded = true; } public class ColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is Color) return ((Color)value).ToAndroid(); return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is global::Android.Graphics.Color) return ((global::Android.Graphics.Color)value).ToColor(); return null; } } [Export("NavigateToTest")] public bool NavigateToTest(string test) { return _app.NavigateToTestPage(test); } [Export("Reset")] public void Reset() { _app.Reset(); } void SetUpForceRestartTest() { // Listen for messages from the app restart test MessagingCenter.Subscribe<RestartAppTest>(this, RestartAppTest.ForceRestart, (e) => { // We can force a restart by making a configuration change; in this case, we'll enter // Car Mode. (The easy way to do this is to change the orientation, but ControlGallery // handles orientation changes so they don't cause a restart.) var uiModeManager = UiModeManager.FromContext(this); if (uiModeManager.CurrentModeType == UiMode.TypeCar) { // If for some reason we're already in car mode, disable it uiModeManager.DisableCarMode(DisableCarModeFlags.None); } uiModeManager.EnableCarMode(EnableCarModeFlags.None); // And put things back to normal so we can keep running tests uiModeManager.DisableCarMode(DisableCarModeFlags.None); ((App)Microsoft.Maui.Controls.Application.Current).Reset(); }); } } }
32.298913
151
0.737843
[ "MIT" ]
APopatanasov/maui
src/Compatibility/ControlGallery/src/Android/Activity1.cs
5,945
C#
using System; using System.Collections.Generic; using System.Text; namespace ValveMultitool.Models.Formats.Vpc { public class VpcValue { public object Value; public VpcValueType Type; public override string ToString() => Value.ToString(); } }
18.8
62
0.684397
[ "MIT" ]
ChaosInitiative/ValveMultitool
ValveMultitool/Models/Formats/Vpc/VpcValue.cs
284
C#
/* * Strings.cs - Implementation of the "I18N.Common.Strings" class. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ namespace I18N.Common { using System; using System.Reflection; using System.Resources; // This class provides string resource support to the rest // of the I18N library assemblies. public sealed class Strings { // Cached copy of the resources for this assembly. // private static ResourceManager resources = null; // Helper for obtaining string resources for this assembly. public static String GetString(String tag) { switch (tag) { case "ArgRange_Array": return "Argument index is out of array range."; case "Arg_InsufficientSpace": return "Insufficient space in the argument array."; case "ArgRange_NonNegative": return "Non-negative value is expected."; case "NotSupp_MissingCodeTable": return "This encoding is not supported. Code table is missing."; case "ArgRange_StringIndex": return "String index is out of range."; case "ArgRange_StringRange": return "String length is out of range."; default: throw new ArgumentException (String.Format ("Unexpected error tag name: {0}", tag)); } } }; // class Strings }; // namespace I18N.Common
35.96875
88
0.747176
[ "Apache-2.0" ]
121468615/mono
mcs/class/I18N/Common/Strings.cs
2,302
C#
using System.Collections.Generic; using System.Diagnostics.Contracts; namespace ReClassNET.Util { public class GrowingList<T> { private readonly List<T> list; public T DefaultValue { get; set; } public GrowingList() { Contract.Ensures(list != null); list = new List<T>(); } public GrowingList(T defaultValue) : this() { DefaultValue = defaultValue; } private void GrowToSize(int size) { for (var i = list.Count; i <= size; ++i) { list.Add(DefaultValue); } } private void CheckIndex(int index) { Contract.Requires(index >= 0); if (index >= list.Count) { GrowToSize(index); } } public T this[int index] { get { Contract.Requires(index >= 0); CheckIndex(index); return list[index]; } set { Contract.Requires(index >= 0); CheckIndex(index); list[index] = value; } } } }
14.0625
43
0.604444
[ "MIT" ]
AlisaDarkCoder/ReClass.NET
ReClass.NET/Util/GrowingList.cs
902
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using Microsoft.Maui.Controls.StyleSheets; namespace Microsoft.Maui.Controls { [Flags] public enum InitializationFlags : long { DisableCss = 1 << 0, SkipRenderers = 1 << 1, } } namespace Microsoft.Maui.Controls.Internals { [EditorBrowsable(EditorBrowsableState.Never)] public class Registrar<TRegistrable> where TRegistrable : class { readonly Dictionary<Type, Dictionary<Type, (Type target, short priority)>> _handlers = new Dictionary<Type, Dictionary<Type, (Type target, short priority)>>(); static Type _defaultVisualType = typeof(VisualMarker.DefaultVisual); static Type _materialVisualType = typeof(VisualMarker.MaterialVisual); static Type[] _defaultVisualRenderers = new[] { _defaultVisualType }; public void Register(Type tview, Type trender, Type[] supportedVisuals, short priority) { supportedVisuals = supportedVisuals ?? _defaultVisualRenderers; //avoid caching null renderers if (trender == null) return; if (!_handlers.TryGetValue(tview, out Dictionary<Type, (Type target, short priority)> visualRenderers)) { visualRenderers = new Dictionary<Type, (Type target, short priority)>(); _handlers[tview] = visualRenderers; } for (int i = 0; i < supportedVisuals.Length; i++) { if (visualRenderers.TryGetValue(supportedVisuals[i], out (Type target, short priority) existingTargetValue)) { if (existingTargetValue.priority <= priority) visualRenderers[supportedVisuals[i]] = (trender, priority); } else visualRenderers[supportedVisuals[i]] = (trender, priority); } // This registers a factory into the Handler version of the registrar. // This way if you are running a .NET MAUI app but want to use legacy renderers // the Handler.Registrar will use this factory to resolve a RendererToHandlerShim for the given type // This only comes into play if users "Init" a legacy set of renderers // The default for a .NET MAUI application will be to not do this but 3rd party vendors or // customers with large custom renderers will be able to use this to easily shim their renderer to a handler // to ease the migration process // TODO: This implementation isn't currently compatible with Visual but we have no concept of visual inside // .NET MAUI currently. // TODO: We need to implemnt this with the new AppHostBuilder //Microsoft.Maui.Registrar.Handlers.Register(tview, // (viewType) => // { // return Registrar.RendererToHandlerShim?.Invoke(null); // }); } public void Register(Type tview, Type trender, Type[] supportedVisual) => Register(tview, trender, supportedVisual, 0); public void Register(Type tview, Type trender) => Register(tview, trender, _defaultVisualRenderers); internal TRegistrable GetHandler(Type type) => GetHandler(type, _defaultVisualType); internal TRegistrable GetHandler(Type type, Type visualType) { Type handlerType = GetHandlerType(type, visualType ?? _defaultVisualType); if (handlerType == null) return null; object handler = DependencyResolver.ResolveOrCreate(handlerType); return (TRegistrable)handler; } internal TRegistrable GetHandler(Type type, object source, IVisual visual, params object[] args) { TRegistrable returnValue = default(TRegistrable); if (args.Length == 0) { returnValue = GetHandler(type, visual?.GetType() ?? _defaultVisualType); } else { Type handlerType = GetHandlerType(type, visual?.GetType() ?? _defaultVisualType); if (handlerType != null) returnValue = (TRegistrable)DependencyResolver.ResolveOrCreate(handlerType, source, visual?.GetType(), args); } return returnValue; } public TOut GetHandler<TOut>(Type type) where TOut : class, TRegistrable { return GetHandler(type) as TOut; } public TOut GetHandler<TOut>(Type type, params object[] args) where TOut : class, TRegistrable { return GetHandler(type, null, null, args) as TOut; } public TOut GetHandlerForObject<TOut>(object obj) where TOut : class, TRegistrable { if (obj == null) throw new ArgumentNullException(nameof(obj)); var reflectableType = obj as IReflectableType; var type = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : obj.GetType(); return GetHandler(type, (obj as IVisualController)?.EffectiveVisual?.GetType()) as TOut; } public TOut GetHandlerForObject<TOut>(object obj, params object[] args) where TOut : class, TRegistrable { if (obj == null) throw new ArgumentNullException(nameof(obj)); var reflectableType = obj as IReflectableType; var type = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : obj.GetType(); return GetHandler(type, obj, (obj as IVisualController)?.EffectiveVisual, args) as TOut; } public Type GetHandlerType(Type viewType) => GetHandlerType(viewType, _defaultVisualType); public Type GetHandlerType(Type viewType, Type visualType) { visualType = visualType ?? _defaultVisualType; // 1. Do we have this specific type registered already? if (_handlers.TryGetValue(viewType, out Dictionary<Type, (Type target, short priority)> visualRenderers)) if (visualRenderers.TryGetValue(visualType, out (Type target, short priority) specificTypeRenderer)) return specificTypeRenderer.target; else if (visualType == _materialVisualType) VisualMarker.MaterialCheck(); if (visualType != _defaultVisualType && visualRenderers != null) if (visualRenderers.TryGetValue(_defaultVisualType, out (Type target, short priority) specificTypeRenderer)) return specificTypeRenderer.target; // 2. Do we have a RenderWith for this type or its base types? Register them now. RegisterRenderWithTypes(viewType, visualType); // 3. Do we have a custom renderer for a base type or did we just register an appropriate renderer from RenderWith? if (LookupHandlerType(viewType, visualType, out (Type target, short priority) baseTypeRenderer)) return baseTypeRenderer.target; else return null; } public Type GetHandlerTypeForObject(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); var reflectableType = obj as IReflectableType; var type = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : obj.GetType(); return GetHandlerType(type); } bool LookupHandlerType(Type viewType, Type visualType, out (Type target, short priority) handlerType) { visualType = visualType ?? _defaultVisualType; while (viewType != null && viewType != typeof(Element)) { if (_handlers.TryGetValue(viewType, out Dictionary<Type, (Type target, short priority)> visualRenderers)) if (visualRenderers.TryGetValue(visualType, out handlerType)) return true; if (visualType != _defaultVisualType && visualRenderers != null) if (visualRenderers.TryGetValue(_defaultVisualType, out handlerType)) return true; viewType = viewType.GetTypeInfo().BaseType; } handlerType = (null, 0); return false; } void RegisterRenderWithTypes(Type viewType, Type visualType) { visualType = visualType ?? _defaultVisualType; // We're going to go through each type in this viewType's inheritance chain to look for classes // decorated with a RenderWithAttribute. We're going to register each specific type with its // renderer. while (viewType != null && viewType != typeof(Element)) { // Only go through this process if we have not registered something for this type; // we don't want RenderWith renderers to override ExportRenderers that are already registered. // Plus, there's no need to do this again if we already have a renderer registered. if (!_handlers.TryGetValue(viewType, out Dictionary<Type, (Type target, short priority)> visualRenderers) || !(visualRenderers.ContainsKey(visualType) || visualRenderers.ContainsKey(_defaultVisualType))) { // get RenderWith attribute for just this type, do not inherit attributes from base types var attribute = viewType.GetTypeInfo().GetCustomAttributes<RenderWithAttribute>(false).FirstOrDefault(); if (attribute == null) { // TODO this doesn't appear to do anything. Register just returns as a NOOP if the renderer is null Register(viewType, null, new[] { visualType }); // Cache this result so we don't have to do GetCustomAttributes again } else { Type specificTypeRenderer = attribute.Type; if (specificTypeRenderer.Name.StartsWith("_", StringComparison.Ordinal)) { // TODO: Remove attribute2 once renderer names have been unified across all platforms var attribute2 = specificTypeRenderer.GetTypeInfo().GetCustomAttribute<RenderWithAttribute>(); if (attribute2 != null) { for (int i = 0; i < attribute2.SupportedVisuals.Length; i++) { if (attribute2.SupportedVisuals[i] == _defaultVisualType) specificTypeRenderer = attribute2.Type; if (attribute2.SupportedVisuals[i] == visualType) { specificTypeRenderer = attribute2.Type; break; } } } if (specificTypeRenderer.Name.StartsWith("_", StringComparison.Ordinal)) { Register(viewType, null, new[] { visualType }); // Cache this result so we don't work through this chain again viewType = viewType.GetTypeInfo().BaseType; continue; } } Register(viewType, specificTypeRenderer, new[] { visualType }); // Register this so we don't have to look for the RenderWithAttibute again in the future } } viewType = viewType.GetTypeInfo().BaseType; } } } [EditorBrowsable(EditorBrowsableState.Never)] public static class Registrar { static Registrar() { Registered = new Registrar<IRegisterable>(); } internal static Dictionary<string, Type> Effects { get; } = new Dictionary<string, Type>(); internal static Dictionary<string, IList<StylePropertyAttribute>> StyleProperties => LazyStyleProperties.Value; static bool DisableCSS = false; static readonly Lazy<Dictionary<string, IList<StylePropertyAttribute>>> LazyStyleProperties = new Lazy<Dictionary<string, IList<StylePropertyAttribute>>>(LoadStyleSheets); public static IEnumerable<Assembly> ExtraAssemblies { get; set; } public static Registrar<IRegisterable> Registered { get; internal set; } //typeof(ExportRendererAttribute); //typeof(ExportCellAttribute); //typeof(ExportImageSourceHandlerAttribute); //TODO this is no longer used? public static void RegisterRenderers(HandlerAttribute[] attributes) { var length = attributes.Length; for (var i = 0; i < length; i++) { var attribute = attributes[i]; if (attribute.ShouldRegister()) Registered.Register(attribute.HandlerType, attribute.TargetType, attribute.SupportedVisuals, attribute.Priority); } } // This is used when you're running an app that only knows about handlers (.NET MAUI app) // If the user has called Forms.Init() this will register all found types // into the handlers registrar and then it will use this factory to create a shim internal static Func<object, IViewHandler> RendererToHandlerShim { get; private set; } public static void RegisterRendererToHandlerShim(Func<object, IViewHandler> handlerShim) { RendererToHandlerShim = handlerShim; } public static void RegisterStylesheets(InitializationFlags flags) { if ((flags & InitializationFlags.DisableCss) == InitializationFlags.DisableCss) DisableCSS = true; } static Dictionary<string, IList<StylePropertyAttribute>> LoadStyleSheets() { var properties = new Dictionary<string, IList<StylePropertyAttribute>>(); if (DisableCSS) return properties; var assembly = typeof(StylePropertyAttribute).GetTypeInfo().Assembly; var styleAttributes = assembly.GetCustomAttributesSafe(typeof(StylePropertyAttribute)); var stylePropertiesLength = styleAttributes?.Length ?? 0; for (var i = 0; i < stylePropertiesLength; i++) { var attribute = (StylePropertyAttribute)styleAttributes[i]; if (properties.TryGetValue(attribute.CssPropertyName, out var attrList)) attrList.Add(attribute); else properties[attribute.CssPropertyName] = new List<StylePropertyAttribute> { attribute }; } return properties; } public static void RegisterEffects(string resolutionName, ExportEffectAttribute[] effectAttributes) { var exportEffectsLength = effectAttributes.Length; for (var i = 0; i < exportEffectsLength; i++) { var effect = effectAttributes[i]; RegisterEffect(resolutionName, effect.Id, effect.Type); } } public static void RegisterEffect(string resolutionName, string id, Type effectType) { Effects[resolutionName + "." + id] = effectType; } public static void RegisterAll(Type[] attrTypes) { RegisterAll(attrTypes, default(InitializationFlags)); } public static void RegisterAll(Type[] attrTypes, InitializationFlags flags) { RegisterAll( Device.GetAssemblies(), Device.PlatformServices.GetType().GetTypeInfo().Assembly, attrTypes, flags, null); } public static void RegisterAll( Assembly[] assemblies, Assembly defaultRendererAssembly, Type[] attrTypes, InitializationFlags flags, Action<Type> viewRegistered) { Profile.FrameBegin(); if (ExtraAssemblies != null) assemblies = assemblies.Union(ExtraAssemblies).ToArray(); int indexOfExecuting = Array.IndexOf(assemblies, defaultRendererAssembly); if (indexOfExecuting > 0) { assemblies[indexOfExecuting] = assemblies[0]; assemblies[0] = defaultRendererAssembly; } // Don't use LINQ for performance reasons // Naive implementation can easily take over a second to run Profile.FramePartition("Reflect"); foreach (Assembly assembly in assemblies) { string frameName = Profile.IsEnabled ? assembly.GetName().Name : "Assembly"; Profile.FrameBegin(frameName); foreach (Type attrType in attrTypes) { object[] attributes = assembly.GetCustomAttributesSafe(attrType); if (attributes == null || attributes.Length == 0) continue; var length = attributes.Length; for (var i = 0; i < length; i++) { var a = attributes[i]; var attribute = a as HandlerAttribute; if (attribute == null && (a is ExportFontAttribute fa)) { CompatServiceProvider.FontRegistrar.Register(fa.FontFileName, fa.Alias, assembly); } else { if (attribute.ShouldRegister()) { Registered.Register(attribute.HandlerType, attribute.TargetType, attribute.SupportedVisuals, attribute.Priority); viewRegistered?.Invoke(attribute.HandlerType); } } } } object[] effectAttributes = assembly.GetCustomAttributesSafe(typeof(ExportEffectAttribute)); if (effectAttributes == null || effectAttributes.Length == 0) { Profile.FrameEnd(frameName); continue; } string resolutionName = assembly.FullName; var resolutionNameAttribute = (ResolutionGroupNameAttribute)assembly.GetCustomAttribute(typeof(ResolutionGroupNameAttribute)); if (resolutionNameAttribute != null) resolutionName = resolutionNameAttribute.ShortName; //NOTE: a simple cast to ExportEffectAttribute[] failed on UWP, hence the Array.Copy var typedEffectAttributes = new ExportEffectAttribute[effectAttributes.Length]; Array.Copy(effectAttributes, typedEffectAttributes, effectAttributes.Length); RegisterEffects(resolutionName, typedEffectAttributes); Profile.FrameEnd(frameName); } var type = Registered.GetHandlerType(typeof(EmbeddedFont)); if (type != null) CompatServiceProvider.SetFontLoader(type); RegisterStylesheets(flags); Profile.FramePartition("DependencyService.Initialize"); DependencyService.Initialize(assemblies); Profile.FrameEnd(); } } }
36.375566
173
0.722478
[ "MIT" ]
IgorPRZ/maui
src/Controls/src/Core/Registrar.cs
16,078
C#
//======= Copyright (c) Valve Corporation, All rights reserved. =============== using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using Valve.Newtonsoft.Json; using System.IO; namespace Valve.VR { [System.Serializable] public class SteamVR_Input_ActionFile { public List<SteamVR_Input_ActionFile_Action> actions = new List<SteamVR_Input_ActionFile_Action>(); public List<SteamVR_Input_ActionFile_ActionSet> action_sets = new List<SteamVR_Input_ActionFile_ActionSet>(); public List<SteamVR_Input_ActionFile_DefaultBinding> default_bindings = new List<SteamVR_Input_ActionFile_DefaultBinding>(); public List<Dictionary<string, string>> localization = new List<Dictionary<string, string>>(); [JsonIgnore] public List<SteamVR_Input_ActionFile_LocalizationItem> localizationHelperList = new List<SteamVR_Input_ActionFile_LocalizationItem>(); public void InitializeHelperLists() { foreach (var actionset in action_sets) { actionset.actionsInList = new List<SteamVR_Input_ActionFile_Action>(actions.Where(action => action.path.StartsWith(actionset.name) && SteamVR_Input_ActionFile_ActionTypes.listIn.Contains(action.type))); actionset.actionsOutList = new List<SteamVR_Input_ActionFile_Action>(actions.Where(action => action.path.StartsWith(actionset.name) && SteamVR_Input_ActionFile_ActionTypes.listOut.Contains(action.type))); } foreach (var item in localization) { localizationHelperList.Add(new SteamVR_Input_ActionFile_LocalizationItem(item)); } } public void SaveHelperLists() { actions.Clear(); foreach (var actionset in action_sets) { actions.AddRange(actionset.actionsInList); actions.AddRange(actionset.actionsOutList); } localization.Clear(); foreach (var item in localizationHelperList) { Dictionary<string, string> localizationItem = new Dictionary<string, string>(); localizationItem.Add(SteamVR_Input_ActionFile_LocalizationItem.languageTagKeyName, item.language); foreach (var itemItem in item.items) { localizationItem.Add(itemItem.Key, itemItem.Value); } localization.Add(localizationItem); } } public static string GetShortName(string name) { string fullName = name; int lastSlash = fullName.LastIndexOf('/'); if (lastSlash != -1) { if (lastSlash == fullName.Length - 1) { fullName = fullName.Remove(lastSlash); lastSlash = fullName.LastIndexOf('/'); if (lastSlash == -1) { return GetCodeFriendlyName(fullName); } } return GetCodeFriendlyName(fullName.Substring(lastSlash + 1)); } return GetCodeFriendlyName(fullName); } public static string GetCodeFriendlyName(string name) { name = name.Replace('/', '_').Replace(' ', '_'); if (char.IsLetter(name[0]) == false) name = "_" + name; for (int charIndex = 0; charIndex < name.Length; charIndex++) { if (char.IsLetterOrDigit(name[charIndex]) == false && name[charIndex] != '_') { name = name.Remove(charIndex, 1); name = name.Insert(charIndex, "_"); } } return name; } public string[] GetFilesToCopy(bool throwErrors = false) { List<string> files = new List<string>(); FileInfo actionFileInfo = new FileInfo(SteamVR_Input.actionsFilePath); string path = actionFileInfo.Directory.FullName; files.Add(SteamVR_Input.actionsFilePath); foreach (var binding in default_bindings) { string bindingPath = Path.Combine(path, binding.binding_url); if (File.Exists(bindingPath)) files.Add(bindingPath); else { if (throwErrors) { Debug.LogError("<b>[SteamVR]</b> Could not bind binding file specified by the actions.json manifest: " + bindingPath); } } } return files.ToArray(); } public void CopyFilesToPath(string toPath, bool overwrite) { string[] files = SteamVR_Input.actionFile.GetFilesToCopy(); foreach (string file in files) { FileInfo bindingInfo = new FileInfo(file); string newFilePath = Path.Combine(toPath, bindingInfo.Name); bool exists = false; if (File.Exists(newFilePath)) exists = true; if (exists) { if (overwrite) { FileInfo existingFile = new FileInfo(newFilePath); existingFile.IsReadOnly = false; existingFile.Delete(); File.Copy(file, newFilePath); RemoveAppKey(newFilePath); Debug.Log("<b>[SteamVR]</b> Copied (overwrote) SteamVR Input file at path: " + newFilePath); } else { Debug.Log("<b>[SteamVR]</b> Skipped writing existing file at path: " + newFilePath); } } else { File.Copy(file, newFilePath); RemoveAppKey(newFilePath); Debug.Log("<b>[SteamVR]</b> Copied SteamVR Input file to folder: " + newFilePath); } } } private const string findString_appKeyStart = "\"app_key\""; private const string findString_appKeyEnd = "\","; private static void RemoveAppKey(string newFilePath) { if (File.Exists(newFilePath)) { string jsonText = System.IO.File.ReadAllText(newFilePath); string findString = "\"app_key\""; int stringStart = jsonText.IndexOf(findString); if (stringStart == -1) return; //no app key int stringEnd = jsonText.IndexOf("\",", stringStart); if (stringEnd == -1) return; //no end? stringEnd += findString_appKeyEnd.Length; int stringLength = stringEnd - stringStart; string newJsonText = jsonText.Remove(stringStart, stringLength); FileInfo file = new FileInfo(newFilePath); file.IsReadOnly = false; File.WriteAllText(newFilePath, newJsonText); } } public void Save(string path) { FileInfo existingActionsFile = new FileInfo(path); if (existingActionsFile.Exists) { existingActionsFile.IsReadOnly = false; } //SanitizeActionFile(); //todo: shouldn't we be doing this? string json = JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); File.WriteAllText(path, json); } } public enum SteamVR_Input_ActionFile_DefaultBinding_ControllerTypes { vive, vive_pro, vive_controller, generic, holographic_controller, oculus_touch, gamepad, knuckles, } [System.Serializable] public class SteamVR_Input_ActionFile_DefaultBinding { public string controller_type; public string binding_url; public SteamVR_Input_ActionFile_DefaultBinding GetCopy() { SteamVR_Input_ActionFile_DefaultBinding newDefaultBinding = new SteamVR_Input_ActionFile_DefaultBinding(); newDefaultBinding.controller_type = this.controller_type; newDefaultBinding.binding_url = this.binding_url; return newDefaultBinding; } } [System.Serializable] public class SteamVR_Input_ActionFile_ActionSet { [JsonIgnore] private const string actionSetInstancePrefix = "instance_"; public string name; public string usage; [JsonIgnore] public string codeFriendlyName { get { return SteamVR_Input_ActionFile.GetCodeFriendlyName(name); } } [JsonIgnore] public string shortName { get { int lastIndex = name.LastIndexOf('/'); if (lastIndex == name.Length - 1) return string.Empty; return SteamVR_Input_ActionFile.GetShortName(name); } } public void SetNewShortName(string newShortName) { name = "/actions/" + newShortName; } public static string CreateNewName() { return "/actions/NewSet"; } public static SteamVR_Input_ActionFile_ActionSet CreateNew() { return new SteamVR_Input_ActionFile_ActionSet() { name = CreateNewName() }; } public SteamVR_Input_ActionFile_ActionSet GetCopy() { SteamVR_Input_ActionFile_ActionSet newSet = new SteamVR_Input_ActionFile_ActionSet(); newSet.name = this.name; newSet.usage = this.usage; return newSet; } public override bool Equals(object obj) { if (obj is SteamVR_Input_ActionFile_ActionSet) { SteamVR_Input_ActionFile_ActionSet set = (SteamVR_Input_ActionFile_ActionSet)obj; if (set == this) return true; if (set.name == this.name) return true; return false; } return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } [JsonIgnore] public List<SteamVR_Input_ActionFile_Action> actionsInList = new List<SteamVR_Input_ActionFile_Action>(); [JsonIgnore] public List<SteamVR_Input_ActionFile_Action> actionsOutList = new List<SteamVR_Input_ActionFile_Action>(); } public enum SteamVR_Input_ActionFile_Action_Requirements { optional, suggested, mandatory, } [System.Serializable] public class SteamVR_Input_ActionFile_Action { [JsonIgnore] private static string[] _requirementValues; [JsonIgnore] public static string[] requirementValues { get { if (_requirementValues == null) _requirementValues = System.Enum.GetNames(typeof(SteamVR_Input_ActionFile_Action_Requirements)); return _requirementValues; } } public string name; public string type; public string scope; public string skeleton; public string requirement; public SteamVR_Input_ActionFile_Action GetCopy() { SteamVR_Input_ActionFile_Action newAction = new SteamVR_Input_ActionFile_Action(); newAction.name = this.name; newAction.type = this.type; newAction.scope = this.scope; newAction.skeleton = this.skeleton; newAction.requirement = this.requirement; return newAction; } [JsonIgnore] public SteamVR_Input_ActionFile_Action_Requirements requirementEnum { get { for (int index = 0; index < requirementValues.Length; index++) { if (string.Equals(requirementValues[index], requirement, System.StringComparison.CurrentCultureIgnoreCase)) { return (SteamVR_Input_ActionFile_Action_Requirements)index; } } return SteamVR_Input_ActionFile_Action_Requirements.suggested; } set { requirement = value.ToString(); } } [JsonIgnore] public string codeFriendlyName { get { return SteamVR_Input_ActionFile.GetCodeFriendlyName(name); } } [JsonIgnore] public string shortName { get { return SteamVR_Input_ActionFile.GetShortName(name); } } [JsonIgnore] public string path { get { int lastIndex = name.LastIndexOf('/'); if (lastIndex != -1 && lastIndex + 1 < name.Length) { return name.Substring(0, lastIndex + 1); } return name; } } private const string nameTemplate = "/actions/{0}/{1}/{2}"; public static string CreateNewName(string actionSet, string direction) { return string.Format(nameTemplate, actionSet, direction, "NewAction"); } public static SteamVR_Input_ActionFile_Action CreateNew(string actionSet, SteamVR_ActionDirections direction, string actionType) { return new SteamVR_Input_ActionFile_Action() { name = CreateNewName(actionSet, direction.ToString().ToLower()), type = actionType }; } [JsonIgnore] public SteamVR_ActionDirections direction { get { if (type.ToLower() == SteamVR_Input_ActionFile_ActionTypes.vibration) return SteamVR_ActionDirections.Out; return SteamVR_ActionDirections.In; } } protected const string prefix = "/actions/"; [JsonIgnore] public string actionSet { get { int setEnd = name.IndexOf('/', prefix.Length); if (setEnd == -1) return string.Empty; return name.Substring(0, setEnd); } } public void SetNewActionSet(string newSetName) { name = string.Format(nameTemplate, newSetName, direction.ToString().ToLower(), shortName); } public override string ToString() { return shortName; } public override bool Equals(object obj) { if (obj is SteamVR_Input_ActionFile_Action) { SteamVR_Input_ActionFile_Action action = (SteamVR_Input_ActionFile_Action)obj; if (this == obj) return true; if (this.name == action.name && this.type == action.type && this.skeleton == action.skeleton && this.requirement == action.requirement) return true; return false; } return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } public class SteamVR_Input_ActionFile_LocalizationItem { public const string languageTagKeyName = "language_tag"; public string language; public Dictionary<string, string> items = new Dictionary<string, string>(); public SteamVR_Input_ActionFile_LocalizationItem(string newLanguage) { language = newLanguage; } public SteamVR_Input_ActionFile_LocalizationItem(Dictionary<string, string> dictionary) { if (dictionary == null) return; if (dictionary.ContainsKey(languageTagKeyName)) language = (string)dictionary[languageTagKeyName]; else Debug.Log("<b>[SteamVR]</b> Input: Error in actions file, no language_tag in localization array item."); foreach (KeyValuePair<string, string> item in dictionary) { if (item.Key != languageTagKeyName) items.Add(item.Key, (string)item.Value); } } } public class SteamVR_Input_ManifestFile { public string source; public List<SteamVR_Input_ManifestFile_Application> applications; } public class SteamVR_Input_ManifestFile_Application { public string app_key; public string launch_type; public string url; public string binary_path_windows; public string binary_path_linux; public string binary_path_osx; public string action_manifest_path; //public List<SteamVR_Input_ManifestFile_Application_Binding> bindings = new List<SteamVR_Input_ManifestFile_Application_Binding>(); public string image_path; public Dictionary<string, SteamVR_Input_ManifestFile_ApplicationString> strings = new Dictionary<string, SteamVR_Input_ManifestFile_ApplicationString>(); } public class SteamVR_Input_ManifestFile_ApplicationString { public string name; } public class SteamVR_Input_ManifestFile_Application_Binding { public string controller_type; public string binding_url; } public class SteamVR_Input_ManifestFile_Application_Binding_ControllerTypes { public static string oculus_touch = "oculus_touch"; public static string vive_controller = "vive_controller"; public static string knuckles = "knuckles"; public static string holographic_controller = "holographic_controller"; public static string vive = "vive"; public static string vive_pro = "vive_pro"; } static public class SteamVR_Input_ActionFile_ActionTypes { public static string boolean = "boolean"; public static string vector1 = "vector1"; public static string vector2 = "vector2"; public static string vector3 = "vector3"; public static string vibration = "vibration"; public static string pose = "pose"; public static string skeleton = "skeleton"; public static string skeletonLeftPath = "\\skeleton\\hand\\left"; public static string skeletonRightPath = "\\skeleton\\hand\\right"; public static string[] listAll = new string[] { boolean, vector1, vector2, vector3, vibration, pose, skeleton }; public static string[] listIn = new string[] { boolean, vector1, vector2, vector3, pose, skeleton }; public static string[] listOut = new string[] { vibration }; public static string[] listSkeletons = new string[] { skeletonLeftPath, skeletonRightPath }; } static public class SteamVR_Input_ActionFile_ActionSet_Usages { public static string leftright = "leftright"; public static string single = "single"; public static string hidden = "hidden"; public static string leftrightDescription = "per hand"; public static string singleDescription = "mirrored"; public static string hiddenDescription = "hidden"; public static string[] listValues = new string[] { leftright, single, hidden }; public static string[] listDescriptions = new string[] { leftrightDescription, singleDescription, hiddenDescription }; } }
34.249584
221
0.557958
[ "MIT" ]
HCUM/dronos
DronOS Unity/Assets/SteamVR/Input/SteamVR_Input_ActionFile.cs
20,586
C#
using System.ComponentModel.DataAnnotations; namespace GolfScoreUI.Data { public class RoundSettings { [Range(1, 10, ErrorMessage = "Must be at least 1 and at most 10.")] public int MaxStrokesPerHole { get; set; } = 8; [Range(1, 18, ErrorMessage = "Must be between 1 and 18.")] public int NumberOfHoles { get; set; } = 9; public List<Player> Players { get; } = new List<Player> { new Player { Name = "" }, new Player { Name = "" }, new Player { Name = "" }, new Player { Name = "" } }; } }
34.125
171
0.595238
[ "MIT" ]
BuildItBusk/VirtualScoreCard
GolfScoreUI/Data/RoundSettings.cs
548
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("SaturdayTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SaturdayTest")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("5c3fa240-480d-4078-8963-5daf5d6c2094")] // 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")]
37.555556
84
0.751479
[ "Unlicense" ]
MammosGeorgios/TestingGrounds
SaturdayTest/Properties/AssemblyInfo.cs
1,355
C#
using CupCake.Command; using CupCake.Command.Source; using CupCake.Permissions; namespace CupCake.DefaultCommands.Commands.Utility { public class PingCommand : UtilityCommandBase { [MinGroup(Group.Moderator)] [Label("ping")] [CorrectUsage("")] protected override void Run(IInvokeSource source, ParsedCommand message) { source.Reply("Pong."); } } }
24.764706
80
0.650831
[ "MIT" ]
KylerM/CupCake
CupCake.DefaultCommands/Commands/Utility/PingCommand.cs
423
C#
using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; namespace JwtAuth.Demo.Dto { public class EncryptRequest { [Required] [JsonPropertyName("text")] public string Text { get; set; } } }
20.461538
45
0.639098
[ "MIT" ]
cdcd72/gss.techtalk.demo
src/ProjectExperience/JwtAuth.Demo/JwtAuth.Demo/Dto/EncryptRequest.cs
266
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Xamarin.BookReader.UI.Listeners; using Xamarin.BookReader.Models; using Java.Lang; using Android.Text; using Xamarin.BookReader.Bases; using Com.Bumptech.Glide; using Com.Bumptech.Glide.Load.Resource.Bitmap; namespace Xamarin.BookReader.UI.Adapters { public class TopRankAdapter: BaseExpandableListAdapter { private Context mContext; private LayoutInflater inflater; private List<RankingList.MaleBean> groupArray; private List<List<RankingList.MaleBean>> childArray; private IOnRvItemClickListener<RankingList.MaleBean> listener; public TopRankAdapter(Context context, List<RankingList.MaleBean> groupArray, List<List<RankingList.MaleBean>> childArray) { this.childArray = childArray; this.groupArray = groupArray; mContext = context; inflater = LayoutInflater.From(context); } public override int GroupCount => groupArray.Count(); public override bool HasStableIds => false; public override Java.Lang.Object GetChild(int groupPosition, int childPosition) { return null;//TODO: childArray[groupPosition][childPosition]; } public override long GetChildId(int groupPosition, int childPosition) { return childPosition; } public override int GetChildrenCount(int groupPosition) { return childArray[groupPosition].Count(); } public override View GetChildView(int groupPosition, int childPosition, bool isLastChild, View convertView, ViewGroup parent) { View child = inflater.Inflate(Resource.Layout.item_top_rank_child, null); TextView tvName = child.FindViewById<TextView>(Resource.Id.tvRankChildName); tvName.Text = (childArray[groupPosition][childPosition].title); child.Click += (sender, e) => { listener.onItemClick(child, childPosition, childArray[groupPosition][childPosition]); }; return child; } public override Java.Lang.Object GetGroup(int groupPosition) { return null;//TODO: groupArray[groupPosition]; } public override long GetGroupId(int groupPosition) { return groupPosition; } public override View GetGroupView(int groupPosition, bool isExpanded, View convertView, ViewGroup parent) { View group = inflater.Inflate(Resource.Layout.item_top_rank_group, null); ImageView ivCover = group.FindViewById<ImageView>(Resource.Id.ivRankCover); if (!TextUtils.IsEmpty(groupArray[groupPosition].cover)) { Glide.With(mContext) .Load(Constant.IMG_BASE_URL + groupArray[groupPosition].cover) //.Placeholder(Resource.Drawable.avatar_default) .Transform(new GlideCircleTransform(mContext)) .Into(ivCover); group.Click += (sender, e) => { if (listener != null) { listener.onItemClick(group, groupPosition, groupArray[groupPosition]); } }; } else { ivCover.SetImageResource(Resource.Drawable.ic_rank_collapse); } TextView tvName = group.FindViewById<TextView>(Resource.Id.tvRankGroupName); tvName.Text = (groupArray[groupPosition].title); ImageView ivArrow = group.FindViewById<ImageView>(Resource.Id.ivRankArrow); if (childArray[groupPosition].Count() > 0) { if (isExpanded) { ivArrow.SetImageResource(Resource.Drawable.rank_arrow_up); } else { ivArrow.SetImageResource(Resource.Drawable.rank_arrow_down); } } else { ivArrow.Visibility = ViewStates.Gone; } return group; } public override bool IsChildSelectable(int groupPosition, int childPosition) { return true; } public void setItemClickListener(IOnRvItemClickListener<RankingList.MaleBean> listener) { this.listener = listener; } } }
35.629921
133
0.625414
[ "Apache-2.0" ]
FleetingWang/Xamarin.BookReader
Xamarin.BookReader/UI/Adapters/TopRankAdapter.cs
4,527
C#
 #region using statements using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; #endregion namespace DataJuggler.UltimateHelper { #region XmlPatternHelper /// <summary> /// This class is used to encode and decode xml text if the /// file contains ampersands (&) or greater than or less than signs. /// </summary> public class XmlPatternHelper { #region Private Variables // Source Values private const string GreaterThanSymbol = ">"; private const string LessThanSymbol = "<"; private const string AmpersandSymbol = "&"; private const string PercentSymbol = "%"; // EncodedValues private const string GreaterThanCode = "&gt;"; private const string LessThanCode = "&lt;"; private const string AmpersandCode = "&amp;"; private const string PercentCode = "&#37;"; #endregion #region Methods #region Decode(string sourceText) /// <summary> /// Decode the xml safe text back to normal text /// </summary> /// <param name="sourceText"></param> /// <returns></returns> public static string Decode(string sourceText) { // initial value string decodedText = ""; // If the sourceText string exists if (TextHelper.Exists(sourceText)) { // replace out each of the values that need to be replaced decodedText = sourceText.Replace(AmpersandCode, AmpersandSymbol); decodedText = decodedText.Replace(GreaterThanCode, GreaterThanSymbol); decodedText = decodedText.Replace(LessThanCode, LessThanSymbol); decodedText = decodedText.Replace(PercentCode, PercentSymbol); } // return value return decodedText; } #endregion #region Encode(string sourceText) /// <summary> /// Encode the text given into xml safe text /// </summary> /// <param name="sourceText"></param> /// <returns></returns> public static string Encode(string sourceText) { // initial value string encodedText = ""; // If the sourceText string exists if (TextHelper.Exists(sourceText)) { // replace out each of the values that need to be replaced encodedText = sourceText.Replace(GreaterThanSymbol, GreaterThanCode); encodedText = encodedText.Replace(LessThanSymbol, LessThanCode); encodedText = encodedText.Replace(AmpersandSymbol, AmpersandCode); encodedText = encodedText.Replace(PercentSymbol, PercentCode); } // return value return encodedText; } #endregion #region NeedsEncoding(string text) /// <summary> /// This method returns true if the text passed in contains /// & < > or %. /// </summary> public static bool NeedsEncoding(string text) { // initial value bool needsEncoding = false; // If the text string exists if (TextHelper.Exists(text)) { // set to true if the text contains of the symbols that need encoding. needsEncoding = text.Contains(AmpersandSymbol) || text.Contains(GreaterThanSymbol) || text.Contains(LessThanSymbol) || text.Contains(PercentSymbol); } // return value return needsEncoding; } #endregion #endregion } #endregion }
33.719008
168
0.533578
[ "MIT" ]
DataJuggler/UltimateHelper
XmlPatternHelper.cs
4,082
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; namespace g3 { // This class is analogous to GeneralPolygon2d, but for closed loops of curves, instead // of polygons. However, we cannot do some of the operations we would otherwise do in // GeneralPolygon2d (for example cw/ccw checking, intersctions, etc). // // So, it is strongly recommended that this be constructed alongside a GeneralPolygon2d, // which can be used for checking everything. public class PlanarSolid2d { IParametricCurve2d outer; //bool bOuterIsCW; List<IParametricCurve2d> holes = new List<IParametricCurve2d>(); public PlanarSolid2d() { } public IParametricCurve2d Outer { get { return outer; } } public void SetOuter(IParametricCurve2d loop, bool bIsClockwise) { Debug.Assert(loop.IsClosed); outer = loop; //bOuterIsCW = bIsClockwise; } public void AddHole(IParametricCurve2d hole) { if (outer == null) { throw new Exception("PlanarSolid2d.AddHole: outer polygon not set!"); } // if ( (bOuterIsCW && hole.IsClockwise) || (bOuterIsCW == false && hole.IsClockwise == false) ) //throw new Exception("PlanarSolid2d.AddHole: new hole has same orientation as outer polygon!"); holes.Add(hole); } bool HasHoles { get { return Holes.Count > 0; } } public ReadOnlyCollection<IParametricCurve2d> Holes { get { return holes.AsReadOnly(); } } public bool HasArcLength { get { bool bHas = outer.HasArcLength; foreach (var h in Holes) { bHas = bHas && h.HasArcLength; } return bHas; } } public double Perimeter { get { if (!HasArcLength) { throw new Exception("PlanarSolid2d.Perimeter: some curves do not have arc length"); } double dPerim = outer.ArcLength; foreach (var h in Holes) { dPerim += h.ArcLength; } return dPerim; } } /// <summary> /// Resample parametric solid into polygonal solid /// </summary> public GeneralPolygon2d Convert(double fSpacingLength, double fSpacingT, double fDeviationTolerance) { var poly = new GeneralPolygon2d(); poly.Outer = new Polygon2d( CurveSampler2.AutoSample(this.outer, fSpacingLength, fSpacingT)); poly.Outer.Simplify(0, fDeviationTolerance); foreach (var hole in this.Holes) { var holePoly = new Polygon2d( CurveSampler2.AutoSample(hole, fSpacingLength, fSpacingT)); holePoly.Simplify(0, fDeviationTolerance); poly.AddHole(holePoly, false); } return poly; } } }
21.865546
106
0.681399
[ "BSD-2-Clause" ]
595787816/agg-sharp
geometry3Sharp/curve/PlanarSolid2d.cs
2,604
C#
using System; using UnityEngine; using UnityEngine.EventSystems; using Random = UnityEngine.Random; namespace PcSoft.ExtendedUI._90_Scripts._00_Runtime.Components.UI.Component { [AddComponentMenu(ExtendedUIConstants.Menus.Components.Ui.ComponentMenu + "/Progress Indicator")] [DisallowMultipleComponent] public class UiProgressIndicator : UIBehaviour { #region Inspector Data [Header("Animation")] [SerializeField] [Range(1f, 10f)] private float minSpeed = 1f; [SerializeField] [Range(1f, 10f)] private float maxSpeed = 1f; [SerializeField] private ProgressIndicatorDirection direction = ProgressIndicatorDirection.Random; [Header("References")] [SerializeField] private RectTransform animationTransform; #endregion private float _speed; #region Builtin Methods protected override void Awake() { bool dir; switch (direction) { case ProgressIndicatorDirection.Clockwise: dir = true; break; case ProgressIndicatorDirection.AntiClockwise: dir = false; break; case ProgressIndicatorDirection.Random: dir = Random.Range(0, 2) == 0; break; default: throw new NotImplementedException(); } _speed = Random.Range(minSpeed, maxSpeed) * (dir ? 1 : -1); } protected virtual void LateUpdate() { animationTransform.rotation *= Quaternion.Euler(0f, 0f, _speed * Time.deltaTime); } #endregion } public enum ProgressIndicatorDirection { Clockwise, AntiClockwise, Random } }
27.169014
101
0.561949
[ "Apache-2.0" ]
KleinerHacker/unity.extensions
Assets/PcSoft/ExtendedUI/90 Scripts/00 Runtime/Components/UI/Component/UiProgressIndicator.cs
1,929
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 Microsoft.Win32.SafeHandles; using System; namespace Microsoft.Win32 { #if REGISTRY_ASSEMBLY public #else internal #endif sealed partial class RegistryKey : MarshalByRefObject, IDisposable { private void ClosePerfDataKey() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private void FlushCore() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private void DeleteSubKeyCore(string subkey, bool throwOnMissingSubKey) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private void DeleteSubKeyTreeCore(string subkey) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private void DeleteValueCore(string name, bool throwOnMissingValue) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private static RegistryKey OpenBaseKeyCore(RegistryHive hKey, RegistryView view) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view) { throw new PlatformNotSupportedException(SR.Security_RegistryPermission); // remote stores not supported on Unix } private RegistryKey InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights, bool throwOnPermissionFailure) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private RegistryKey InternalOpenSubKeyCore(string name, bool writable, bool throwOnPermissionFailure) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } internal RegistryKey InternalOpenSubKeyWithoutSecurityChecksCore(string name, bool writable) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private SafeRegistryHandle SystemKeyHandle { get { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } } private int InternalSubKeyCountCore() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private string[] InternalGetSubKeyNamesCore(int subkeys) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private int InternalValueCountCore() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private string[] GetValueNamesCore(int values) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private Object InternalGetValueCore(string name, Object defaultValue, bool doNotExpand) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private RegistryValueKind GetValueKindCore(string name) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private void SetValueCore(string name, Object value, RegistryValueKind valueKind) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private static int GetRegistryKeyAccess(bool isWritable) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } } }
35.404762
172
0.697826
[ "MIT" ]
Acidburn0zzz/corefx
src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.FileSystem.cs
4,461
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. // ---------------------------------------------------------------------------------- using System; namespace Microsoft.Azure.Commands.Resources.Models.ActiveDirectory { public class PSADPasswordCredential { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public Guid KeyId { get; set; } public string Value { get; set; } } }
35.677419
87
0.587703
[ "MIT" ]
DalavanCloud/azure-powershell
src/ResourceManager/Resources/Commands.Resources/Models.ActiveDirectory/PSADPasswordCredential.cs
1,078
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.Network.Inputs { /// <summary> /// A load balancer probe. /// </summary> public sealed class ProbeArgs : Pulumi.ResourceArgs { /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. /// </summary> [Input("intervalInSeconds")] public Input<int>? IntervalInSeconds { get; set; } /// <summary> /// The name of the resource that is unique within the set of probes used by the load balancer. This name can be used to access the resource. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. /// </summary> [Input("numberOfProbes")] public Input<int>? NumberOfProbes { get; set; } /// <summary> /// The port for communicating the probe. Possible values range from 1 to 65535, inclusive. /// </summary> [Input("port", required: true)] public Input<int> Port { get; set; } = null!; /// <summary> /// The protocol of the end point. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' or 'Https' is specified, a 200 OK response from the specifies URI is required for the probe to be successful. /// </summary> [Input("protocol", required: true)] public InputUnion<string, Pulumi.AzureNextGen.Network.ProbeProtocol> Protocol { get; set; } = null!; /// <summary> /// The URI used for requesting health status from the VM. Path is required if a protocol is set to http. Otherwise, it is not allowed. There is no default value. /// </summary> [Input("requestPath")] public Input<string>? RequestPath { get; set; } public ProbeArgs() { } } }
42.538462
312
0.63689
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/Inputs/ProbeArgs.cs
2,765
C#
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using VisitorStatistics.Services.Abstraction; namespace VisitorStatistics.Services { /// <summary> /// The purpose with this timer is to automatically remove visit data from the database based on /// stored deletion dates. The deletion dates are set based on configured deletion days in the /// appsettings.json file, which can be configured via the application admin panel "VisitSettings". /// </summary> public class TimedHostedService : IHostedService, IDisposable { private readonly ILogger<TimedHostedService> _logger; private readonly IServiceScopeFactory _scope; private readonly IConfiguration _config; private Timer _timer; public TimedHostedService(ILogger<TimedHostedService> logger, IConfiguration config, IServiceScopeFactory scope) { _logger = logger; _config = config; _scope = scope; } /// <summary> /// Task to set and start the timer on a daily basis to check for matching /// deletion dates to delete visitor statistics from the database. /// </summary> /// <param name="stoppingToken"></param> /// <returns></returns> public Task StartAsync(CancellationToken stoppingToken) { _logger.LogInformation("Timed Hosted Service running."); _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromDays(1)); return Task.CompletedTask; } /// <summary> /// This is the callback method to trigger the events we want by the timer. /// </summary> /// <param name="state"></param> private void DoWork(object state) { // Create service scope to solve necessary dependency to IVisitorHandler: var scope = _scope.CreateScope(); var handler = scope.ServiceProvider.GetService<IVisitorHandler>(); handler.DeleteVisitors(); _logger.LogInformation("DeleteVisitorsTimer was executed."); } public Task StopAsync(CancellationToken stoppingToken) { _logger.LogInformation("Timed Hosted Service is stopping."); _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } } // End class. } // End namespace.
34.115385
120
0.645246
[ "MIT" ]
annices/VisitorStatistics1.0
VisitorStatistics/Services/DeleteVisitorsTimer.cs
2,663
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// AlipayPcreditHuabeiAuthBusinessConfirmResponse. /// </summary> public class AlipayPcreditHuabeiAuthBusinessConfirmResponse : AopResponse { /// <summary> /// 业务信息回执失败原因描述 /// </summary> [XmlElement("fail_reason")] public string FailReason { get; set; } /// <summary> /// 商户本次操作的请求流水号,用于标示请求流水的唯一性,不能包含除中文、英文、数字以外的字符,需要保证在商户端不重复。 /// </summary> [XmlElement("out_request_no")] public string OutRequestNo { get; set; } } }
26.708333
78
0.597504
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/AlipayPcreditHuabeiAuthBusinessConfirmResponse.cs
779
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class movement : MonoBehaviour { public Animator anim; public bool[] info = new bool[10]; public bool at_flag; private float count_Time = 3; [SerializeField] private float at_Time; private int ran; void Start() { anim = gameObject.GetComponent<Animator>(); info[0] = anim.GetCurrentAnimatorStateInfo(0).IsTag("at1"); info[1] = anim.GetCurrentAnimatorStateInfo(0).IsTag("at2"); info[2] = anim.GetCurrentAnimatorStateInfo(0).IsTag("at3"); info[3] = anim.GetCurrentAnimatorStateInfo(0).IsTag("at4"); at_flag = false; } void Update() { Debug.Log("at_type: " + ran); //Debug.Log("time: " + count_Time); info[0] = anim.GetCurrentAnimatorStateInfo(0).IsTag("at1"); info[1] = anim.GetCurrentAnimatorStateInfo(0).IsTag("at2"); info[2] = anim.GetCurrentAnimatorStateInfo(0).IsTag("at3"); info[3] = anim.GetCurrentAnimatorStateInfo(0).IsTag("at4"); if (!info[0] && !info[1] && !info[2] && !info[3]) { at_flag = false; } if (!at_flag) { if(count_Time >= at_Time) { ran = Random.RandomRange(0, 4); count_Time = 0; at_flag = true; } else { count_Time += Time.deltaTime; } } if (at_flag) { if (ran == 0) at1(); else if (ran == 1) at2(); else if (ran == 2) at3(); else if (ran == 3) at4(); //랜덤으로 뽑아내서 어찌저찌 한다. } } private void at1() { anim.SetTrigger("at1"); } private void at2() { anim.SetTrigger("at2"); } private void at3() // at1+at2 { anim.SetTrigger("at3"); } private void at4() { anim.SetTrigger("at4"); } }
24.39759
67
0.506173
[ "MIT" ]
dandoc/Game
Assets/boss/script/New_boss/movement.cs
2,055
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Linq; using MongoDB.Entities.Tests.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MongoDB.Entities.Tests { [TestClass] public class Saving { [TestMethod] public async Task saving_new_document_returns_an_id() { var book = new Book { Title = "Test" }; await book.SaveAsync(); var idEmpty = string.IsNullOrEmpty(book.ID); Assert.IsFalse(idEmpty); } [TestMethod] public async Task saved_book_has_correct_title() { var book = new Book { Title = "Test" }; await book.SaveAsync(); var title = book.Queryable().Where(b => b.ID == book.ID).Select(b => b.Title).SingleOrDefault(); Assert.AreEqual("Test", title); } [TestMethod] public async Task created_on_property_works() { var author = new Author { Name = "test" }; await author.SaveAsync(); var res = (await DB.Find<Author, DateTime>() .Match(a => a.ID == author.ID) .Project(a => a.CreatedOn) .ExecuteAsync()) .Single(); Assert.AreEqual(res.ToLongTimeString(), author.CreatedOn.ToLongTimeString()); Assert.IsTrue(DateTime.UtcNow.Subtract(res).TotalSeconds <= 5); } [TestMethod] public async Task save_partially_single_include() { var book = new Book { Title = "test book", Price = 100 }; await book.SaveOnlyAsync(b => new { b.Title }); var res = await DB.Find<Book>().MatchID(book.ID).ExecuteSingleAsync(); Assert.AreEqual(0, res.Price); Assert.AreEqual("test book", res.Title); res.Price = 200; await res.SaveOnlyAsync(b => new { b.Price }); res = await DB.Find<Book>().MatchID(res.ID).ExecuteSingleAsync(); Assert.AreEqual(200, res.Price); } [TestMethod] public async Task save_partially_batch_include() { var books = new[] { new Book{ Title = "one", Price = 100}, new Book{ Title = "two", Price = 200} }; await books.SaveOnlyAsync(b => new { b.Title }); var ids = books.Select(b => b.ID).ToArray(); var res = await DB.Find<Book>() .Match(b => ids.Contains(b.ID)) .Sort(b => b.ID, Order.Ascending) .ExecuteAsync(); Assert.AreEqual(0, res[0].Price); Assert.AreEqual(0, res[1].Price); Assert.AreEqual("one", res[0].Title); Assert.AreEqual("two", res[1].Title); } [TestMethod] public async Task save_partially_single_exclude() { var book = new Book { Title = "test book", Price = 100 }; await book.SaveExceptAsync(b => new { b.Title }); var res = await DB.Find<Book>().MatchID(book.ID).ExecuteSingleAsync(); Assert.AreEqual(100, res.Price); Assert.AreEqual(null, res.Title); res.Title = "updated"; await res.SaveExceptAsync(b => new { b.Price }); res = await DB.Find<Book>().MatchID(res.ID).ExecuteSingleAsync(); Assert.AreEqual("updated", res.Title); } [TestMethod] public async Task save_partially_batch_exclude() { var books = new[] { new Book{ Title = "one", Price = 100}, new Book{ Title = "two", Price = 200} }; await books.SaveExceptAsync(b => new { b.Title }); var ids = books.Select(b => b.ID).ToArray(); var res = await DB.Find<Book>() .Match(b => ids.Contains(b.ID)) .Sort(b => b.ID, Order.Ascending) .ExecuteAsync(); Assert.AreEqual(100, res[0].Price); Assert.AreEqual(200, res[1].Price); Assert.AreEqual(null, res[0].Title); Assert.AreEqual(null, res[1].Title); } [TestMethod] public async Task save_preserving_upsert() { var book = new Book { Title = "Original Title", Price = 123.45m, DontSaveThis = 111 }; book.ID = book.GenerateNewID(); book.Title = "updated title"; book.Price = 543.21m; await book.SavePreservingAsync(); book = await DB.Find<Book>().OneAsync(book.ID); Assert.AreEqual("updated title", book.Title); Assert.AreEqual(543.21m, book.Price); Assert.AreEqual(default, book.DontSaveThis); } [TestMethod] public async Task save_preserving() { var book = new Book { Title = "Original Title", Price = 123.45m, DontSaveThis = 111 }; await book.SaveAsync(); book.Title = "updated title"; book.Price = 543.21m; await book.SavePreservingAsync(); book = await DB.Find<Book>().OneAsync(book.ID); Assert.AreEqual("updated title", book.Title); Assert.AreEqual(543.21m, book.Price); Assert.AreEqual(default, book.DontSaveThis); } [TestMethod] public async Task save_preserving_inverse_attribute() { var book = new Book { Title = "original", //dontpreserve Price = 100, //dontpreserve PriceDbl = 666, MainAuthor = ObjectId.GenerateNewId().ToString() }; await book.SaveAsync(); book.Title = "updated"; book.Price = 111; book.PriceDbl = 999; book.MainAuthor = null; await book.SavePreservingAsync(); var res = await DB.Find<Book>().OneAsync(book.ID); Assert.AreEqual(res.Title, book.Title); Assert.AreEqual(res.Price, book.Price); Assert.AreEqual(res.PriceDbl, 666); Assert.IsFalse(res.MainAuthor.ID == null); } [TestMethod] public async Task save_preserving_attribute() { var author = new Author { Age = 123, Name = "initial name", FullName = "initial fullname", Birthday = DateTime.UtcNow }; await author.SaveAsync(); author.Name = "updated author name"; author.Age = 666; //preserve author.Age2 = 400; //preserve author.Birthday = DateTime.MinValue; //preserve author.FullName = null; author.BestSeller = ObjectId.GenerateNewId().ToString(); await author.SavePreservingAsync(); var res = await DB.Find<Author>().OneAsync(author.ID); Assert.AreEqual("updated author name", res.Name); Assert.AreEqual(123, res.Age); Assert.AreEqual(default, res.Age2); Assert.AreNotEqual(DateTime.MinValue, res.Birthday); Assert.AreEqual("initial fullname", res.FullName); Assert.AreEqual(author.BestSeller.ID, res.BestSeller.ID); } [TestMethod] public async Task embedding_non_entity_returns_correct_document() { var book = new Book { Title = "Test" }; book.Review = new Review { Stars = 5, Reviewer = "enercd" }; await book.SaveAsync(); var res = book.Queryable() .Where(b => b.ID == book.ID) .Select(b => b.Review.Reviewer) .SingleOrDefault(); Assert.AreEqual(book.Review.Reviewer, res); } [TestMethod] public async Task embedding_with_ToDocument_returns_correct_doc() { var book = new Book { Title = "Test" }; var author = new Author { Name = "ewtdrcd" }; book.RelatedAuthor = author.ToDocument(); await book.SaveAsync(); var res = book.Queryable() .Where(b => b.ID == book.ID) .Select(b => b.RelatedAuthor.Name) .SingleOrDefault(); Assert.AreEqual(book.RelatedAuthor.Name, res); } [TestMethod] public async Task embedding_with_ToDocument_returns_blank_id() { var book = new Book { Title = "Test" }; var author = new Author { Name = "Test Author" }; book.RelatedAuthor = author.ToDocument(); await book.SaveAsync(); var res = book.Queryable() .Where(b => b.ID == book.ID) .Select(b => b.RelatedAuthor.ID) .SingleOrDefault(); Assert.AreEqual(book.RelatedAuthor.ID, res); } [TestMethod] public async Task embedding_with_ToDocuments_Arr_returns_correct_docs() { var book = new Book { Title = "Test" }; await book.SaveAsync(); var author1 = new Author { Name = "ewtrcd1" }; await author1.SaveAsync(); var author2 = new Author { Name = "ewtrcd2" }; await author2.SaveAsync(); book.OtherAuthors = (new Author[] { author1, author2 }).ToDocuments(); await book.SaveAsync(); var authors = book.Queryable() .Where(b => b.ID == book.ID) .Select(b => b.OtherAuthors).Single(); Assert.AreEqual(authors.Length, 2); Assert.AreEqual(author2.Name, authors[1].Name); Assert.AreEqual(book.OtherAuthors[0].ID, authors[0].ID); } [TestMethod] public async Task embedding_with_ToDocuments_IEnumerable_returns_correct_docs() { var book = new Book { Title = "Test" }; await book.SaveAsync(); var author1 = new Author { Name = "ewtrcd1" }; await author1.SaveAsync(); var author2 = new Author { Name = "ewtrcd2" }; await author2.SaveAsync(); var list = new List<Author>() { author1, author2 }; book.OtherAuthors = list.ToDocuments().ToArray(); await book.SaveAsync(); var authors = book.Queryable() .Where(b => b.ID == book.ID) .Select(b => b.OtherAuthors).Single(); Assert.AreEqual(authors.Length, 2); Assert.AreEqual(author2.Name, authors[1].Name); Assert.AreEqual(book.OtherAuthors[0].ID, authors[0].ID); } [TestMethod] public async Task find_by_lambda_returns_correct_documents() { var guid = Guid.NewGuid().ToString(); var author1 = new Author { Name = guid }; await author1.SaveAsync(); var author2 = new Author { Name = guid }; await author2.SaveAsync(); var res = await DB.Find<Author>().ManyAsync(a => a.Name == guid); Assert.AreEqual(2, res.Count); } [TestMethod] public async Task find_by_id_returns_correct_document() { var book1 = new Book { Title = "fbircdb1" }; await book1.SaveAsync(); var book2 = new Book { Title = "fbircdb2" }; await book2.SaveAsync(); var res1 = await DB.Find<Book>().OneAsync(new ObjectId().ToString()); var res2 = await DB.Find<Book>().OneAsync(book2.ID); Assert.AreEqual(null, res1); Assert.AreEqual(book2.ID, res2.ID); } [TestMethod] public async Task find_by_filter_basic_returns_correct_documents() { var guid = Guid.NewGuid().ToString(); var author1 = new Author { Name = guid }; await author1.SaveAsync(); var author2 = new Author { Name = guid }; await author2.SaveAsync(); var res = await DB.Find<Author>().ManyAsync(f => f.Eq(a => a.Name, guid)); Assert.AreEqual(2, res.Count); } [TestMethod] public async Task find_by_multiple_match_methods() { var guid = Guid.NewGuid().ToString(); var one = new Author { Name = "a", Age = 10, Surname = guid }; await one.SaveAsync(); var two = new Author { Name = "b", Age = 20, Surname = guid }; await two.SaveAsync(); var three = new Author { Name = "c", Age = 30, Surname = guid }; await three.SaveAsync(); var four = new Author { Name = "d", Age = 40, Surname = guid }; await four.SaveAsync(); var res = await DB.Find<Author>() .Match(a => a.Age > 10) .Match(a => a.Surname == guid) .ExecuteAsync(); Assert.AreEqual(3, res.Count); Assert.IsFalse(res.Any(a => a.Age == 10)); } [TestMethod] public async Task find_by_filter_returns_correct_documents() { var guid = Guid.NewGuid().ToString(); var one = new Author { Name = "a", Age = 10, Surname = guid }; await one.SaveAsync(); var two = new Author { Name = "b", Age = 20, Surname = guid }; await two.SaveAsync(); var three = new Author { Name = "c", Age = 30, Surname = guid }; await three.SaveAsync(); var four = new Author { Name = "d", Age = 40, Surname = guid }; await four.SaveAsync(); var res = await DB.Find<Author>() .Match(f => f.Where(a => a.Surname == guid) & f.Gt(a => a.Age, 10)) .Sort(a => a.Age, Order.Descending) .Sort(a => a.Name, Order.Descending) .Skip(1) .Limit(1) .Project(p => p.Include("Name").Include("Surname")) .Option(o => o.MaxTime = TimeSpan.FromSeconds(1)) .ExecuteAsync(); Assert.AreEqual(three.Name, res[0].Name); } private class Test { public string Tester { get; set; } } [TestMethod] public async Task find_with_projection_to_custom_type_works() { var guid = Guid.NewGuid().ToString(); var one = new Author { Name = "a", Age = 10, Surname = guid }; await one.SaveAsync(); var two = new Author { Name = "b", Age = 20, Surname = guid }; await two.SaveAsync(); var three = new Author { Name = "c", Age = 30, Surname = guid }; await three.SaveAsync(); var four = new Author { Name = "d", Age = 40, Surname = guid }; await four.SaveAsync(); var res = (await DB.Find<Author, Test>() .Match(f => f.Where(a => a.Surname == guid) & f.Gt(a => a.Age, 10)) .Sort(a => a.Age, Order.Descending) .Sort(a => a.Name, Order.Descending) .Skip(1) .Limit(1) .Project(a => new Test { Tester = a.Name }) .Option(o => o.MaxTime = TimeSpan.FromSeconds(1)) .ExecuteAsync()) .FirstOrDefault(); Assert.AreEqual(three.Name, res.Tester); } [TestMethod] public async Task find_with_exclusion_projection_works() { var author = new Author { Name = "name", Surname = "sername", Age = 22, FullName = "fullname" }; await author.SaveAsync(); var res = (await DB.Find<Author>() .Match(a => a.ID == author.ID) .ProjectExcluding(a => new { a.Age, a.Name }) .ExecuteAsync()) .Single(); Assert.AreEqual(author.FullName, res.FullName); Assert.AreEqual(author.Surname, res.Surname); Assert.IsTrue(res.Age == default); Assert.IsTrue(res.Name == default); } [TestMethod] public async Task find_with_aggregation_pipeline_returns_correct_docs() { var guid = Guid.NewGuid().ToString(); var one = new Author { Name = "a", Age = 10, Surname = guid }; await one.SaveAsync(); var two = new Author { Name = "b", Age = 20, Surname = guid }; await two.SaveAsync(); var three = new Author { Name = "c", Age = 30, Surname = guid }; await three.SaveAsync(); var four = new Author { Name = "d", Age = 40, Surname = guid }; await four.SaveAsync(); var res = await DB.Fluent<Author>() .Match(a => a.Surname == guid && a.Age > 10) .SortByDescending(a => a.Age) .ThenByDescending(a => a.Name) .Skip(1) .Limit(1) .Project(a => new { Test = a.Name }) .FirstOrDefaultAsync(); Assert.AreEqual(three.Name, res.Test); } [TestMethod] public async Task find_with_aggregation_expression_works() { var guid = Guid.NewGuid().ToString(); var author = new Author { Name = "a", Age = 10, Age2 = 11, Surname = guid }; await author.SaveAsync(); var res = (await DB.Find<Author>() .MatchExpression("{$and:[{$gt:['$Age2','$Age']},{$eq:['$Surname','" + guid + "']}]}") .ExecuteAsync()) .Single(); Assert.AreEqual(res.Surname, guid); } [TestMethod] public async Task find_with_aggregation_expression_using_template_works() { var guid = Guid.NewGuid().ToString(); var author = new Author { Name = "a", Age = 10, Age2 = 11, Surname = guid }; await author.SaveAsync(); var template = new Template<Author>("{$and:[{$gt:['$<Age2>','$<Age>']},{$eq:['$<Surname>','<guid>']}]}") .Path(a => a.Age2) .Path(a => a.Age) .Path(a => a.Surname) .Tag("guid", guid); var res = (await DB.Find<Author>() .MatchExpression(template) .ExecuteAsync()) .Single(); Assert.AreEqual(res.Surname, guid); } [TestMethod] public async Task find_fluent_with_aggregation_expression_works() { var guid = Guid.NewGuid().ToString(); var author = new Author { Name = "a", Age = 10, Age2 = 11, Surname = guid }; await author.SaveAsync(); var res = await DB.Fluent<Author>() .Match(a => a.Surname == guid) .MatchExpression("{$gt:['$Age2','$Age']}") .SingleAsync(); Assert.AreEqual(res.Surname, guid); } [TestMethod] public async Task decimal_properties_work_correctly() { var guid = Guid.NewGuid().ToString(); var book1 = new Book { Title = guid, Price = 100.123m }; await book1.SaveAsync(); var book2 = new Book { Title = guid, Price = 100.123m }; await book2.SaveAsync(); var res = DB.Queryable<Book>() .Where(b => b.Title == guid) .GroupBy(b => b.Title) .Select(g => new { Title = g.Key, Sum = g.Sum(b => b.Price) }).Single(); Assert.AreEqual(book1.Price + book2.Price, res.Sum); } [TestMethod] public async Task ignore_if_defaults_convention_works() { var author = new Author { Name = "test" }; await author.SaveAsync(); var res = await DB.Find<Author>().OneAsync(author.ID); Assert.IsTrue(res.Age == 0); Assert.IsTrue(res.Birthday == null); } [TestMethod] public async Task custom_id_generation_logic_works() { var customer = new CustomerWithCustomID(); await customer.SaveAsync(); var res = await DB.Find<CustomerWithCustomID>().OneAsync(customer.ID); Assert.AreEqual(res.ID, customer.ID); } [TestMethod] public async Task custom_id_used_in_a_relationship() { var customer = new CustomerWithCustomID(); await customer.SaveAsync(); var book = new Book { Title = "ciuiar", Customer = customer }; await book.SaveAsync(); var res = await book.Customer.ToEntityAsync(); Assert.AreEqual(res.ID, customer.ID); var cus = await DB.Queryable<Book>() .Where(b => b.Customer.ID == customer.ID) .Select(b => b.Customer) .SingleOrDefaultAsync(); Assert.AreEqual(cus.ID, customer.ID); } [TestMethod] public async Task custom_id_override_string() { var e = new CustomIDOverride(); await DB.SaveAsync(e); await Task.Delay(100); var creationTime = new DateTime(long.Parse(e.ID)); Assert.IsTrue(creationTime < DateTime.Now); } [TestMethod] public async Task custom_id_override_objectid() { var e = new CustomIDOverride { ID = ObjectId.GenerateNewId().ToString() }; await e.SaveAsync(); Assert.IsTrue(ObjectId.TryParse(e.ID, out _)); } [TestMethod] public Task custom_id_duplicate_throws() { var one = new CustomIDDuplicate(); var two = new CustomIDDuplicate(); return Assert.ThrowsExceptionAsync<MongoBulkWriteException<CustomIDDuplicate>>(() => new[] { one, two }.SaveAsync()); } } }
38.52349
117
0.497125
[ "MIT" ]
unitysir/MongoDB.Entities
Tests/TestSaving.cs
22,960
C#
using JClicker.Upgrades; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Mail; using System.Reflection; using System.Runtime.Remoting.Metadata.W3cXsd2001; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace JClicker { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private List<Upgrade> Upgrades = new List<Upgrade>(); private int TotalCoins = 0; readonly int Interval = 10; // 1MS Run Event private double CountIntervalUpdates = 0; readonly Timer _timer; public int MW_TotalClicks { get; set; } = 0; public MainWindow() { InitializeComponent(); SetupTooltips(); ClickButton.Content = new Image { Source = new BitmapImage(new Uri("cookie.png", UriKind.Relative)), VerticalAlignment = VerticalAlignment.Center, Stretch = Stretch.Fill, Height = 180, Width = 180 }; // Start a repeating timer. _timer = new Timer(Tick, null, Interval, Timeout.Infinite); } /// <summary> /// Set up the tool tips. /// This is done in code and not the XAML. /// </summary> public void SetupTooltips() { //TODO: Change the coins value according to the new set value. PointersLabel.ToolTip = new ToolTip { Content = "Gain 1 extra cookie every 2 seconds.\nCost: 1 Coin\nCPS: 0.5" }; BuyPointerButton.ToolTip = new ToolTip { Content = "Click to buy 1x Pointer upgrade." }; ClickerLabel.ToolTip = new ToolTip { Content = "Gain 3 extra cookies every 1 second.\nCost: 4 Coins\nCPS: 3.0" }; BuyClickerButton.ToolTip = new ToolTip { Content = "Click to buy 1x Clicker upgrade." }; BakerLabel.ToolTip = new ToolTip { Content = "Gain 10 Cookies every second. \nCost: 8 Coins\nCPS: 10" }; BuyBakerButton.ToolTip = new ToolTip { Content = "Click to buy 1x Baker upgrade." }; CookieFarmLabel.ToolTip = new ToolTip { Content = "Gain 35 Cookies every second. \nCost: 14 Coins\nCPS: 35" }; BuyCookieFarmButton.ToolTip = new ToolTip { Content = "Click to buy 1x Cookie Farm upgrade." }; CookieFactoryLabel.ToolTip = new ToolTip { Content = "Gain 100 Cookies every second. \nCost: 30 Coins\nCPS: 100" }; BuyCookieFactoryButton.ToolTip = new ToolTip { Content = "Click to buy 1x Cookie Factory upgrade." }; } public List<Upgrade> GetUpgradeList() { return Upgrades; } private void ClickButton_Click(object sender, RoutedEventArgs e) { MW_TotalClicks++; Console.WriteLine("User clicked the button!"); if(MW_TotalClicks % 100 == 0) { TotalCoins++; } // UpdateVisual() called in CheckForCoins(); } private void Button_Click(object sender, RoutedEventArgs e) { string ButtonPressedName = (sender as Button).Name; // Get the name of button clicked. if(ButtonPressedName.Equals("BuyPointerButton")) { Upgrade upgrade = new PointerUpgrade("Pointer", PointerUpgrade.BasePrice, this); //upgrade.Price *= Upgrades.Count(u => u.GetType() == typeof(PointerUpgrade)); if (TotalCoins < upgrade.Price) { MessageBox.Show($"You do not have enough currency to purchase this item!\nRequired Amount:{upgrade.Price}\nYour Amount:{TotalCoins}"); return; } TotalCoins -= (int)upgrade.Price; Upgrades.Add(upgrade); }else if(ButtonPressedName.Equals("BuyClickerButton")) { Upgrade upgrade = new ClickerUpgrade("Clicker", ClickerUpgrade.BasePrice, this); if (TotalCoins < upgrade.Price) { MessageBox.Show($"You do not have enough currency to purchase this item!\nRequired Amount:{upgrade.Price}\nYour Amount:{TotalCoins}"); return; } TotalCoins -= (int)upgrade.Price; Upgrades.Add(upgrade); }else if(ButtonPressedName.Equals("BuyBakerButton")) { // Setup Baker Upgrade. Upgrade upgrade = new BakerUpgrade("Baker", BakerUpgrade.BasePrice, this); if(TotalCoins < upgrade.Price) { MessageBox.Show($"You do not have enough currency to purchase this item!\nRequired Amount:{upgrade.Price}\nYour Amount:{TotalCoins}"); return; } TotalCoins -= (int)upgrade.Price; Upgrades.Add(upgrade); }else if(ButtonPressedName.Equals("BuyCookieFarmButton")) { Upgrade upgrade = new CookieFarmUpgrade("Cookie Farm", CookieFarmUpgrade.BasePrice, this); if (TotalCoins < upgrade.Price) { MessageBox.Show($"You do not have enough currency to purchase this item!\nRequired Amount:{upgrade.Price}\nYour Amount:{TotalCoins}"); return; } TotalCoins -= (int)upgrade.Price; Upgrades.Add(upgrade); }else if(ButtonPressedName.Equals("BuyCookieFactoryButton")) { Upgrade upgrade = new CookieFactoryUpgrade("Cookie Factory", CookieFactoryUpgrade.BasePrice, this); if(TotalCoins < upgrade.Price) { MessageBox.Show($"You do not have enough currency to purchase this item!\nRequired Amount:{upgrade.Price}\nYour Amount:{TotalCoins}"); return; } TotalCoins -= (int)upgrade.Price; Upgrades.Add(upgrade); } UpdateVisual(); } /// <summary> /// Updates the text on the screen to account for changes. /// </summary> public void UpdateVisual() { ClickCounter.Content = "Total Cookies: " + MW_TotalClicks; CoinCounter.Content = "Total Coins: " + TotalCoins; // List all upgrade labels here. PointersLabel.Content = Upgrades.Count(u => u.GetType() == typeof(PointerUpgrade)) + "x " + "Pointer (0.5CPS) - " + new PointerUpgrade(null,PointerUpgrade.BasePrice,this).Price + "C"; ClickerLabel.Content = Upgrades.Count(u => u.GetType() == typeof(ClickerUpgrade)) + "x Clicker (3CPS) - " + new ClickerUpgrade(null, ClickerUpgrade.BasePrice, this).Price + "C"; ; BakerLabel.Content = Upgrades.Count(u => u.GetType() == typeof(BakerUpgrade)) + "x Baker (10CPS) - " + new BakerUpgrade(null, BakerUpgrade.BasePrice, this).Price + "C"; CookieFarmLabel.Content = Upgrades.Count(u => u.GetType() == typeof(CookieFarmUpgrade)) + "x Cookie Farm (35CPS) - " + new CookieFarmUpgrade(null, CookieFarmUpgrade.BasePrice, this).Price + "C"; CookieFactoryLabel.Content = Upgrades.Count(u => u.GetType() == typeof(CookieFactoryUpgrade)) + "x Cookie Factory (100CPS) - " + new CookieFactoryUpgrade(null, CookieFactoryUpgrade.BasePrice, this).Price + "C"; } bool f1 = true; private void Tick(object state) { CountIntervalUpdates++; try { // Update Coins int previous = MW_TotalClicks; Upgrades.ForEach(u => u.ClickAction(CountIntervalUpdates)); if(previous > 100) { if(f1) { TotalCoins++; f1 = false; } else { // Detect how many coins we should give the player based on the change in clicks. // This checks the distance from the previous number amount to the new amount and decides how many coins to give. (1 Coin every 100) int num1 = previous.ToString().ToCharArray()[previous.ToString().ToCharArray().Length - 3]; int num2 = MW_TotalClicks.ToString().ToCharArray()[previous.ToString().ToCharArray().Length - 3]; if (num1 > num2) { Console.WriteLine("Detected Shift in Number place. Attempting to add coins."); TotalCoins++; if ((MW_TotalClicks - previous) / 100 == 0) { TotalCoins++; } else { TotalCoins += (MW_TotalClicks - previous) / 100; } // TotalCoins += (MW_TotalClicks - previous) / 100; // 933 to 1256 thats +3 Coins } else { int coins = num2 - num1; TotalCoins += coins; } } } // Update UI Dispatcher.Invoke(() => { UpdateVisual(); }); }catch(Exception) { Console.WriteLine("Exception Handled. Added Cookie."); MW_TotalClicks++; } finally { _timer?.Change(Interval, Timeout.Infinite); } } } }
40.920949
222
0.533855
[ "MIT" ]
jluvisi2021/JClicker
JClicker/JClicker/MainWindow.xaml.cs
10,355
C#
namespace Task_6.Problem2 { using System.IO; public static class Program { public static void Main(string[] args) { var lines = File.ReadAllLines("map.txt"); var map = new Map(lines); var vc = new VirtualConsole(); vc.RenderMap(map); var gameLoop = new EventLoop(); var gameLogic = new GameLogic(map, gameLoop, vc); gameLoop.Start(); } } }
22.285714
61
0.525641
[ "Apache-2.0" ]
m0rphed/SPBU-homework-sem02
Source/ProblemSet06/Task-6.2/Task-6.2/Program.cs
470
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Data.Common; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage; namespace Microsoft.EntityFrameworkCore.TestUtilities { public class TestRelationalTransactionFactory : IRelationalTransactionFactory { public TestRelationalTransactionFactory(RelationalTransactionFactoryDependencies dependencies) { Dependencies = dependencies; } protected virtual RelationalTransactionFactoryDependencies Dependencies { get; } public RelationalTransaction Create( IRelationalConnection connection, DbTransaction transaction, Guid transactionId, IDiagnosticsLogger<DbLoggerCategory.Database.Transaction> logger, bool transactionOwned) => new TestRelationalTransaction(connection, transaction, logger, transactionOwned, Dependencies.SqlGenerationHelper); } public class TestRelationalTransaction : RelationalTransaction { private readonly TestSqlServerConnection _testConnection; public TestRelationalTransaction( IRelationalConnection connection, DbTransaction transaction, IDiagnosticsLogger<DbLoggerCategory.Database.Transaction> logger, bool transactionOwned, ISqlGenerationHelper sqlGenerationHelper) : base(connection, transaction, new Guid(), logger, transactionOwned, sqlGenerationHelper) { _testConnection = (TestSqlServerConnection)connection; } public override void Commit() { if (_testConnection.CommitFailures.Count > 0) { var fail = _testConnection.CommitFailures.Dequeue(); if (fail.HasValue) { if (fail.Value) { this.GetDbTransaction().Rollback(); } else { this.GetDbTransaction().Commit(); } _testConnection.DbConnection.Close(); throw SqlExceptionFactory.CreateSqlException(_testConnection.ErrorNumber, _testConnection.ConnectionId); } } base.Commit(); } public override async Task CommitAsync(CancellationToken cancellationToken = default) { if (_testConnection.CommitFailures.Count > 0) { var fail = _testConnection.CommitFailures.Dequeue(); if (fail.HasValue) { if (fail.Value) { await this.GetDbTransaction().RollbackAsync(cancellationToken); } else { await this.GetDbTransaction().CommitAsync(cancellationToken); } await _testConnection.DbConnection.CloseAsync(); throw SqlExceptionFactory.CreateSqlException(_testConnection.ErrorNumber, _testConnection.ConnectionId); } } await base.CommitAsync(cancellationToken); } public override bool SupportsSavepoints => true; /// <inheritdoc /> public override void ReleaseSavepoint(string name) { } /// <inheritdoc /> public override Task ReleaseSavepointAsync(string name, CancellationToken cancellationToken = default) => Task.CompletedTask; } }
36.333333
130
0.607602
[ "Apache-2.0" ]
0x0309/efcore
test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestRelationalTransaction.cs
3,815
C#
using System; using System.Linq; using BluffinMuffin.Poker.Common.Contract; namespace BluffinMuffin.Poker.Common.Helpers { public interface IStringCardHelper { string CardToString(ICard card); ICard StringToCard(string s); } public class StringCardHelper : IStringCardHelper { private static readonly string[] _values = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" }; private static readonly string[] _suits = { "C", "D", "H", "S" }; public string CardToString(ICard card) { return $"{_values[(int)card.Value]}{_suits[(int)card.Suit]}"; } public ICard StringToCard(string s) { if (s.Length < 2 || s.Length > 3) throw new InvalidStringRepresentationException(s, "Length"); var value = s.Remove(s.Length - 1).ToUpper(); if (!_values.Contains(value)) throw new InvalidStringRepresentationException(s, "Value"); var suit = s.Substring(s.Length - 1, 1).ToUpper(); if (!_suits.Contains(suit)) throw new InvalidStringRepresentationException(s, "Suit"); return new Card { Suit = (CardSuitEnum)Array.IndexOf(_suits, suit), Value = (CardValueEnum)Array.IndexOf(_values, value) }; } } }
34.384615
135
0.58613
[ "MIT" ]
BluffinMuffin/Poker.Common
src/Poker.Common/Helpers/StringCardHelper.cs
1,343
C#
// ========================================================================== // Notifo.io // ========================================================================== // Copyright (c) Sebastian Stehle // All rights reserved. Licensed under the MIT license. // ========================================================================== namespace Notifo.Domain.UserNotifications { public enum UserNotificationQueryScope { NonDeleted, Deleted, All } }
28.941176
78
0.345528
[ "MIT" ]
INOS-soft/notifo
backend/src/Notifo.Domain/UserNotifications/UserNotificationQueryScope.cs
494
C#
namespace Havit.NewProjectTemplate.Model.Localizations { /// <summary> /// Lokalizace. /// </summary> public interface ILocalization<TLocalizedEntity> : Havit.Model.Localizations.ILocalization<TLocalizedEntity, Language> { new TLocalizedEntity Parent { get; set; } // new - Havit.Model.Localizations.ILocalization<,> jiĹľ má vlastnost Parent int ParentId { get; set; } new Language Language { get; set; } // new - Havit.Model.Localizations.ILocalization<,> jiĹľ má vlastnost Language int LanguageId { get; set; } } }
35.666667
121
0.736449
[ "MIT" ]
havit/NewProjectTemplate-React
Model/Localizations/ILocalization.cs
545
C#
// // UIImagePickerContrller.cs // // Authors: // Miguel de Icaza // // Copyright 2009, Novell, Inc. // Copyright 2012-2014 Xamarin Inc // #if !TVOS && !WATCH // __TVOS_PROHIBITED, doesn't show up in WatchOS headers using ObjCRuntime; using Foundation; using CoreGraphics; using Photos; using System; using System.Drawing; using System.Runtime.Versioning; namespace UIKit { public partial class UIImagePickerController { // // The following construct emulates the support for: // id<UINavigationControllerDelegate, UIImagePickerControllerDelegate> // // That is, the type can contain either one, but we still want it strongly typed // #if NET public IUIImagePickerControllerDelegate ImagePickerControllerDelegate { get { return Delegate as IUIImagePickerControllerDelegate; } set { Delegate = (NSObject) value; } } public IUINavigationControllerDelegate NavigationControllerDelegate { get { return Delegate as IUINavigationControllerDelegate; } set { Delegate = (NSObject) value; } } #else public UIImagePickerControllerDelegate ImagePickerControllerDelegate { get { return Delegate as UIImagePickerControllerDelegate; } set { Delegate = value; } } public UINavigationControllerDelegate NavigationControllerDelegate { get { return Delegate as UINavigationControllerDelegate; } set { Delegate = value; } } #endif } public partial class UIImagePickerMediaPickedEventArgs { public string MediaType { get { return ((NSString)Info [UIImagePickerController.MediaType]).ToString (); } } public UIImage OriginalImage { get { return (UIImage) Info [UIImagePickerController.OriginalImage]; } } public UIImage EditedImage { get { return (UIImage) Info [UIImagePickerController.EditedImage]; } } public CGRect? CropRect { get { var nsv = ((NSValue)Info [UIImagePickerController.CropRect]); if (nsv == null) return null; return nsv.CGRectValue; } } public NSUrl MediaUrl { get { return (NSUrl) Info [UIImagePickerController.MediaURL]; } } #if NET [SupportedOSPlatform ("ios9.1")] #else [iOS (9,1)] #endif public PHLivePhoto LivePhoto { get { return (PHLivePhoto) Info [UIImagePickerController.LivePhoto]; } } public NSDictionary MediaMetadata { get { return (NSDictionary) Info [UIImagePickerController.MediaMetadata]; } } public NSUrl ReferenceUrl { get { return (NSUrl) Info [UIImagePickerController.ReferenceUrl]; } } #if NET [SupportedOSPlatform ("ios11.0")] #else [iOS (11,0)] #endif public PHAsset PHAsset { get { return (PHAsset) Info [UIImagePickerController.PHAsset]; } } #if NET [SupportedOSPlatform ("ios11.0")] #else [iOS (11,0)] #endif public NSUrl ImageUrl { get { return (NSUrl) Info [UIImagePickerController.ImageUrl]; } } } } #endif // !TVOS && !WATCH
19.427632
82
0.693532
[ "BSD-3-Clause" ]
NormanChiflen/xamarin-all-IOS
src/UIKit/UIImagePickerController.cs
2,953
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.FIS; using Amazon.FIS.Model; namespace Amazon.PowerShell.Cmdlets.FIS { [AWSClientCmdlet("AWS Fault Injection Simulator", "FIS", "2020-12-01", "FIS")] public abstract partial class AmazonFISClientCmdlet : ServiceCmdlet { protected IAmazonFIS Client { get; private set; } protected IAmazonFIS CreateClient(AWSCredentials credentials, RegionEndpoint region) { var config = new AmazonFISConfig { RegionEndpoint = region }; Amazon.PowerShell.Utils.Common.PopulateConfig(this, config); this.CustomizeClientConfig(config); var client = new AmazonFISClient(credentials, config); client.BeforeRequestEvent += RequestEventHandler; client.AfterResponseEvent += ResponseEventHandler; return client; } protected override void ProcessRecord() { base.ProcessRecord(); Client = CreateClient(_CurrentCredentials, _RegionEndpoint); } } }
37.943396
92
0.636002
[ "Apache-2.0" ]
QPC-database/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/FIS/AmazonFISClientCmdlet.cs
2,011
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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. #if !SILVERLIGHT // we do not support xml config on SL namespace Castle.Windsor.Tests.Configuration2 { using NUnit.Framework; [TestFixture] public class ConfigWithStatementsTestCase { private IWindsorContainer container; [TestCase("debug")] [TestCase("prod")] [TestCase("qa")] [TestCase("default")] public void SimpleChoose(string flag) { var file = ConfigHelper.ResolveConfigPath("Configuration2/config_with_define_{0}.xml", flag); container = new WindsorContainer(file); var store = container.Kernel.ConfigurationStore; Assert.AreEqual(1, store.GetComponents().Length); var config = store.GetComponentConfiguration(flag); Assert.IsNotNull(config); } [Test] public void SimpleIf() { container = new WindsorContainer(ConfigHelper.ResolveConfigPath("Configuration2/config_with_if_stmt.xml")); var store = container.Kernel.ConfigurationStore; Assert.AreEqual(4, store.GetComponents().Length); var config = store.GetComponentConfiguration("debug"); Assert.IsNotNull(config); var childItem = config.Children["item"]; Assert.IsNotNull(childItem); Assert.AreEqual("some value", childItem.Value); childItem = config.Children["item2"]; Assert.IsNotNull(childItem); Assert.AreEqual("some <&> value2", childItem.Value); config = store.GetComponentConfiguration("qa"); Assert.IsNotNull(config); config = store.GetComponentConfiguration("default"); Assert.IsNotNull(config); config = store.GetComponentConfiguration("notprod"); Assert.IsNotNull(config); } } } #endif
29.934211
111
0.712088
[ "Apache-2.0" ]
castleproject-deprecated/Castle.Windsor-READONLY
src/Castle.Windsor.Tests/Configuration2/ConfigWithStatementsTestCase.cs
2,275
C#
using CSRedis.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace CSRedisCore.Tests { public class Resp3HelperTests { public class RedisSocket : IDisposable { Socket _socket; public NetworkStream Stream { get; } public RedisSocket(Socket socket) { _socket = socket; Stream = new NetworkStream(_socket, true); } public void Dispose() { _socket.Shutdown(SocketShutdown.Both); _socket.Close(); _socket.Dispose(); } public static RedisSocket GetRedisSocket() { var endpoint = new IPEndPoint(IPAddress.Parse("192.168.164.10"), 6379); var _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(endpoint); return new RedisSocket(_socket); } } static object[] PrepareCmd(string cmd, string subcmd = null, params object[] parms) { if (string.IsNullOrWhiteSpace(cmd)) throw new ArgumentNullException("Redis command not is null or empty."); object[] args = null; if (parms?.Any() != true) { if (string.IsNullOrWhiteSpace(subcmd) == false) args = new object[] { cmd, subcmd }; else args = cmd.Split(' ').Where(a => string.IsNullOrWhiteSpace(a) == false).ToArray(); } else { var issubcmd = string.IsNullOrWhiteSpace(subcmd) == false; args = new object[parms.Length + 1 + (issubcmd ? 1 : 0)]; var argsIdx = 0; args[argsIdx++] = cmd; if (issubcmd) args[argsIdx++] = subcmd; foreach (var prm in parms) args[argsIdx++] = prm; } return args; } static Resp3Helper.ReadResult<T> ExecCmd<T>(string cmd, string subcmd = null, params object[] parms) { var args = PrepareCmd(cmd, subcmd, parms); using (var rds = RedisSocket.GetRedisSocket()) { Resp3Helper.Write(rds.Stream, args, true); var rt = Resp3Helper.Read<T>(rds.Stream); return rt; } } static ExecCmdListenResult ExecCmdListen(Action<ExecCmdListenResult, string> ondata, string cmd, string subcmd = null, params object[] parms) { var args = PrepareCmd(cmd, subcmd, parms); var rds = RedisSocket.GetRedisSocket(); Resp3Helper.Write(rds.Stream, args, true); var rd = Resp3Helper.Read<string>(rds.Stream); var rt = new ExecCmdListenResult { rds = rds }; new Thread(() => { ondata?.Invoke(rt, rd.Value); while (rt._running) { try { ondata?.Invoke(rt, Resp3Helper.Read<string>(rds.Stream).Value); } catch(Exception ex) { Console.WriteLine(ex.Message); } } }).Start(); return rt; } public class ExecCmdListenResult : IDisposable { internal RedisSocket rds; internal bool _running = true; public void Dispose() => _running = false; } class RedisCommand { class RedisServerException : Exception { public RedisServerException(string message) : base(message) { } } public Resp3Helper.ReadResult<string[]> AclCat(string categoryname = null) => string.IsNullOrWhiteSpace(categoryname) ? ExecCmd<string[]>("ACL", "CAT") : ExecCmd<string[]>("ACL", "CAT", categoryname); public Resp3Helper.ReadResult<int> AclDelUser(params string[] username) => username?.Any() == true ? ExecCmd<int>("ACL", "DELUSER", username) : throw new ArgumentException(nameof(username)); public Resp3Helper.ReadResult<string> AclGenPass(int bits = 0) => bits <= 0 ? ExecCmd<string>("ACL", "GENPASS") : ExecCmd<string>("ACL", "GENPASS", bits); public Resp3Helper.ReadResult<string[]> AclList() => ExecCmd<string[]>("ACL", "LIST"); public Resp3Helper.ReadResult<string> AclLoad() => ExecCmd<string>("ACL", "LOAD"); public Resp3Helper.ReadResult<LogInfo[]> AclLog(long count = 0) => (count <= 0 ? ExecCmd<object[][]>("ACL", "LOG") : ExecCmd<object[][]>("ACL", "LOG", count)).NewValue(x => x.Select(a => a.MapToClass<LogInfo>()).ToArray()); public class LogInfo { public long Count { get; } public string Reason { get; } public string Context { get; } public string Object { get; } public string Username { get; } public decimal AgeSeconds { get; } public string ClientInfo { get; } } public Resp3Helper.ReadResult<string> AclSave() => ExecCmd<string>("ACL", "SAVE"); public Resp3Helper.ReadResult<string> AclSetUser(params string[] rule) => rule?.Any() == true ? ExecCmd<string>("ACL", "SETUSER", rule) : throw new ArgumentException(nameof(rule)); public Resp3Helper.ReadResult<string[]> AclUsers() => ExecCmd<string[]>("ACL", "USERS"); public Resp3Helper.ReadResult<string> AclWhoami() => ExecCmd<string>("ACL", "WHOAMI"); public Resp3Helper.ReadResult<string> BgRewriteAof() => ExecCmd<string>("BGREWRITEAOF"); public Resp3Helper.ReadResult<string> BgSave(string schedule = null) => ExecCmd<string>("BGSAVE", schedule); public Resp3Helper.ReadResult<object[]> Command() => ExecCmd<object[]>("COMMAND"); public Resp3Helper.ReadResult<int> CommandCount() => ExecCmd<int>("COMMAND", "COUNT"); public Resp3Helper.ReadResult<string[]> CommandGetKeys(params string[] command) => command?.Any() == true ? ExecCmd<string[]>("COMMAND", "GETKEYS", command) : throw new ArgumentException(nameof(command)); public Resp3Helper.ReadResult<string[]> CommandInfo(params string[] command) => command?.Any() == true ? ExecCmd<string[]>("COMMAND", "INFO", command) : throw new ArgumentException(nameof(command)); public Resp3Helper.ReadResult<Dictionary<string, string>> ConfigGet(string parameter) => ExecCmd<string[]>("CONFIG", "GET", parameter).NewValue(a => a.MapToHash<string>()); public Resp3Helper.ReadResult<string> ConfigResetStat() => ExecCmd<string>("CONFIG", "RESETSTAT"); public Resp3Helper.ReadResult<string> ConfigRewrite() => ExecCmd<string>("CONFIG", "REWRITE"); public Resp3Helper.ReadResult<string> ConfigSet(string parameter, object value) => ExecCmd<string>("CONFIG", "SET", parameter, value); public Resp3Helper.ReadResult<long> DbSize() => ExecCmd<long>("DBSIZE"); public Resp3Helper.ReadResult<string> DebugObject(string key) => ExecCmd<string>("DEBUG", "OBJECT", key); public Resp3Helper.ReadResult<string> DebugSegfault() => ExecCmd<string>("DEBUG", "SEGFAULT"); public Resp3Helper.ReadResult<string> FlushAll(bool isasync = false) => ExecCmd<string>("FLUSHALL", isasync ? "ASYNC" : null); public Resp3Helper.ReadResult<string> FlushDb(bool isasync = false) => ExecCmd<string>("FLUSHDB", isasync ? "ASYNC" : null); public Resp3Helper.ReadResult<string> Info(string section = null) => ExecCmd<string>("INFO", section); public Resp3Helper.ReadResult<long> LastSave() => ExecCmd<long>("LASTSAVE"); public Resp3Helper.ReadResult<string> LatencyDoctor() => ExecCmd<string>("LATENCY", "DOCTOR"); public Resp3Helper.ReadResult<string> LatencyGraph(string @event) => ExecCmd<string>("LATENCY", "GRAPH", @event); public Resp3Helper.ReadResult<string[]> LatencyHelp() => ExecCmd<string[]>("LATENCY", "HELP"); public Resp3Helper.ReadResult<string[][]> LatencyHistory(string @event) => ExecCmd<string[][]>("HISTORY", "HELP", @event); public Resp3Helper.ReadResult<string[][]> LatencyLatest() => ExecCmd<string[][]>("HISTORY", "LATEST"); public Resp3Helper.ReadResult<long> LatencyReset(string @event) => ExecCmd<long>("LASTSAVE", "RESET", @event); public Resp3Helper.ReadResult<string> Lolwut(string version) => ExecCmd<string>("LATENCY", string.IsNullOrWhiteSpace(version) ? null : $"VERSION {version}"); public Resp3Helper.ReadResult<string> MemoryDoctor() => ExecCmd<string>("MEMORY", "DOCTOR"); public Resp3Helper.ReadResult<string[]> MemoryHelp() => ExecCmd<string[]>("MEMORY", "HELP"); public Resp3Helper.ReadResult<string> MemoryMallocStats() => ExecCmd<string>("MEMORY", "MALLOC-STATS"); public Resp3Helper.ReadResult<string> MemoryPurge() => ExecCmd<string>("MEMORY", "PURGE"); public Resp3Helper.ReadResult<Dictionary<string, string>> MemoryStats() => ExecCmd<string[]>("MEMORY", "STATS").NewValue(a => a.MapToHash<string>()); public Resp3Helper.ReadResult<long> MemoryUsage(string key, long count = 0) => count <= 0 ? ExecCmd<long>("MEMORY ", "USAGE", key) : ExecCmd<long>("MEMORY ", "USAGE", key, "SAMPLES", count); public Resp3Helper.ReadResult<string[][]> ModuleList() => ExecCmd<string[][]>("MODULE", "LIST"); public Resp3Helper.ReadResult<string> ModuleLoad(string path, params string[] args) => args?.Any() == true ? ExecCmd<string>("MODULE", "LOAD", new[] { path }.Concat(args)) : ExecCmd<string>("MODULE", "LOAD", path); public Resp3Helper.ReadResult<string> ModuleUnload(string name) => ExecCmd<string>("MODULE", "UNLOAD", name); public ExecCmdListenResult Monitor(Action<ExecCmdListenResult, string> onData) => ExecCmdListen(onData, "MONITOR"); public ExecCmdListenResult Psync(string replicationid, string offset, Action<ExecCmdListenResult, string> onData) => ExecCmdListen(onData, "PSYNC", replicationid, offset); public Resp3Helper.ReadResult<string> ReplicaOf(string host, int port) => ExecCmd<string>("REPLICAOF", host, port); public Resp3Helper.ReadResult<object> Role() => ExecCmd<object>("ROLE"); public Resp3Helper.ReadResult<string> Save() => ExecCmd<string>("SAVE"); public Resp3Helper.ReadResult<string> Shutdown(bool save) => ExecCmd<string>("SHUTDOWN", save ? "SAVE" : "NOSAVE"); public Resp3Helper.ReadResult<string> SlaveOf(string host, int port) => ExecCmd<string>("SLAVEOF", host, port); public Resp3Helper.ReadResult<object> SlowLog(string subcommand, params string[] argument) => ExecCmd<object>("SLOWLOG", subcommand, argument); public Resp3Helper.ReadResult<string> SwapDb(int index1, int index2) => ExecCmd<string>("SWAPDB", null, index1, index2); public ExecCmdListenResult Sync(Action<ExecCmdListenResult, string> onData) => ExecCmdListen(onData, "SYNC"); public Resp3Helper.ReadResult<DateTime> Time() => ExecCmd<long[]>("TIME").NewValue(a => new DateTime(1970, 0, 0).AddSeconds(a[0]).AddTicks(a[1] * 10)); } RedisCommand rds { get; } = new RedisCommand(); #region server test [Fact] public void BgRewriteAof() { var rt = rds.BgRewriteAof(); if (!rt.IsError) rt.Value.AssertEqual("Background append only file rewriting started"); } [Fact] public void BgSave() { var rt = rds.BgSave(); if (!rt.IsError) rt.Value.AssertEqual("Background saving started"); } [Fact] public void Command() { string UFString(string text) { if (text.Length <= 1) return text.ToUpper(); else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1); } var rt = rds.Command(); var sb = string.Join("\r\n\r\n", (rt.Value).OrderBy(a1 => (a1 as List<object>)[0].ToString()).Select(a1 => { var a = a1 as List<object>; var plen = int.Parse(a[1].ToString()); var firstKey = int.Parse(a[3].ToString()); var lastKey = int.Parse(a[4].ToString()); var stepCount = int.Parse(a[5].ToString()); var parms = ""; if (plen > 1) { for (var x = 1; x < plen; x++) { if (x == firstKey) parms += "string key, "; else parms += "string parm, "; } parms = parms.Remove(parms.Length - 2); } if (plen < 0) { for (var x = 1; x < -plen; x++) { if (x == firstKey) parms += "string key, "; else parms += "string parm, "; } if (parms.Length > 0) parms = parms.Remove(parms.Length - 2); } return $@" //{string.Join(", ", a[2] as List<object>)} //{string.Join(", ", a[6] as List<object>)} public void {UFString(a[0].ToString())}({parms}) {{ }}"; })); } [Fact] public void CommandCount() { var rt = rds.CommandCount(); if (!rt.IsError) (rt.Value > 100).AssertEqual(true); } [Fact] public void CommandGetKeys() { var rt = rds.CommandGetKeys("MSET", "a", "b", "c", "d", "e", "f"); if (!rt.IsError) { rt.Value[0].AssertEqual("a"); rt.Value[1].AssertEqual("c"); rt.Value[2].AssertEqual("e"); } } [Fact] public void ConfigGet() { var rt = rds.ConfigGet("*max-*-entries*"); if (!rt.IsError) { rt.Value.ContainsKey("hash-max-ziplist-entries").AssertEqual(true); rt.Value.ContainsKey("set-max-intset-entries").AssertEqual(true); rt.Value.ContainsKey("zset-max-ziplist-entries").AssertEqual(true); } } [Fact] public void ConfigResetStat() { var rt = rds.ConfigResetStat(); if (!rt.IsError) rt.Value.AssertEqual("OK"); } [Fact] public void ConfigRewrite() { var rt = rds.ConfigRewrite(); if (!rt.IsError) rt.Value.AssertEqual("OK"); } [Fact] public void ConfigSet() { var rt = rds.ConfigSet("hash-max-ziplist-entries", 512); if (!rt.IsError) rt.Value.AssertEqual("OK"); } [Fact] public void DbSize() { var rt = rds.DbSize(); if (!rt.IsError) (rt.Value >= 0).AssertEqual(true); } [Fact] public void DebugObject() { var rt = rds.ConfigSet("hash-max-ziplist-entries", 512); if (!rt.IsError) rt.Value.AssertEqual("Value at:"); //Value at:0x7f52b584aa80 refcount:2147483647 encoding:int serializedlength:2 lru:12199791 lru_seconds_idle:40537 } [Fact] public void LastSave() { var rt = rds.LastSave(); if (!rt.IsError) (rt.Value >= 0).AssertEqual(true); } [Fact] public void LatencyHelp() { var rt = rds.LatencyHelp(); if (!rt.IsError) (rt.Value.Length > 0).AssertEqual(true); } [Fact] public void MemoryStats() { var rt = rds.MemoryStats(); if (!rt.IsError) rt.Value.ContainsKey("keys.count").AssertEqual(true); } [Fact] public void MemoryUsage() { var rt = rds.MemoryUsage("key"); if (!rt.IsError) (rt.Value > 0).AssertEqual(true); } #endregion #region acl test [Fact] public void AclCat() { var assertList = new[] { "keyspace", "read", "write", "set", "sortedset", "list", "hash", "string", "bitmap", "hyperloglog", "geo", "stream", "pubsub", "admin", "fast", "slow", "blocking", "dangerous", "connection", "transaction", "scripting" }; var rt = rds.AclCat(); if (!rt.IsError) assertList.Where(a => rt.Value.Contains(a)).Count().AssertEqual(assertList.Length); assertList = new[] { "flushdb", "lastsave", "info", "latency", "slowlog", "replconf", "slaveof", "acl", "flushall", "role", "pfdebug", "cluster", "shutdown", "restore-asking", "sort", "sync", "pfselftest", "restore", "swapdb", "config", "keys", "psync", "migrate", "bgsave", "monitor", "bgrewriteaof", "module", "debug", "save", "client", "replicaof" }; rt = rds.AclCat("dangerous"); if (!rt.IsError) assertList.Where(a => rt.Value.Contains(a)).Count().AssertEqual(assertList.Length); } [Fact] public void AclDelUser() { var rt = rds.AclDelUser("antirez"); if (!rt.IsError) rt.Value.AssertEqual(0); } [Fact] public void AclGenPass() { var rt = rds.AclGenPass(); if (!rt.IsError) rt.Value.ToString().Length.AssertEqual(64); rt = rds.AclGenPass(32); if (!rt.IsError) rt.Value.ToString().Length.AssertEqual(8); rt = rds.AclGenPass(5); if (!rt.IsError) rt.Value.ToString().Length.AssertEqual(2); } [Fact] public void AclList() { //1) "user default on nopass ~* +@all" //2) "user karin on +@all -@admin -@dangerous" //1) "user antirez on #9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 ~objects:* +@all -@admin -@dangerous" //2) "user default on nopass ~* +@all" var rt = rds.AclList(); if (!rt.IsError) rt.Value[0].StartsWith("user ").AssertEqual(true); } [Fact] public void AclLoad() { var rt = rds.AclLoad(); if (!rt.IsError) rt.Value.AssertEqual("OK"); //rt.Value.ToString().StartsWith("ERR This Redis instance is not configured to use an ACL file."); } [Fact] public void AclLog() { //127.0.0.1:6379> acl log 1 //1) 1# "count" => (integer) 1 // 2# "reason" => "auth" // 3# "context" => "toplevel" // 4# "object" => "AUTH" // 5# "username" => "someuser" // 6# "age-seconds" => (double) 8.3040000000000003 // 7# "client-info" => "id=8 addr=127.0.0.1:40298 fd=8 name= age=6802 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=48 qbuf-free=32720 obl=0 oll=0 omem=0 events=r cmd=auth user=default" ExecCmd<string>("AUTH someuser wrongpassword"); var rt = rds.AclLog(); if (!rt.IsError) rt.Value.AssertEqual("OK"); } [Fact] public void AclSave() { var rt = rds.AclSave(); if (!rt.IsError) rt.Value.AssertEqual("OK"); //rt.Value.ToString().StartsWith("ERR This Redis instance is not configured to use an ACL file."); } [Fact] public void AclSetUser() { var rt = rds.AclSetUser("karin", "on", "+@all", "-@dangerous"); if (!rt.IsError) rt.Value.AssertEqual("OK"); } [Fact] public void AclUsers() { var rt = rds.AclUsers(); if (!rt.IsError) rt.Value.Contains("default").AssertEqual(true); } [Fact] public void AclWhoami() { var rt = rds.AclWhoami(); if (!rt.IsError) rt.Value.AssertEqual("default"); } #endregion // [Fact] //public void Set() //{ // var val = Guid.NewGuid().ToString(); // ExecCmd("SET", "test01", val).AssertEqual("OK"); // ExecCmd("GET", "test01").AssertEqual(val); // ExecCmd("SET", "test02", Encoding.UTF8.GetBytes(val)).AssertEqual("OK"); // ExecCmd("SET", "test02", val).AssertEqual(val); //} } static class TestExntesions { public static void AssertEqual(this object obj, object val) => Assert.Equal(val, obj); } }
42.230024
356
0.662749
[ "MIT" ]
277366155/csredis
test/CSRedisCore.Tests/Resp3HelperTests.cs
17,443
C#
using System.Net; namespace ArangoDBNetStandard.CollectionApi.Models { public class GetCollectionFiguresResponse { public FiguresResult Figures { get; set; } public CollectionKeyOptions KeyOptions { get; set; } public string GloballyUniqueId { get; set; } public string StatusString { get; set; } public string Id { get; set; } public int IndexBuckets { get; set; } public string Error { get; set; } public HttpStatusCode Code { get; set; } public CollectionType Type { get; set; } public int Status { get; set; } public int JournalSize { get; set; } public bool IsVolatile { get; set; } public string Name { get; set; } public bool DoCompact { get; set; } public bool IsSystem { get; set; } public int Count { get; set; } public bool WaitForSync { get; set; } } }
22.166667
60
0.60043
[ "Apache-2.0" ]
Actify-Inc/arangodb-net-standard
arangodb-net-standard/CollectionApi/Models/GetCollectionFiguresResponse.cs
933
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("Orchard.ImageProcessing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Orchard")] [assembly: AssemblyCopyright("")] [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("8ac0ba94-3401-4a83-8d40-5a3aa569d4ff")] // 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.10")] [assembly: AssemblyFileVersion("1.10")]
35.972973
84
0.752817
[ "BSD-3-Clause" ]
Accessit-Dev/Accessit.Blog
src/Orchard.Web/Modules/Orchard.MediaProcessing/Properties/AssemblyInfo.cs
1,331
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Windows.Input; using Android.OS; using Android.Runtime; using Android.Support.V7.Widget; using Android.Views; using MvvmCross.Binding; using MvvmCross.Binding.BindingContext; using MvvmCross.Binding.Droid.BindingContext; using MvvmCross.Binding.ExtensionMethods; using MvvmCross.Droid.Support.V7.RecyclerView; using MvvmCross.Droid.Support.V7.RecyclerView.ItemTemplates; using MvvmCross.Platform.Platform; using MvvmCross.Platform.WeakSubscription; #pragma warning disable CS0618 namespace AppRopio.Base.Droid.Adapters { public interface IARFlatGroupTemplateSelector : IMvxTemplateSelector { int GetHeaderViewType(object forItemObject); int GetFooterViewType(object forItemObject); } public delegate void TuneViewHolderOnCreateDelegate(RecyclerView.ViewHolder viewHolder, int viewType); public delegate void TuneViewHolderOnBindDelegate(bool first, bool last, RecyclerView.ViewHolder viewHolder); public class ARFlatGroupAdapter : RecyclerView.Adapter, IMvxRecyclerAdapter { #region Fields private IDisposable _subscription; private List<int> _headersPostions; private List<int> _footerPostions; private List<int> _headersViewTypes; private List<int> _footerViewTypes; private List<object> _flatItems; private ICommand _itemClick, _itemLongClick, _sectionClick, _sectionLongClick; private InnerItemsProviderDelegate _innerItemsProvider; private int _headerLayout = -1; private int _footerLayout = -1; protected readonly IMvxAndroidBindingContext _bindingContext; #endregion #region Properties public int HeadersCount => _headersPostions?.Count ?? 0; public int FootersCount => _footerPostions?.Count ?? 0; public bool ReloadOnAllItemsSourceSets { get; set; } public delegate IEnumerable InnerItemsProviderDelegate(object item); public Func<object, bool> HasHeader { get; set; } public Func<object, bool> HasFooter { get; set; } public TuneViewHolderOnBindDelegate TuneSectionHeaderOnBind { get; set; } public TuneViewHolderOnBindDelegate TuneSectionItemOnBind { get; set; } public TuneViewHolderOnBindDelegate TuneSectionFooterOnBind { get; set; } public TuneViewHolderOnCreateDelegate TuneViewHolderOnCreate { get; set; } public ICommand SectionClick { get { return _sectionClick; } set { if (ReferenceEquals(_sectionClick, value)) { return; } if (_sectionClick != null) { MvxTrace.Warning("Changing ItemClick may cause inconsistencies where some items still call the old command."); } _sectionClick = value; } } public ICommand SectionLongClick { get { return _sectionLongClick; } set { if (ReferenceEquals(_sectionLongClick, value)) { return; } if (_sectionLongClick != null) { MvxTrace.Warning("Changing ItemLongClick may cause inconsistencies where some items still call the old command."); } _sectionLongClick = value; } } private IARFlatGroupTemplateSelector _flatGroupTemplateSelector; public virtual IARFlatGroupTemplateSelector FlatGroupTemplateSelector { get { return _flatGroupTemplateSelector; } set { if (ReferenceEquals(_itemTemplateSelector, value)) return; _flatGroupTemplateSelector = value; if (_flatItems != null) NotifyDataSetChanged(); } } #region IMvxRecyclerAdapter Implementation private IEnumerable _itemsSource; public virtual IEnumerable ItemsSource { get { return _itemsSource; } set { SetItemsSource(value); } } private IMvxTemplateSelector _itemTemplateSelector; [System.Obsolete("Используй FlatGroupTemplateSelector")] public virtual IMvxTemplateSelector ItemTemplateSelector { get { return _itemTemplateSelector; } set { if (ReferenceEquals(_itemTemplateSelector, value)) return; _itemTemplateSelector = value; if (_flatItems != null) NotifyDataSetChanged(); } } public ICommand ItemClick { get { return _itemClick; } set { if (ReferenceEquals(_itemClick, value)) { return; } if (_itemClick != null) { MvxTrace.Warning("Changing ItemClick may cause inconsistencies where some items still call the old command."); } _itemClick = value; } } public ICommand ItemLongClick { get { return _itemLongClick; } set { if (ReferenceEquals(_itemLongClick, value)) { return; } if (_itemLongClick != null) { MvxTrace.Warning("Changing ItemLongClick may cause inconsistencies where some items still call the old command."); } _itemLongClick = value; } } public int ItemTemplateId { get; set; } public override int ItemCount => _flatItems?.Count ?? 0; #endregion #endregion #region Constructor public ARFlatGroupAdapter(InnerItemsProviderDelegate innerItemsProvider, IARFlatGroupTemplateSelector flatGroupTemplateSelector, IMvxBindingContext bindingContext) : this(innerItemsProvider, (IMvxAndroidBindingContext)bindingContext) { _flatGroupTemplateSelector = flatGroupTemplateSelector; } public ARFlatGroupAdapter(InnerItemsProviderDelegate innerItemsProvider, IMvxBindingContext bindingContext, int sectionHeaderLayout = -1, int sectionFooterLayout = -1) : this(innerItemsProvider, (IMvxAndroidBindingContext)bindingContext) { _headerLayout = sectionHeaderLayout; _footerLayout = sectionFooterLayout; } protected ARFlatGroupAdapter(InnerItemsProviderDelegate innerItemsProvider, IMvxAndroidBindingContext bindingContext) { _bindingContext = bindingContext; _innerItemsProvider = innerItemsProvider; } public ARFlatGroupAdapter(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } #endregion #region Private private void SetInnerItems() { if (ItemsSource == null) { _flatItems = null; _headersPostions = null; _footerPostions = null; _headersViewTypes = null; _footerViewTypes = null; return; } _flatItems = new List<object>(); _headersPostions = new List<int>(); _footerPostions = new List<int>(); _footerViewTypes = new List<int>(); _headersViewTypes = new List<int>(); int currentPosition = 0; foreach (var item in ItemsSource) { var hasHeader = HasHeader?.Invoke(item) ?? false; var hasFooter = HasFooter?.Invoke(item) ?? false; if (hasHeader) { _flatItems.Add(item); _headersPostions.Add(currentPosition); currentPosition++; } if (_innerItemsProvider != null) { var innerItems = _innerItemsProvider(item); foreach (var innerItem in innerItems) _flatItems.Add(innerItem); currentPosition += innerItems.Count(); } else { _flatItems.Add(item); currentPosition++; } if (hasFooter) { _flatItems.Add(item); _footerPostions.Add(currentPosition); currentPosition++; } } } #endregion #region Protected protected virtual void SetItemsSource(IEnumerable value) { if (ReferenceEquals(_itemsSource, value) && !ReloadOnAllItemsSourceSets) { return; } _subscription?.Dispose(); _subscription = null; _itemsSource = value; SetInnerItems(); if (_itemsSource != null && !(_itemsSource is IList)) { MvxBindingTrace.Trace(MvxTraceLevel.Warning, "Binding to IEnumerable rather than IList - this can be inefficient, especially for large lists"); } var newObservable = _itemsSource as INotifyCollectionChanged; if (newObservable != null) _subscription = newObservable.WeakSubscribe(OnItemsSourceCollectionChanged); NotifyDataSetChanged(); } protected virtual void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { SetInnerItems(); if (Looper.MainLooper == Looper.MyLooper()) { NotifyDataSetChanged(e); } else { var h = new Handler(Looper.MainLooper); h.Post(() => NotifyDataSetChanged(e)); } } public virtual void NotifyDataSetChanged(NotifyCollectionChangedEventArgs e) { try { switch (e.Action) { case NotifyCollectionChangedAction.Add: NotifyItemRangeInserted(GetViewPosition(e.NewStartingIndex), e.NewItems.Count); break; case NotifyCollectionChangedAction.Move: for (int i = 0; i < e.NewItems.Count; i++) { var oldItem = e.OldItems[i]; var newItem = e.NewItems[i]; NotifyItemMoved(GetViewPosition(oldItem), GetViewPosition(newItem)); } break; case NotifyCollectionChangedAction.Replace: NotifyItemRangeChanged(GetViewPosition(e.NewStartingIndex), e.NewItems.Count); break; case NotifyCollectionChangedAction.Remove: NotifyItemRangeRemoved(GetViewPosition(e.OldStartingIndex), e.OldItems.Count); break; case NotifyCollectionChangedAction.Reset: NotifyDataSetChanged(); break; } } catch (Exception exception) { MvxTrace.Warning( "Exception masked during Adapter RealNotifyDataSetChanged {0}. Are you trying to update your collection from a background task? See http://goo.gl/0nW0L6", exception.BuildAllMessagesAndStackTrace()); } } protected virtual bool IsSectionHeaderPosition(int position) { return _headersPostions == null ? false : _headersPostions.Any(t => t == position); } protected virtual bool IsSectionFooterPosition(int position) { return _footerPostions == null ? false : _footerPostions.Any(t => t == position); } protected virtual bool IsSectionHeaderViewType(int viewType) { return (_headerLayout == viewType) || (_headersViewTypes?.Any(t => t == viewType) ?? false); } protected virtual bool IsSectionFooterViewType(int viewType) { return (_footerLayout == viewType) || (_footerViewTypes?.Any(t => t == viewType) ?? false); } protected virtual View InflateViewForHolder(ViewGroup parent, int viewType, IMvxAndroidBindingContext bindingContext) { int layoutId; if (FlatGroupTemplateSelector == null) layoutId = viewType == _headerLayout ? _headerLayout : ( viewType == _footerLayout ? _footerLayout : ItemTemplateSelector.GetItemLayoutId(viewType) ); else layoutId = FlatGroupTemplateSelector.GetItemLayoutId(viewType); return bindingContext.BindingInflate(layoutId, parent, false); } #endregion #region Public public virtual object GetItem(int position) { if (_flatItems != null && position >= 0 && position < _flatItems.Count) { return _flatItems[position]; } return null; } protected virtual int GetViewPosition(object item) { var itemsSourcePosition = _itemsSource.GetPosition(item); return GetViewPosition(itemsSourcePosition); } protected virtual int GetViewPosition(int itemsSourcePosition) { return itemsSourcePosition; } protected virtual int GetItemsSourcePosition(int viewPosition) { return viewPosition; } public override int GetItemViewType(int position) { var itemAtPosition = GetItem(position); if (FlatGroupTemplateSelector == null) { return IsSectionHeaderPosition(position) ? _headerLayout : ( IsSectionFooterPosition(position) ? _footerLayout : ItemTemplateSelector.GetItemViewType(itemAtPosition) ); } else { int viewType = 0; if (IsSectionHeaderPosition(position)) { viewType = FlatGroupTemplateSelector.GetHeaderViewType(itemAtPosition); _headersViewTypes.Add(viewType); } else if (IsSectionFooterPosition(position)) { viewType = FlatGroupTemplateSelector.GetFooterViewType(itemAtPosition); _footerViewTypes.Add(viewType); } else viewType = FlatGroupTemplateSelector.GetItemViewType(itemAtPosition); return viewType; } } public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { var dataContext = GetItem(position); if (holder is IMvxRecyclerViewHolder mvxHolder) mvxHolder.DataContext = dataContext; var sectionHeader = IsSectionHeaderPosition(position); var sectionFooter = IsSectionFooterPosition(position); if (sectionHeader && TuneSectionHeaderOnBind != null) { bool first = _headersPostions.First() == position; bool last = _headersPostions.Last() == position; TuneSectionHeaderOnBind(first, last, holder); } if (sectionFooter && TuneSectionFooterOnBind != null) { bool first = _footerPostions.First() == position; bool last = _footerPostions.Last() == position; TuneSectionFooterOnBind(first, last, holder); } if (!sectionHeader && !sectionFooter && TuneSectionItemOnBind != null) { bool first = (position == 0) || (_headersPostions?.Any(t => t == position - 1) ?? false) || (_footerPostions?.Any(t => t == position - 1) ?? false); bool last = (position == ItemCount - 1) || (_headersPostions?.Any(t => t == position + 1) ?? false) || (_footerPostions?.Any(t => t == position + 1) ?? false); TuneSectionItemOnBind(first, last, holder); } } public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { var itemBindingContext = new MvxAndroidBindingContext(parent.Context, _bindingContext.LayoutInflaterHolder); var vh = new MvxRecyclerViewHolder(InflateViewForHolder(parent, viewType, itemBindingContext), itemBindingContext); bool isHeader = IsSectionHeaderViewType(viewType); bool isFooter = IsSectionFooterViewType(viewType); if (isHeader || isFooter) { vh.Click = SectionClick; vh.LongClick = SectionLongClick; } else { vh.Click = ItemClick; vh.LongClick = ItemLongClick; } TuneViewHolderOnCreate?.Invoke(vh, viewType); return vh; } public void ReloadData() { SetInnerItems(); NotifyDataSetChanged(); } #region IMvxRecyclerViewHolder public override void OnViewAttachedToWindow(Java.Lang.Object holder) { base.OnViewAttachedToWindow(holder); var viewHolder = (IMvxRecyclerViewHolder)holder; viewHolder.OnAttachedToWindow(); } public override void OnViewDetachedFromWindow(Java.Lang.Object holder) { base.OnViewDetachedFromWindow(holder); var viewHolder = (IMvxRecyclerViewHolder)holder; viewHolder.OnDetachedFromWindow(); } public override void OnViewRecycled(Java.Lang.Object holder) { base.OnViewRecycled(holder); var viewHolder = (IMvxRecyclerViewHolder)holder; viewHolder.OnViewRecycled(); } #endregion #endregion } }
31.913478
175
0.550782
[ "Apache-2.0" ]
cryptobuks/AppRopio.Mobile
src/app-ropio/AppRopio.Base/Droid/Adapters/ARFlatGroupAdapter.cs
19,191
C#
using System; using System.Globalization; namespace Gamma.Binding.Converters { public class IdToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { int id = (int)value; if(id > 0) return id.ToString(); else return "не определён"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if(int.TryParse(value.ToString(), out int result)) return result; return null; } } }
21.52
97
0.713755
[ "Apache-2.0" ]
Art8m/QSProjects
Binding/Gamma.Binding/Binding/Converters/IdToStringConverter.cs
551
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.Web.LibraryManager.Contracts; using Microsoft.Web.LibraryManager.LibraryNaming; using Microsoft.WebTools.Languages.Json.Parser.Nodes; using Microsoft.WebTools.Languages.Shared.Editor.SuggestedActions; using Microsoft.WebTools.Languages.Shared.Parser.Nodes; using Microsoft.WebTools.Languages.Shared.Utility; namespace Microsoft.Web.LibraryManager.Vsix { internal class UninstallSuggestedAction : SuggestedActionBase { private static readonly Guid Guid = new Guid("2975f71b-809d-4ed6-a170-6bbc04058424"); private const int MaxLength = 40; private readonly SuggestedActionProvider _provider; private readonly ILibraryCommandService _libraryCommandService; public UninstallSuggestedAction(SuggestedActionProvider provider, ILibraryCommandService libraryCommandService) : base(provider.TextBuffer, provider.TextView, GetDisplayText(provider), Guid) { _libraryCommandService = libraryCommandService; _provider = provider; IconMoniker = KnownMonikers.Cancel; } private static string GetDisplayText(SuggestedActionProvider provider) { ILibraryInstallationState state = provider.InstallationState; string cleanId = LibraryIdToNameAndVersionConverter.Instance.GetLibraryId(state.Name, state.Version, state.ProviderId); if (cleanId.Length > MaxLength + 10) { cleanId = $"...{cleanId.Substring(cleanId.Length - MaxLength)}"; } return string.Format(Resources.Text.UninstallLibrary, cleanId); } public override async void Invoke(CancellationToken cancellationToken) { try { Telemetry.TrackUserTask("Invoke-UninstallFromSuggestedAction"); var state = _provider.InstallationState; await _libraryCommandService.UninstallAsync(_provider.ConfigFilePath, state.Name, state.Version, state.ProviderId, cancellationToken) .ConfigureAwait(false); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); using (ITextEdit edit = TextBuffer.CreateEdit()) { var arrayElement = _provider.LibraryObject.Parent as ArrayElementNode; var prev = GetPreviousSibling(arrayElement) as ArrayElementNode; var next = GetNextSibling(arrayElement) as ArrayElementNode; int start = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.Start).Start; int end = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.End).EndIncludingLineBreak; if (next == null && prev?.Comma != null) { start = prev.Comma.Start; end = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.End).End; } edit.Delete(Span.FromBounds(start, end)); edit.Apply(); } } catch (Exception ex) { Logger.LogEvent(ex.ToString(), LibraryManager.Contracts.LogLevel.Error); Telemetry.TrackException("UninstallFromSuggestedActionFailed", ex); } } private Node GetPreviousSibling(ArrayElementNode arrayElementNode) { ComplexNode parent = arrayElementNode.Parent as ComplexNode; SortedNodeList<Node> children = JsonHelpers.GetChildren(parent); return parent != null ? GetPreviousChild(arrayElementNode, children) : null; } private Node GetNextSibling(ArrayElementNode arrayElementNode) { ComplexNode parent = arrayElementNode.Parent as ComplexNode; SortedNodeList<Node> children = JsonHelpers.GetChildren(parent); return parent != null ? GetNextChild(arrayElementNode, children) : null; } private Node GetPreviousChild(Node child, SortedNodeList<Node> children) { int index = (child != null) ? children.IndexOf(child) : -1; if (index > 0) { return children[index - 1]; } return null; } private Node GetNextChild(Node child, SortedNodeList<Node> children) { int index = (child != null) ? children.IndexOf(child) : -1; if (index != -1 && index + 1 < children.Count) { return children[index + 1]; } return null; } } }
40.096774
149
0.63757
[ "Apache-2.0" ]
tlmii/LibraryManager
src/LibraryManager.Vsix/Json/SuggestedActions/UninstallSuggestedActions.cs
4,974
C#
using TMPro; using UnityEngine; using UnityEngine.SceneManagement; public class Kitsulope : ObjectType { /// Just adding something to make sure my new repo works. #region LivingRoom public GameObject fridge; public GameObject window; public GameObject shelf; public GameObject aloe; public GameObject beanBag; public GameObject exitButton; public bool shakePlant; public GameObject blinkingFaceObj; public float blinkingCounter; [SerializeField] public float maxBlinkingCounter = 3f; public GameObject cheat; #endregion #region Outside public GameObject bike; public GameObject rusakko; public GameObject reset; public GameObject diileri; #endregion #region SittingInside public GameObject phone; public GameObject mug; public Sprite emptyMug; public GameObject banana; public GameObject noBananaOnTable; public SpriteRenderer lightRenderer; public SpriteRenderer mugRenderer; public Sprite on; public Sprite off; public float mugFullFor = 5; public SpriteRenderer tableRenderer; public Sprite noBanana; public Sprite thereIsBanana; #endregion public GameObject door; #region MovementVariables [SerializeField] private float xMin = -0.9F; [SerializeField] private float xMax = 0.9F; [SerializeField] float speed = 3F; int direction = 1; float counter = 0; #endregion #region Bubble public float exitCounter = 2.0f; public Sprite exitBubble; public Sprite windowBubble; public Sprite downBubble; public Sprite cornerBubble; public Sprite shelfBubble; DialogueManager dialogueManager; public GameObject bubbleObject; public GameObject bubbleTextObject; public Color color; public TextMeshProUGUI bubbleText; public SpriteRenderer bubbleSpriteRenderer; [SerializeField] public float maxBubbleCounter = 10f; public float bubbleCounter = 0f; #endregion #region Animation public Animator animator; [SerializeField] public float pettingAnimationLength = 2.5f; public float maxPettingAnimationLength = 2.5f; [SerializeField] public float feedingAnimationLength = 2.5f; public float maxFeedingAnimationLength = 2.5f; [SerializeField] public float chillingAnimationLength = 2.5f; public float maxChillingAnimationLength = 2.5f; [SerializeField] public float yawningAnimationLength = 2.5f; public float maxYawningAnimationLength = 2.5f; public bool isChilling; public bool isPetNoticingYou; public bool isYawning; public bool isRefusing; public float rand; public SpriteRenderer fridgeRenderer; public Sprite fridgeClosed; public Sprite fridgeOpen; #endregion #region Input public Vector3 newPos; bool _touchBegan, _touchHold, _touchEnded; #endregion public SpriteRenderer kitsuRenderer; public Sprite fourteen; void Start() { // Needs to be set as something at the start to avoid errors. dialogueManager = GetComponent<DialogueManager>(); maxPettingAnimationLength = pettingAnimationLength; maxFeedingAnimationLength = feedingAnimationLength; maxChillingAnimationLength = chillingAnimationLength; color = bubbleSpriteRenderer.color; bubbleText = bubbleTextObject.GetComponent<TextMeshProUGUI>(); // This script is in many different scenes with different objects so this is used to prevent annoying and unnecessary error messages. try { } catch (UnassignedReferenceException e) { return; } } int frame = 0; float pancakingCounter = 0; // TODO /*** * Tap pet --> Answer prompt with yes & no (timesRefusedToLetGo) * Let go --> timesRefusedToLetGo doesn't increase, petAway does --> averageAttachment leads to Good or Ok Ending * Refuse --> timesRefusedToLetGo increases, petAway doesn't * Tap pet --> Answer prompt with yes & no (timesRefusedToLetGo) * Let go --> timesRefusedToLetGo doesn't increase, petAway does --> averageAttachment leads to Ok or Bad Ending * Refuse --> petAway increases (pet runs away) --> automatic Bad Eding ***/ void Update() { BubbleCounter(); if (SceneManager.GetActiveScene().name == "Game") { ShakePlant(); } else if (SceneManager.GetActiveScene().name == "Sitting") { // Pet can be pancaked in sitting scene. //Debug.Log(chillingAnimationLength); if (chillingAnimationLength < 0) { SaveSerial.SAVE.isPetting = false; animator.SetBool("IsChilling", false); animator.SetBool("IsPetting", false); chillingAnimationLength = maxChillingAnimationLength; } if (!(_touchBegan || _touchHold) && SaveSerial.SAVE.isPetting == true) { Debug.Log(kitsuRenderer.sprite.name); if (kitsuRenderer.sprite.name != "goingpancake_14" && kitsuRenderer.sprite.name != "goingpancake_15" && (kitsuRenderer.sprite.name == "goingpancake_4" || kitsuRenderer.sprite.name == "goingpancake_3" || kitsuRenderer.sprite.name == "goingpancake_2" || kitsuRenderer.sprite.name == "goingpancake_1"|| kitsuRenderer.sprite.name == "goingpancake_0")) { Debug.LogWarning("4 OR LESS"); SaveSerial.SAVE.isPetting = false; } // Make sure it's the last frame! else if(kitsuRenderer.sprite.name == "goingpancake_17") { SaveSerial.SAVE.isPetting = false; } pettingAnimationLength = 0; chillingAnimationLength = 0; } else { chillingAnimationLength = maxChillingAnimationLength; } mugFullFor = mugFullFor - Time.deltaTime; if (mugFullFor <= 0) { mugRenderer.sprite = emptyMug; } if (SaveSerial.SAVE.banana == 0) { tableRenderer.sprite = noBanana; } else if (SaveSerial.SAVE.banana == 1) { tableRenderer.sprite = thereIsBanana; } if (transform.position.x == -0.03) { newPos.y = 0.05f; transform.Translate(newPos); } else if (transform.position.y > -0.03) { newPos.y = -0.03f; transform.Translate(newPos); } #region sitting scene animation if (!SaveSerial.SAVE.isFeeding || !SaveSerial.SAVE.isPetting || !SaveSerial.SAVE.isRefusing) { rand = Random.Range(0.0f, 100.0f); if (rand > 99.6f) { //isChilling = true; if (rand > 99.9) { //isYawning = true; chillingAnimationLength = maxYawningAnimationLength; } } } else { isChilling = false; } if (SaveSerial.SAVE.isPetting) { Debug.Log(kitsuRenderer.sprite.name); pancakingCounter += Time.deltaTime; Debug.Log(pancakingCounter); if (pancakingCounter > 1f) { Debug.Log("pancakingCounter: " + pancakingCounter + " frame: " + frame); animator.Play("Pancake", 0, frame/15); animator.Update(1f); frame = frame + 1; } else { pancakingCounter = 0; } } if (isYawning) { chillingAnimationLength -= Time.deltaTime; if (chillingAnimationLength <= 0) { isChilling = false; isYawning = false; chillingAnimationLength = maxChillingAnimationLength; } } // TODO: Break this into a few categories. // Check if necessary items are owned. If pet is close enough to an item, choose animation for it. // Chewing the stick needs to be slightly shorter and jumping in the box needs to be a lot shorter. if (isChilling) { chillingAnimationLength -= Time.deltaTime; if (chillingAnimationLength <= 0) { isChilling = false; chillingAnimationLength = maxChillingAnimationLength; } } if (SaveSerial.SAVE.isFeeding) { feedingAnimationLength -= Time.deltaTime; if (feedingAnimationLength <= 0) { SaveSerial.SAVE.isFeeding = false; feedingAnimationLength = maxFeedingAnimationLength; } } // TODO: Make this shorter. if (SaveSerial.SAVE.isRefusing) { yawningAnimationLength -= Time.deltaTime; if (yawningAnimationLength <= 0) { SaveSerial.SAVE.isRefusing = false; animator.SetBool("IsRefusing", false); yawningAnimationLength = maxYawningAnimationLength; } /*pettingAnimationLength -= Time.deltaTime; chillingAnimationLength = pettingAnimationLength; if (chillingAnimationLength <= 0) { SaveSerial.SAVE.isRefusing = false; pettingAnimationLength = maxPettingAnimationLength; chillingAnimationLength = maxChillingAnimationLength; }*/ } animator.SetInteger("Satisfaction", (int)SaveLoad.SaveData[(int)SaveLoad.Line.SatisfiedLevel]); animator.SetBool("IsPetting", SaveSerial.SAVE.isPetting); animator.SetBool("IsFeeding", SaveSerial.SAVE.isFeeding); animator.SetInteger("Direction", direction); //Debug.Log(isChilling); //animator.SetBool("IsChilling", isChilling); animator.SetBool("IsYawning", isYawning); animator.SetBool("IsRefusing", SaveSerial.SAVE.isRefusing); animator.SetFloat("Rand", rand); #endregion } // Yeah this code isn't optimal but it works so ehh. if (SceneManager.GetActiveScene().name != "Sitting") { #region animation logic if (!SaveSerial.SAVE.isFeeding || !SaveSerial.SAVE.isPetting || !SaveSerial.SAVE.isRefusing) { rand = Random.Range(0.0f, 100.0f); if (rand > 99.6f) { isChilling = true; if (rand > 99.9) { isYawning = true; chillingAnimationLength = maxYawningAnimationLength; } } } else { isChilling = false; } if (SaveSerial.SAVE.isPetting) { pettingAnimationLength -= Time.deltaTime; chillingAnimationLength = pettingAnimationLength; if (chillingAnimationLength <= 0) { SaveSerial.SAVE.isPetting = false; pettingAnimationLength = maxPettingAnimationLength; chillingAnimationLength = maxChillingAnimationLength; } } if (isYawning) { chillingAnimationLength -= Time.deltaTime; if (chillingAnimationLength <= 0) { isChilling = false; isYawning = false; chillingAnimationLength = maxChillingAnimationLength; } } else if (isChilling) { chillingAnimationLength -= Time.deltaTime; if (chillingAnimationLength <= 0) { isChilling = false; chillingAnimationLength = maxChillingAnimationLength; } } if (SaveSerial.SAVE.isFeeding) { feedingAnimationLength -= Time.deltaTime; if (feedingAnimationLength <= 0) { SaveSerial.SAVE.isFeeding = false; feedingAnimationLength = maxFeedingAnimationLength; } } //Debug.Log(yawningAnimationLength); if (SaveSerial.SAVE.isRefusing) { yawningAnimationLength -= Time.deltaTime; if (yawningAnimationLength <= 0) { SaveSerial.SAVE.isRefusing = false; animator.SetBool("IsRefusing", false); yawningAnimationLength = maxYawningAnimationLength; } } animator.SetInteger("Satisfaction", (int)SaveLoad.SaveData[(int)SaveLoad.Line.SatisfiedLevel]); animator.SetBool("IsPetting", SaveSerial.SAVE.isPetting); animator.SetBool("IsFeeding", SaveSerial.SAVE.isFeeding); animator.SetInteger("Direction", direction); animator.SetBool("IsChilling", isChilling); animator.SetBool("IsYawning", isYawning); animator.SetBool("IsRefusing", SaveSerial.SAVE.isRefusing); animator.SetFloat("Rand", rand); #endregion } #region input // && operations happen before || operations // in math terms: // && is * (multiply), || is + (add) _touchBegan = Input.GetMouseButtonDown(0) || Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began; _touchHold = Input.GetMouseButton(0) || Input.touchCount > 0 && (Input.GetTouch(0).phase == TouchPhase.Stationary || Input.GetTouch(0).phase == TouchPhase.Moved); _touchEnded = Input.GetMouseButtonUp(0) || Input.touchCount > 0 && (Input.GetTouch(0).phase == TouchPhase.Canceled || Input.GetTouch(0).phase == TouchPhase.Ended); if (_touchBegan || _touchHold || _touchEnded) { if (Input.touchCount > 0) DoTouch(Input.GetTouch(0).position); else DoTouch(Input.mousePosition); } #endregion #region movement Vector3 position = transform.position; if (isChilling || SaveSerial.SAVE.isPetting || SaveSerial.SAVE.isFeeding || SaveSerial.SAVE.isRefusing || SaveLoad.SaveData[(int)SaveLoad.Line.SatisfiedLevel] < 2) { direction = 0; } else if (direction == 0 || (direction == -1 && position.x < xMin)) { direction = 1; } else if (direction == 0 || (direction == 1 && position.x > xMax)) { direction = -1; } Vector3 movement = Vector3.right * direction * Time.deltaTime; if (counter < 0.1) { counter += Time.deltaTime; } else { transform.Translate(movement * speed); counter = 0; } #endregion } void BubbleCounter() { if (SceneManager.GetActiveScene().name == "Game" || SceneManager.GetActiveScene().name == "Field" || SceneManager.GetActiveScene().name == "Sitting") { if (blinkingFaceObj.activeInHierarchy) { blinkingCounter += Time.deltaTime; } if (blinkingCounter >= maxBlinkingCounter) { blinkingFaceObj.SetActive(false); blinkingCounter = 0; } } if (bubbleObject.activeInHierarchy) { bubbleCounter += Time.deltaTime; } if (bubbleCounter >= maxBubbleCounter) { bubbleCounter = maxBubbleCounter; color.a = color.a - 0.01f; if (color.a <= 0) { color.a = 0; bubbleCounter = 0; bubbleObject.SetActive(false); bubbleTextObject.SetActive(false); fridgeRenderer.sprite = fridgeClosed; //telepathy.SetActive(false); } } else { color.a = 1f; } bubbleSpriteRenderer.color = new Color(bubbleSpriteRenderer.color.r, bubbleSpriteRenderer.color.g, bubbleSpriteRenderer.color.b, color.a); bubbleText.color = new Color(bubbleText.color.r, bubbleText.color.g, bubbleText.color.b, color.a); } #region InputHandling void DoTouch(Vector2 point) { RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(point), Camera.main.transform.forward); if (!hit) return; Object hitType = hit.transform.GetComponent<ObjectType>().type; //Debug.Log(hitType); switch (hitType) { case Object.Kitsulope: #region Kitsulope if (SceneManager.GetActiveScene().name == "Sitting") { if (_touchBegan || _touchHold) { animator.SetBool("IsPetting", true); SaveSerial.SAVE.Pet(); } else if (_touchEnded) { //animator.SetBool("IsPetting", false); pettingAnimationLength = 0; chillingAnimationLength = 0; } } else { if (_touchBegan) { Debug.Log("You tapped."); isPetNoticingYou = true; animator.SetBool("IsPetting", true); } if (_touchHold && isPetNoticingYou == true) { Debug.Log("Touch phase is Began, Moved or Stationary."); animator.SetBool("IsPetting", true); } if (_touchEnded) { SaveSerial.SAVE.Pet(); if (SaveSerial.SAVE.satisfiedLvlToSave == 4 & SaveSerial.SAVE.frequencyCheck > 0 & SaveSerial.SAVE.frequencyCheck < 3) { blinkingFaceObj.SetActive(true); SaveSerial.SAVE.frequencyCheck = 0; } else if (SaveSerial.SAVE.satisfiedLvlToSave == 4) { SaveSerial.SAVE.frequencyCheck = 0; } } } #endregion break; case Object.AloeVera: if (_touchBegan || _touchHold) { shakePlant = true; } break; case Object.Fridge: #region fridgeBubble if (_touchBegan) { if (Tapped(downBubble, fridge.GetComponent<Dialogue>())) { fridgeRenderer.sprite = fridgeOpen; SaveSerial.SAVE.Feed(); if (SaveSerial.SAVE.satisfiedLvlToSave == 4 & SaveSerial.SAVE.frequencyCheck > 0 & SaveSerial.SAVE.frequencyCheck < 3) { blinkingFaceObj.SetActive(true); SaveSerial.SAVE.frequencyCheck = 0; } else if (SaveSerial.SAVE.satisfiedLvlToSave == 4) { SaveSerial.SAVE.frequencyCheck = 0; } } } #endregion break; case Object.Shelf: #region shelf if (_touchBegan) { Debug.LogWarning("SENTENCES: " + dialogueManager.sentences.Count); if (Tapped(shelfBubble, shelf.GetComponent<Dialogue>())) { if (dialogueManager.sentences.Count == 0) { SceneManager.LoadScene("ReadingCorner"); } } } #endregion break; case Object.BeanBag: #region beanBagBubble if (_touchBegan) { if (Tapped(cornerBubble, beanBag.GetComponent<Dialogue>())) { SaveSerial.SAVE.isPetting = false; animator.SetBool("IsChilling", false); animator.SetBool("IsPetting", false); SaveSerial.SAVE.isFeeding = false; SaveSerial.SAVE.isRefusing = false; animator.SetBool("IsFeeding", false); animator.SetBool("IsRefusing", false); SceneManager.LoadScene("Sitting"); } } #endregion break; case Object.Window: #region toTheField? if (_touchBegan) { if (Tapped(windowBubble, window.GetComponent<Dialogue>())) { SaveSerial.SAVE.isPetting = false; animator.SetBool("IsChilling", false); animator.SetBool("IsPetting", false); SaveSerial.SAVE.isFeeding = false; SaveSerial.SAVE.isRefusing = false; animator.SetBool("IsFeeding", false); animator.SetBool("IsRefusing", false); SceneManager.LoadScene("Field"); } } #endregion break; case Object.WildRabbit: #region raceRabbit if (_touchBegan || _touchHold) { if (TapAndHold(downBubble, rusakko.GetComponent<Dialogue>())) { SceneManager.LoadScene("OutsideGame"); } } #endregion break; case Object.SellerRabbit: #region seller if (_touchBegan) { if (Tapped(shelfBubble, diileri.GetComponent<Dialogue>())) { SceneManager.LoadScene("Store"); } } #endregion break; case Object.Reset: #region resetRusakko if (_touchBegan || _touchHold) { if (TapAndHold(windowBubble, reset.GetComponent<Dialogue>())) { SaveSerial.SAVE.ResetSave(); } } #endregion break; case Object.Bike: #region backInside? if (_touchBegan) { if (Tapped(cornerBubble, bike.GetComponent<Dialogue>())) { SaveSerial.SAVE.isPetting = false; animator.SetBool("IsChilling", false); animator.SetBool("IsPetting", false); SaveSerial.SAVE.isFeeding = false; SaveSerial.SAVE.isRefusing = false; animator.SetBool("IsFeeding", false); animator.SetBool("IsRefusing", false); SceneManager.LoadScene("Game"); } } #endregion break; case Object.Instructions: #region instructions if (_touchBegan) { if (SceneManager.GetActiveScene().name == "Game") { SceneManager.LoadScene("Instructions"); } else if (SceneManager.GetActiveScene().name == "Field") { SceneManager.LoadScene("GameInstructions"); } else if (SceneManager.GetActiveScene().name == "Sitting") { SceneManager.LoadScene("BeanBagInstructions"); } else if (SceneManager.GetActiveScene().name == "Door") { Debug.LogWarning("NOT IMPLEMENTED"); } } break; #endregion case Object.Phone: #region phone if (_touchBegan || _touchHold) { if (TapAndHold(downBubble, phone.GetComponent<Dialogue>())) { SceneManager.LoadScene("Door"); SaveSerial.SAVE.petAway = 1; SaveSerial.SAVE.SaveGame(); } } #endregion break; case Object.Lights: #region Lights Debug.Log(lightRenderer.sprite); if (_touchBegan && lightRenderer.sprite == on) { Debug.Log("OFF"); lightRenderer.sprite = off; } else if (_touchBegan) { Debug.Log("ON"); lightRenderer.sprite = on; } #endregion break; case Object.Banana: if (_touchBegan) { if (SaveSerial.SAVE.banana == 1) { if (Tapped(shelfBubble, banana.GetComponent<Dialogue>())) { if (SaveSerial.SAVE.hungerLvlToSave < SaveSerial.SAVE.maxHungerLvl) { SaveSerial.SAVE.banana = 0; } SaveSerial.SAVE.EatBanana(); if (SaveSerial.SAVE.satisfiedLvlToSave == 4 & SaveSerial.SAVE.frequencyCheck > 0 & SaveSerial.SAVE.frequencyCheck < 3) { blinkingFaceObj.SetActive(true); } else if (SaveSerial.SAVE.satisfiedLvlToSave == 4) { SaveSerial.SAVE.frequencyCheck = 0; } } } else { // Prompt a comment about buying a new banana. if (Tapped(shelfBubble, noBananaOnTable.GetComponent<Dialogue>())) { } } } break; case Object.Mug: #region getUp if (_touchBegan) { if (Tapped(cornerBubble, mug.GetComponent<Dialogue>())) { SaveSerial.SAVE.isPetting = false; animator.SetBool("IsChilling", false); animator.SetBool("IsPetting", false); SaveSerial.SAVE.isFeeding = false; SaveSerial.SAVE.isRefusing = false; animator.SetBool("IsFeeding", false); animator.SetBool("IsRefusing", false); SceneManager.LoadScene("Game"); } } #endregion break; case Object.Door: #region phone if (_touchBegan) { if (Tapped(downBubble, door.GetComponent<Dialogue>())) { SaveSerial.SAVE.petAway = 0; SaveSerial.SAVE.SaveGame(); SceneManager.LoadScene("Game"); } } #endregion break; case Object.UseForSomethingLater: if (_touchBegan) { if (Tapped(downBubble, cheat.GetComponent<Dialogue>())) { SceneManager.LoadScene("FullMoon"); } } break; case Object.ExitButton: #region ExitButton if (_touchBegan || _touchHold) { if (TapAndHold(exitBubble, exitButton.GetComponent<Dialogue>())) { SaveSerial.SAVE.Exit(); } } #endregion break; default: Debug.LogWarning("Blep"); break; } } float shakeFor = 1f; // Do a full flip. void ShakePlant() { if (shakePlant == true && shakeFor >= 0) { shakeFor -= Time.deltaTime; aloe.transform.Rotate(0.0f, 0.0f, -20.0f, Space.World); } else { shakeFor = 1f; shakePlant = false; aloe.transform.SetPositionAndRotation(new Vector3(-0.88f, 0.56f, 0), Quaternion.Euler(0, 0, 0)); } } bool Tapped(Sprite bubbleSprite, Dialogue dialogue) { // check bubble if (bubbleSpriteRenderer.sprite != bubbleSprite) { // set correct bubble bubbleSpriteRenderer.sprite = bubbleSprite; // set bubble object off for next if-else bubbleObject.SetActive(false); } // bubble on if (bubbleObject.activeInHierarchy) { // tapped in time if (bubbleSpriteRenderer.color.a == 1f) { dialogueManager.DisplayNextSentence(); return true; } // tapped too late else { color.a = 1f; bubbleCounter = 0; } } // bubble off else { bubbleCounter = 0; bubbleObject.SetActive(true); bubbleTextObject.SetActive(true); dialogueManager.StartDialogue(dialogue); color.a = 1; } return false; } bool TapAndHold(Sprite bubbleSprite, Dialogue dialogue) { // check bubble if (bubbleSpriteRenderer.sprite != bubbleSprite) { // set correct bubble bubbleSpriteRenderer.sprite = bubbleSprite; // set bubble object off for next if-else bubbleObject.SetActive(false); } // bubble on if (bubbleObject.activeInHierarchy) { // alpha under 1 if (bubbleSpriteRenderer.color.a < 1f) { color.a = 1f; bubbleCounter = 0; } // counter done else if (exitCounter < 0) { return true; } // holding else if (_touchHold) { exitCounter -= Time.deltaTime; bubbleCounter = 0; } } // bubble off else { bubbleCounter = 0; exitCounter = 2.0f; bubbleObject.SetActive(true); bubbleTextObject.SetActive(true); dialogueManager.StartDialogue(dialogue); color.a = 1; } return false; } #endregion }
34.572193
169
0.486991
[ "MIT" ]
FromCaffeineToCode/KitsuCareNewestRepo
Assets/Code/Kitsulope.cs
32,327
C#
using System; using System.Xml.Serialization; using Top.Api.Domain; namespace Top.Api.Response { /// <summary> /// RefundRefuseResponse. /// </summary> public class RefundRefuseResponse : TopResponse { /// <summary> /// 拒绝退款操作是否成功 /// </summary> [XmlElement("is_success")] public bool IsSuccess { get; set; } /// <summary> /// 拒绝退款成功后,会返回Refund数据结构中的refund_id, status, modified字段 /// </summary> [XmlElement("refund")] public Refund Refund { get; set; } } }
22.52
64
0.575488
[ "MIT" ]
objectyan/MyTools
OY.Solution/OY.TopSdk/Response/RefundRefuseResponse.cs
621
C#
using System.Linq; using System.Windows; using System.Windows.Documents; using System.Windows.Input; namespace HindiTransliterator { public partial class MainWindow : Window { bool IsSpecialCharCombinationsEnabled = true; bool IsKeyboardSoundEnglish = false; private void rtb_PreviewTextInput(object sender, TextCompositionEventArgs e) { if (e.Text.Length == 0) return; string s = e.Text; #region KBPronounciation if (IsKeyboardSoundEnglish == true) { switch (s) { case "d": { s = "D"; break; } case "D": { s = "d"; break; } case "t": { s = "T"; break; } case "T": { s = "t"; break; } } } #endregion char PC = this[-1], PPC = this[-2], PPPC = this[-3], PPPPC = this[-4]; #region Special char combinations if (PPPPC == '\u006E' && PPPC == '\u007E' && PPC == '\u0063' && PC == '\u007E' && s == "h") //d + bh =d+b+h { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(4); InsertChar('\u00F6'); InsertChar('\u007E'); } else { RemoveChar(2); InsertChar('\u00D2'); InsertChar('\u007E'); } } else if (PPC == '\u0063' && PC == '\u007E' && s == "h") //b+h { RemoveChar(2); InsertChar('\u00D2'); InsertChar('\u007E'); } else if (PPPC == '\u0043' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half b + danda +h { RemoveChar(3); InsertChar('\u00D2'); InsertChar('\u007E'); } else if (PPC == '\u0043' && PC == '\u007E' && s == "h") //half b +h { RemoveChar(2); InsertChar('\u00D2'); InsertChar('\u007E'); } else if (PPC == '\u006A' && PC == '\u007E' && s == "h") //r+h (No half r) { RemoveChar(2); InsertChar('\u005F'); InsertChar('\u007E'); } else if (PPC == '\u0072' && PC == '\u007E' && s == "h") //t+h { RemoveChar(2); InsertChar('\u0046'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPPC == '\u0052' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half t + danda +h { RemoveChar(3); InsertChar('\u0046'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPC == '\u0052' && PC == '\u007E' && s == "h") //half t +h { RemoveChar(2); InsertChar('\u0046'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPPPC == '\u0042' && PPPC == '\u007E' && PPC == '\u0056' && PC == '\u007E' && s == "h") //(T+h)+Continuation + (T) +h { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(4); InsertChar('\u00F0'); InsertChar('\u007E'); } else { RemoveChar(2); InsertChar('\u0042'); InsertChar('\u007E'); } } else if (PPC == '\u0056' && PC == '\u007E' && s == "h") //T+h (No half T) { RemoveChar(2); InsertChar('\u0042'); InsertChar('\u007E'); } else if (PPC == '\u0072' && PC == '\u007E' && s == "t") //t+t { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(2); InsertChar('\u00D9'); InsertChar('\u006B'); InsertChar('\u007E'); } else { InsertCharByInput('\u0072'); } } else if (PPPC == '\u0052' && PPC == '\u006B' && PC == '\u007E' && s == "t") //half t + danda +t { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(3); InsertChar('\u00D9'); InsertChar('\u006B'); InsertChar('\u007E'); } else { InsertCharByInput('\u0072'); } } else if (PPC == '\u0052' && PC == '\u007E' && s == "t") //half t +t { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(2); InsertChar('\u00D9'); InsertChar('\u006B'); InsertChar('\u007E'); } else { InsertCharByInput('\u0072'); } } else if (PPC == '\u0056' && PC == '\u007E' && s == "T") //T+T (No half T) { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(2); InsertChar('\u00CD'); InsertChar('\u007E'); } else { InsertCharByInput('\u0056'); } } else if (PPC == '\u00CD' && PC == '\u007E' && s == "h") //(T+T)+h (No half T) { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(2); InsertChar('\u00CE'); InsertChar('\u007E'); } else { InsertCharByInput('\u0067'); } } else if (PPPPC == '\u0042' && PPPC == '\u007E' && PPC == '\u0056' && PC == '\u007E' && s == "h") //(T+h)+Continuation + (T) +h { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(4); InsertChar('\u00F0'); InsertChar('\u007E'); } else { RemoveChar(2); InsertChar('\u0042'); InsertChar('\u007E'); } } else if (PPPC == '\u0049' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half p + danda +h { RemoveChar(3); InsertChar('\u0051'); InsertChar('\u007E'); } else if (PPC == '\u0049' && PC == '\u007E' && s == "h") //half p +h { RemoveChar(2); InsertChar('\u0051'); InsertChar('\u007E'); } else if (PPC == '\u006C' && PC == '\u007E' && s == "h") //s+h { RemoveChar(2); InsertChar('\u0027'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPPC == '\u004C' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half s + danda +h { RemoveChar(3); InsertChar('\u0027'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPC == '\u004C' && PC == '\u007E' && s == "h") //half s +h { RemoveChar(2); InsertChar('\u0027'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPC == '\u00CF' && PC == '\u007E' && s == "h") //D + Dh =(D+D)+h (This comb requires a SpecialChar as PPC) { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(2); InsertChar('\u00D4'); InsertChar('\u007E'); } else { RemoveChar(2); InsertChar('\u00D4'); InsertChar('\u007E'); } } else if (PPC == '\u004D' && PC == '\u007E' && s == "D") //D+D { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(2); InsertChar('\u00CF'); InsertChar('\u007E'); } else { InsertChar('\u004D'); InsertChar('\u007E'); } } else if (PPC == '\u00CC' && PC == '\u007E' && s == "h") //dd +h { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(2); InsertChar('\u0029'); InsertChar('\u007E'); } else { InsertCharByInput('\u0067'); } } else if (PPC == '\u006E' && PC == '\u007E' && s == "d") //d+d (No half d) { if (IsSpecialCharCombinationsEnabled == true) { RemoveChar(2); InsertChar('\u00CC'); InsertChar('\u007E'); } else { InsertCharByInput('\u006E'); } } else if (PPC == '\u006E' && PC == '\u007E' && s == "h") //d+h (No half d) { RemoveChar(2); InsertChar('\u002F'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPC == '\u004D' && PC == '\u007E' && s == "h") //D+h (No half D) { RemoveChar(2); InsertChar('\u003C'); InsertChar('\u007E'); } else if (PPC == '\u0078' && PC == '\u007E' && s == "h") //g+h { RemoveChar(2); InsertChar('\u00C4'); InsertChar('\u007E'); } else if (PPPC == '\u0058' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half g + danda +h { RemoveChar(3); InsertChar('\u00C4'); InsertChar('\u007E'); } else if (PPC == '\u0058' && PC == '\u007E' && s == "h") //half g +h { RemoveChar(2); InsertChar('\u00C4'); InsertChar('\u007E'); } else if (PPC == '\u0074' && PC == '\u007E' && s == "h") //j+h { RemoveChar(2); InsertChar('\u003E'); InsertChar('\u007E'); } else if (PPPC == '\u0054' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half j + danda +h { RemoveChar(3); InsertChar('\u003E'); InsertChar('\u007E'); } else if (PPC == '\u0054' && PC == '\u007E' && s == "h") //half j +h { RemoveChar(2); InsertChar('\u003E'); InsertChar('\u007E'); } else if (PPC == '\u0064' && PC == '\u007E' && s == "h") //k+h { RemoveChar(2); InsertChar('\u005B'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPPC == '\u0044' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half k + danda +h { RemoveChar(3); InsertChar('\u005B'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPC == '\u0044' && PC == '\u007E' && s == "h") //half k +h { RemoveChar(2); InsertChar('\u005B'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPC == '\u0070' && PC == '\u007E' && s == "h") //c+h { RemoveChar(2); InsertChar('\u004E'); InsertChar('\u007E'); } else if (PPPC == '\u0050' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half c + danda +h { RemoveChar(3); InsertChar('\u004E'); InsertChar('\u007E'); } else if (PPC == '\u0050' && PC == '\u007E' && s == "h") //half c +h { RemoveChar(2); InsertChar('\u004E'); InsertChar('\u007E'); } else if (PPC == '\u0075' && PC == '\u007E' && s == "h") //n+h { RemoveChar(2); InsertChar('\u002E'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPPC == '\u0055' && PPC == '\u006B' && PC == '\u007E' && s == "h") //half n + danda +h { RemoveChar(3); InsertChar('\u002E'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPC == '\u0055' && PC == '\u007E' && s == "h") //half n +h { RemoveChar(2); InsertChar('\u002E'); InsertChar('\u006B'); InsertChar('\u007E'); } else if (PPC == '\u006E' && PC == '\u007E' && s == "v") //d+v (No half d) { RemoveChar(2); InsertChar('\u007D'); InsertChar('\u007E'); } else if (PPC == '\u006E' && PC == '\u007E' && s == "y") //d+y (No half d) { RemoveChar(2); InsertChar('\u007C'); InsertChar('\u007E'); } else if (PPC == '\u006E' && PC == '\u007E' && s == "r") //d+r (No half d) { RemoveChar(2); InsertChar('\u00E6'); InsertChar('\u007E'); } else if (PPC == '\u006E' && PC == '\u007E' && s == "m") //d+m (No half d) { RemoveChar(2); InsertChar('\u00F9'); InsertChar('\u007E'); } else if (PPC == '\u0067' && PC == '\u007E' && s == "m") //h+m { RemoveChar(2); InsertChar('\u00E3'); InsertChar('\u007E'); } else if (PPPC == '\u00BA' && PPC == '\u006B' && PC == '\u007E' && s == "m") //half h + danda +m { RemoveChar(3); InsertChar('\u00E3'); InsertChar('\u007E'); } else if (PPC == '\u00BA' && PC == '\u007E' && s == "m") //half h +m { RemoveChar(2); InsertChar('\u00E3'); InsertChar('\u007E'); } //My special combination else if (PPC == '\u0067' && PC == '\u007E' && s == "y") //h+y { RemoveChar(2); InsertChar('\u00E1'); InsertChar('\u007E'); } else if (PPPC == '\u00BA' && PPC == '\u006B' && PC == '\u007E' && s == "y") //half h + danda +y { RemoveChar(3); InsertChar('\u00E1'); InsertChar('\u007E'); } else if (PPC == '\u00BA' && PC == '\u007E' && s == "y") //half h +y { RemoveChar(2); InsertChar('\u00E1'); InsertChar('\u007E'); } else if (PPC == '\u0072' && PC == '\u007E' && s == "r") //t+r { RemoveChar(2); InsertChar('\u003D'); InsertChar('\u007E'); } else if (PPPC == '\u0052' && PPC == '\u006B' && PC == '\u007E' && s == "r") //half t + danda +r { RemoveChar(3); InsertChar('\u003D'); InsertChar('\u007E'); } else if (PPC == '\u0052' && PC == '\u007E' && s == "r") //half t +r { RemoveChar(2); InsertChar('\u003D'); InsertChar('\u007E'); } //r matra combinations else if (PPC == '\u0067' && PC == '\u007E' && s == "r") //h+r { RemoveChar(2); InsertChar('\u00E2'); InsertChar('\u007E'); } else if (PPPC == '\u00BA' && PPC == '\u006B' && PC == '\u007E' && s == "r") //half h + danda +r { RemoveChar(3); InsertChar('\u00E2'); InsertChar('\u007E'); } else if (PPC == '\u00BA' && PC == '\u007E' && s == "r") //half h +r { RemoveChar(2); InsertChar('\u00E2'); InsertChar('\u007E'); } else if (PPC == '\u0064' && PC == '\u007E' && s == "r") //k+r { RemoveChar(2); InsertChar('\u00D8'); InsertChar('\u007E'); } else if (PPPC == '\u0044' && PPC == '\u006B' && PC == '\u007E' && s == "r") //half k + danda +r { RemoveChar(3); InsertChar('\u00D8'); InsertChar('\u007E'); } else if (PPC == '\u0044' && PC == '\u007E' && s == "r") //half k +r { RemoveChar(2); InsertChar('\u00D8'); InsertChar('\u007E'); } //No whole char for K else if (PPPC == '\u005B' && PPC == '\u006B' && PC == '\u007E' && s == "r") //half K + danda +r { RemoveChar(3); InsertChar('\u00A3'); InsertChar('\u007E'); } else if (PPC == '\u005B' && PC == '\u007E' && s == "r") //half K +r { RemoveChar(2); InsertChar('\u00A3'); InsertChar('\u007E'); } else if (PPPC == '\u0027' && PPC == '\u006B' && PC == '\u007E' && s == "r") //half sh + danda + r { RemoveChar(3); InsertChar('\u004A'); InsertChar('\u007E'); } else if (PPC == '\u0027' && PC == '\u007E' && s == "r") //half sh + r { RemoveChar(2); InsertChar('\u004A'); InsertChar('\u007E'); } #endregion #region Matras /* Matra Logic * Note: We cannot prevent the user from doing any grammatical mistakes involving matras or to * insert a matra from the char map with no logic at all. e.g. User might apply two matras of same type to same char. * So, in every matra include a logic that if there is a mistake, apply the matra as it is * on the current caret position. * * 1. Matras can only be applied to WholeChar. * 2. Three types of matras, one or maore than one of each type, can be applied to a WholeChar.Only AfterChar matra cam be applied * in combination. They have to be placed in sequence: * First Before matra, then Middle matra then After matra. * Though before matras can be an individual char, they can only be put as part of a WholeChar just following the wholechar. * * */ else if (s == "a" || s == "A") { if (Spaces.Contains(PC)) { InsertChar('\u0076'); } else if (PC == '\u007E') { RemoveChar(1); } else { TextPointer t = rtb.CaretPosition; NavigateToLastMiddleMatra(); InsertChar('\u006B'); rtb.CaretPosition = t; MoveCaretRight(); } } else if (s == "e") { if (this[-1] == '\u007E') { RemoveChar(1); TextPointer t = rtb.CaretPosition; NavigateToLastMiddleMatra(); InsertChar('\u0073'); rtb.CaretPosition = t; MoveCaretRight(); } else { InsertChar('\u002C'); } } else if (s == "E") { if (this[-1] == '\u007E') { RemoveChar(1); TextPointer t = rtb.CaretPosition; NavigateToLastMiddleMatra(); InsertChar('\u0053'); rtb.CaretPosition = t; MoveCaretRight(); } else { InsertChar('\u002C'); InsertChar('\u0073'); } } else if (s == "i") { if (this[-1] == '\u007E') { RemoveChar(1); TextPointer t = rtb.CaretPosition; while (true) //Discarding all matras (including danda for matra or for supporting half char) { if (Matra.Contains(this[-1])) MoveCaretLeft(); else break; } PC = this[-1]; PPC = this[-2]; if (Spaces.Contains(PC)) //This is just to put matra before any other matra { MoveCaretLeft(); //Don't worrry if MoveCaretLeft() is called on first char in document. MoveCaretLeft() checks for null and so it will not move in such cases. } else if (WholeChar.Contains(PC) && Spaces.Contains(PPC)) //If PC is wholechar and PPC is a space { MoveCaretLeft(); } else if (WholeChar.Contains(PC) || HalfChar.Contains(PC)) { while (true) { if (Spaces.Contains(this[-1])) break; else if (WholeChar.Contains(this[-1]) && this[-2] != '\u007E' && !HalfChar.Contains(this[-2])) //PC is Whoolechar { MoveCaretLeft(); break; } else if (HalfChar.Contains(this[-1]) && this[-2] != '\u007E' && !HalfChar.Contains(this[-2])) //PC is half char { MoveCaretLeft(); break; } else if (this[-1] == '\u006B' && HalfChar.Contains(this[-2]) && this[-3] != '\u007E' && !HalfChar.Contains(this[-3])) //Last char comb makes a whole char from a hlaf char and danda { MoveCaretLeft(); MoveCaretLeft(); break; } else MoveCaretLeft(); } } InsertChar('\u0066'); rtb.CaretPosition = t; } else { InsertChar('\u0062'); } } else if (s == "I") { if (this[-1] == '\u007E') { RemoveChar(1); TextPointer t = rtb.CaretPosition; NavigateToLastMiddleMatra(); InsertChar('\u0068'); rtb.CaretPosition = t; MoveCaretRight(); } else { InsertChar('\u00C3'); } } else if (s == "o") { if (this[-1] == '\u007E') { RemoveChar(1); TextPointer t = rtb.CaretPosition; NavigateToLastMiddleMatra(); InsertChar('\u00A8'); rtb.CaretPosition = t; MoveCaretRight(); } else { InsertChar('\u0076'); InsertChar('\u00A8'); } } else if (s == "O") { if (this[-1] == '\u007E') { RemoveChar(1); TextPointer t = rtb.CaretPosition; NavigateToLastMiddleMatra(); InsertChar('\u00A9'); rtb.CaretPosition = t; MoveCaretRight(); } else { InsertChar('\u0076'); InsertChar('\u00A9'); } } else if (s == "u") { if (this[-1] == '\u007E') { if (this[-2] == '\u006A') //ru { RemoveChar(2); InsertChar('\u0023'); } else { RemoveChar(1); TextPointer t = rtb.CaretPosition; NavigateToLastMiddleMatra(); InsertChar('\u0071'); rtb.CaretPosition = t; MoveCaretRight(); } } else { InsertChar('\u006D'); } } else if (s == "U") { if (this[-1] == '\u007E') { if (this[-2] == '\u006A') //ruu { RemoveChar(2); InsertChar('\u003A'); } else { RemoveChar(1); TextPointer t = rtb.CaretPosition; NavigateToLastMiddleMatra(); InsertChar('\u0077'); rtb.CaretPosition = t; MoveCaretRight(); } } else { InsertChar('\u00C5'); } } else if (s == "r") { if (this[-1] == '\u007E') { RemoveChar(1); //Remove continuation PC = this[-1]; PPC = this[-2]; if (WholeChar.Contains(PC)) //If previous char is whole char { TextPointer t = rtb.CaretPosition; NavigateToLastBeforeMatra(); InsertChar('\u007A'); //Insert r matra InsertChar('\u007E'); //Insert continuation rtb.CaretPosition = t; MoveCaretRight(); } else if (PC == '\u006B' && HalfChar.Contains(PPC)) //If previous char is danda and PPC is half char so that two gives a single whole char { TextPointer t = rtb.CaretPosition; NavigateToLastBeforeMatra(); InsertChar('\u007A'); //Insert r matra InsertChar('\u007E'); //Insert continuation rtb.CaretPosition = t; MoveCaretRight(); } else //Previous chars do not make a char combination { //Consider rewise : You should not remove the matra //RemoveChar(1); //Remove danda InsertChar('\u006A'); //Insert r InsertChar('\u007E'); //Insert continuation } } else { InsertChar('\u006A'); InsertChar('\u007E'); } } else if (s == "R") { if (PC == '\u007E') RemoveChar(1); //TextPointer t = rtb.CaretPosition; //Uncomment to apply Navigation function //NavigateToLastBeforeMatra(); InsertChar('\u0060'); //rtb.CaretPosition = t; //MoveCaretRight(); } #endregion #region Characters else if (s == "b") { InsertCharByInput('\u0063'); } else if (s == "B") { InsertCharByInput('\u00D2'); } else if (s == "c") { InsertCharByInput('\u0070'); } else if (s == "C") { InsertCharByInput('\u004E'); } else if (s == "d") { InsertCharByInput('\u006E'); } else if (s == "D") { InsertCharByInput('\u004D'); } else if (s == "f" || s == "F" || s == "P") { InsertCharByInput('\u0051'); } else if (s == "g") { InsertCharByInput('\u0078'); } else if (s == "G") { InsertCharByInput('\u00C4'); } else if (s == "h" || s == "H") { InsertCharByInput('\u0067'); } else if (s == "j") { InsertCharByInput('\u0074'); } else if (s == "J") { InsertCharByInput('\u003E'); } else if (s == "k") { InsertCharByInput('\u0064'); } else if (s == "K") { InsertCharByInput('\u005B'); } else if (s == "l") { InsertCharByInput('\u0079'); } else if (s == "L") { InsertCharByInput('\u0047'); } else if (s == "m") { InsertCharByInput('\u0065'); } else if (s == "M") //Bindus { if (PC == '\u007E') //Remove continuation if present { RemoveChar(1); PC = this[-1]; } if (PC == '\u005A') //r+bindu { RemoveChar(1); InsertChar('\u00B1'); } else if (PC == '\u0061') { RemoveChar(1); InsertChar('\u00A1'); } else if (PC == '\u00A1') { RemoveChar(1); InsertChar('\u0057'); } else if (PC == '\u0057') { RemoveChar(1); InsertChar('\u0061'); } else InsertChar('\u0061'); } else if (s == "n") { InsertCharByInput('\u0075'); } else if (s == "N") { InsertCharByInput('\u002E'); } else if (s == "p") { InsertCharByInput('\u0069'); } else if (s == "q") { InsertCharByInput('\u0064', false); InsertChar('\u002B'); InsertChar('\u007E'); } else if (s == "Q") { InsertChar('\u007E'); //Continuation char } else if (s == "s") { InsertCharByInput('\u006C'); } else if (s == "S") { InsertCharByInput('\u0022'); } else if (s == "t") { InsertCharByInput('\u0072'); } else if (s == "T") { InsertCharByInput('\u0056'); } else if (s == "v" || s == "V" || s == "w") { InsertCharByInput('\u006F'); } else if (s == "W") { InsertCharByInput('\u007D'); } else if (s == "x") { InsertCharByInput('\u007B'); } else if (s == "X") { } else if (s == "y" || s == "Y") { InsertCharByInput('\u00B8'); } else if (s == "z") { InsertCharByInput('\u0074', false); InsertChar('\u002B'); InsertChar('\u007E'); } else if (s == "Z") { } #endregion rtb.IsReadOnly = true; } } }
35.679602
241
0.322606
[ "MIT" ]
anujgeek/HindiTransliterator
HindiTransliterator/HindiTransliterator/PreviewTextInput.cs
35,860
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleSystemsManagement.Model { /// <summary> /// The activation is not valid. The activation might have been deleted, or the ActivationId /// and the ActivationCode do not match. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class InvalidActivationException : AmazonSimpleSystemsManagementException { /// <summary> /// Constructs a new InvalidActivationException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InvalidActivationException(string message) : base(message) {} /// <summary> /// Construct instance of InvalidActivationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public InvalidActivationException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of InvalidActivationException /// </summary> /// <param name="innerException"></param> public InvalidActivationException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of InvalidActivationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidActivationException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of InvalidActivationException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidActivationException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the InvalidActivationException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected InvalidActivationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
48.68
179
0.669351
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/InvalidActivationException.cs
6,085
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Xunit; using BuildXL.Cache.ContentStore.Interfaces.Logging; using BuildXL.Cache.ContentStore.Interfaces.FileSystem; using ContentStoreTest.Test; using BuildXL.Cache.ContentStore.FileSystem; using Xunit.Abstractions; using FluentAssertions; using System; using BuildXL.Cache.ContentStore.Stores; using BuildXL.Cache.ContentStore.Sessions; using BuildXL.Cache.ContentStore.Interfaces.Tracing; using BuildXL.Cache.ContentStore.InterfacesTest.Results; using BuildXL.Cache.ContentStore.Interfaces.Stores; using BuildXL.Cache.ContentStore.Hashing; using BuildXL.Cache.ContentStore.Interfaces.Sessions; using System.Threading; using BuildXL.Cache.ContentStore.Interfaces.Utils; using System.IO; using BuildXL.Native.IO; namespace BuildXL.Cache.ContentStore.App.Test { public class AppTests : TestBase { private static readonly string AppExe = Path.Combine("app", $"ContentStoreApp{(OperatingSystemHelper.IsWindowsOS ? ".exe" : "")}"); private static readonly Random Random = new Random(); public AppTests(ILogger logger = null, ITestOutputHelper output = null) : base(logger ?? TestGlobal.Logger, output) { } [Fact] public async Task PutFileThenPlaceTestAsync() { using var fileSystem = new PassThroughFileSystem(Logger); using var dir = new DisposableDirectory(fileSystem); var cacheDir = dir.Path / "cache"; var file = dir.Path / "theFile.txt"; fileSystem.WriteAllText(file, "Foo"); var args = new Dictionary<string, string> { ["cachePath"] = cacheDir.Path, ["path"] = file.Path, ["hashType"] = "MD5", ["LogSeverity"] = "Diagnostic", }; var hash = "1356C67D7AD1638D816BFB822DD2C25D"; await RunAppAsync("PutFile", args, Logger); var destination = dir.Path / "destination.txt"; args["hash"] = hash; args["path"] = destination.Path; await RunAppAsync("PlaceFile", args, Logger); fileSystem.ReadAllText(destination).Should().Be("Foo"); } [Fact] public async Task ServiceTestAsync() { using var fileSystem = new PassThroughFileSystem(Logger); using var dir = new DisposableDirectory(fileSystem); var cacheDir = dir.Path / "cache"; var dataPath = dir.Path / "data"; var args = new Dictionary<string, string> { ["paths"] = cacheDir.Path, ["names"] = "Default", ["grpcPort"] = "7090", ["LogSeverity"] = "Diagnostic", ["dataRootPath"] = dataPath.Path, ["Scenario"] = "AppTests", ["grpcPortFileName"] = "AppTestsMMF" }; var serviceProcess = RunService("Service", args, Logger); try { await RunAppAsync("ServiceRunning", new Dictionary<string, string> { { "waitSeconds", "5" }, { "Scenario", "AppTests" } }, Logger); var context = new Context(Logger); var config = new ServiceClientContentStoreConfiguration("Default", new ServiceClientRpcConfiguration { GrpcPort = 7090 }, scenario: "AppTests"); using var store = new ServiceClientContentStore(Logger, fileSystem, config); await store.StartupAsync(context).ShouldBeSuccess(); var sessionResult = store.CreateSession(context, "Default", ImplicitPin.None).ShouldBeSuccess(); using var session = sessionResult.Session; await session.StartupAsync(context).ShouldBeSuccess(); var source = dir.Path / "source.txt"; var contents = new byte[1024]; Random.NextBytes(contents); fileSystem.WriteAllBytes(source, contents); var putResult = await session.PutFileAsync(context, HashType.MD5, source, FileRealizationMode.Any, CancellationToken.None).ShouldBeSuccess(); var hash = putResult.ContentHash; await session.PinAsync(context, hash, CancellationToken.None).ShouldBeSuccess(); var destination = dir.Path / "destination.txt"; await session.PlaceFileAsync( context, hash, destination, FileAccessMode.ReadOnly, FileReplacementMode.FailIfExists, FileRealizationMode.Any, CancellationToken.None).ShouldBeSuccess(); fileSystem.ReadAllBytes(destination).Should().BeEquivalentTo(contents); } finally { if (!serviceProcess.HasExited) { serviceProcess.Kill(); #pragma warning disable AsyncFixer02 // WaitForExitAsync should be used instead serviceProcess.WaitForExit(); #pragma warning restore AsyncFixer02 } } } public static async Task RunAppAsync(string verb, Dictionary<string, string> args, ILogger logger) { FileUtilities.TrySetExecutePermissionIfNeeded(Path.Combine(Environment.CurrentDirectory, AppExe)); var info = new ProcessStartInfo { FileName = AppExe, Arguments = $"{verb} {string.Join(" ", args.Select(kvp => $" /{ kvp.Key}:{ kvp.Value}"))}", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; var process = new Process { StartInfo = info }; process.OutputDataReceived += (sender, data) => logger.Info(data.Data); process.ErrorDataReceived += (sender, data) => logger.Error(data.Data); logger.Info($"Running {process.StartInfo.FileName} {process.StartInfo.Arguments}"); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); var result = await Task.Run(() => { #pragma warning disable AsyncFixer02 // WaitForExitAsync should be used instead process.WaitForExit(); #pragma warning restore AsyncFixer02 return process.ExitCode; }); result.Should().Be(0); } public static Process RunService(string verb, Dictionary<string, string> args, ILogger logger) { FileUtilities.TrySetExecutePermissionIfNeeded(Path.Combine(Environment.CurrentDirectory, AppExe)); var info = new ProcessStartInfo { FileName = AppExe, Arguments = $"{verb} {string.Join(" ", args.Select(kvp => $" /{ kvp.Key}:{ kvp.Value}"))}", RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, UseShellExecute = false }; var process = new Process { StartInfo = info }; process.OutputDataReceived += (sender, data) => logger.Info(data.Data); process.ErrorDataReceived += (sender, data) => logger.Error(data.Data); logger.Info($"Running {process.StartInfo.FileName} {process.StartInfo.Arguments}"); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); return process; } } }
38.151659
161
0.57354
[ "MIT" ]
shivanshu3/BuildXL
Public/Src/Cache/ContentStore/AppTest/AppTests.cs
8,052
C#
using System.Diagnostics; using System.Text; using System.Threading.Tasks; using Qmmands; using Volte.Commands.Results; using Gommon; using Humanizer; namespace Volte.Commands.Modules { public sealed partial class UtilityModule : VolteModule { [Command("Ping")] [Description("Show the Gateway latency to Discord.")] [Remarks("ping")] public Task<ActionResult> PingAsync() => None(async () => { var e = Context.CreateEmbedBuilder("Pinging..."); var sw = new Stopwatch(); sw.Start(); var msg = await e.SendToAsync(Context.Channel); sw.Stop(); await msg.ModifyAsync(x => { e.WithDescription(new StringBuilder() .AppendLine($"{EmojiService.Clap} **Gateway**: {Context.Client.Latency} milliseconds") .AppendLine($"{EmojiService.OkHand} **REST**: {sw.Elapsed.Humanize(3)}") .ToString()); x.Embed = e.Build(); }); }, false); } }
33.617647
110
0.524059
[ "MIT" ]
Perksey/Volte
src/Commands/Modules/Utility/PingCommand.cs
1,145
C#
using System; using System.Reflection; using UnityEngine; using UnityEngine.Video; using Object = System.Object; public static class VideoUtil { //获取Preview Texture public static Texture GetPreviewTexture(Object previewID) { Type videoUtilType = Assembly.Load("UnityEditor.dll").GetType("UnityEditor.VideoUtil"); MethodInfo GetPreviewTextureMethodInfo = videoUtilType.GetMethod("GetPreviewTexture", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); Texture image = (Texture) GetPreviewTextureMethodInfo.Invoke(null, new object[] { previewID }); return image; } //开始播放Video public static Object PlayPreview(VideoClip audioClip) { Type videoUtilType = Assembly.Load("UnityEditor.dll").GetType("UnityEditor.VideoUtil"); MethodInfo startPreviewMethodInfo = videoUtilType.GetMethod("StartPreview", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); Object previewID = startPreviewMethodInfo.Invoke(null, new object[] {audioClip}); videoUtilType.GetMethod("PlayPreview", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Invoke(null, new object[] { previewID, true }); return previewID; } //停止播放Video public static void StopPreview(Object previewID) { Type videoUtilType = Assembly.Load("UnityEditor.dll").GetType("UnityEditor.VideoUtil"); videoUtilType.GetMethod("StopPreview", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Invoke(null, new object[] { previewID }); } }
38.090909
152
0.693914
[ "MIT" ]
Enough1122/UnityToolchainsTrick
Assets/Editor/Examples/Example_38_VideoEditorWindow/VideoUtil.cs
1,696
C#
#region License // Moonpie // // Copyright (c) 2022 Stay // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion namespace Moonpie.Protocol.Packets.s2c; public interface IS2CPacket : IPacket { }
39.21875
81
0.756175
[ "MIT" ]
Stay1444/Moonpie
src/Moonpie/Protocol/Packets/s2c/IS2CPacket.cs
1,257
C#
using HtmlAgilityPack; namespace MALScraping.Helpers { internal static class NodeCollectionHelper { internal static HtmlNodeCollection AdaptFavorites(HtmlNodeCollection nodeCollection) { if (nodeCollection.Count == 9) return nodeCollection[5].ChildNodes[1].ChildNodes; else return nodeCollection[7].ChildNodes[1].ChildNodes; } internal static HtmlNodeCollection AdaptAnimeStats(HtmlNodeCollection nodeCollection) { if (nodeCollection.Count == 9) return nodeCollection[1].ChildNodes[3].ChildNodes[1].ChildNodes; else return nodeCollection[3].ChildNodes[3].ChildNodes[1].ChildNodes; } internal static HtmlNodeCollection AdaptMangaStats(HtmlNodeCollection nodeCollection) { if (nodeCollection.Count == 9) return nodeCollection[1].ChildNodes[5].ChildNodes[1].ChildNodes; else return nodeCollection[3].ChildNodes[5].ChildNodes[1].ChildNodes; } } }
38.576923
107
0.693918
[ "MIT" ]
pedro-octavio/MALScraping
MALScraping/Helpers/NodeCollectionHelper.cs
1,005
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.PillPressRegistry.Interfaces { using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Regardingobjectidbcgovlocation. /// </summary> public static partial class RegardingobjectidbcgovlocationExtensions { /// <summary> /// Get regardingobjectid_bcgov_location from activitypointers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='activityid'> /// key: activityid of activitypointer /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMbcgovLocation Get(this IRegardingobjectidbcgovlocation operations, string activityid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.GetAsync(activityid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get regardingobjectid_bcgov_location from activitypointers /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='activityid'> /// key: activityid of activitypointer /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMbcgovLocation> GetAsync(this IRegardingobjectidbcgovlocation operations, string activityid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(activityid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get regardingobjectid_bcgov_location from asyncoperations /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='asyncoperationid'> /// key: asyncoperationid of asyncoperation /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMbcgovLocation Get1(this IRegardingobjectidbcgovlocation operations, string asyncoperationid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.Get1Async(asyncoperationid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get regardingobjectid_bcgov_location from asyncoperations /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='asyncoperationid'> /// key: asyncoperationid of asyncoperation /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMbcgovLocation> Get1Async(this IRegardingobjectidbcgovlocation operations, string asyncoperationid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get1WithHttpMessagesAsync(asyncoperationid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get regardingobjectid_bcgov_location from bulkdeletefailures /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bulkdeletefailureid'> /// key: bulkdeletefailureid of bulkdeletefailure /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMbcgovLocation Get2(this IRegardingobjectidbcgovlocation operations, string bulkdeletefailureid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.Get2Async(bulkdeletefailureid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get regardingobjectid_bcgov_location from bulkdeletefailures /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bulkdeletefailureid'> /// key: bulkdeletefailureid of bulkdeletefailure /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMbcgovLocation> Get2Async(this IRegardingobjectidbcgovlocation operations, string bulkdeletefailureid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get2WithHttpMessagesAsync(bulkdeletefailureid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get regardingobjectid_bcgov_location from syncerrors /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='syncerrorid'> /// key: syncerrorid of syncerror /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> public static MicrosoftDynamicsCRMbcgovLocation Get3(this IRegardingobjectidbcgovlocation operations, string syncerrorid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>)) { return operations.Get3Async(syncerrorid, select, expand).GetAwaiter().GetResult(); } /// <summary> /// Get regardingobjectid_bcgov_location from syncerrors /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='syncerrorid'> /// key: syncerrorid of syncerror /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MicrosoftDynamicsCRMbcgovLocation> Get3Async(this IRegardingobjectidbcgovlocation operations, string syncerrorid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get3WithHttpMessagesAsync(syncerrorid, select, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
46.475728
318
0.57019
[ "Apache-2.0" ]
GeorgeWalker/jag-pill-press-registry
pill-press-interfaces/Dynamics-Autorest/RegardingobjectidbcgovlocationExtensions.cs
9,574
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Media.Import { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] #endif public enum PhotoImportAccessMode { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ ReadWrite, #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ ReadOnly, #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ ReadAndDelete, #endif } #endif }
23.565217
49
0.699262
[ "Apache-2.0" ]
nv-ksavaria/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Import/PhotoImportAccessMode.cs
542
C#
using System; using System.Collections.Generic; using System.Text; namespace MLStudy.Tree { public class CART { } }
11.818182
33
0.692308
[ "Apache-2.0" ]
durow/MLSharp
MLStudy/Tree/CART.cs
132
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Regression; using System; #if UNITY_V4 using Microsoft.Practices.Unity; #else using Unity; using Unity.Lifetime; #endif namespace Registration { public partial class Legacy { [TestMethod] public void SimpleObject() { // Arrange var instance = Guid.NewGuid().ToString(); Container.RegisterInstance(instance); // Act/Validate Assert.AreEqual(Container.Resolve<string>(), instance); } [TestMethod] public void NamedObject() { // Arrange var instance = Guid.NewGuid().ToString(); Container.RegisterInstance(instance, instance); // Act/Validate Assert.AreEqual(Container.Resolve<string>(instance), instance); } [TestMethod] public void InterfacedObject() { // Arrange var instance = new Service(); Container.RegisterInstance<IService>(instance); // Act/Validate Assert.AreSame(instance, Container.Resolve<IService>()); Assert.AreNotSame(instance, Container.Resolve<Service>()); } [TestMethod] public void ExternallyControlledLifetimeManager() { // Arrange var instance = Guid.NewGuid().ToString(); Container.RegisterInstance(instance.GetType(), null, instance, new ExternallyControlledLifetimeManager()); // Act/Validate Assert.AreEqual(Container.Resolve<string>(), instance); } [TestMethod] public void RegisterWithParentAndChild() { //create unity container Container.RegisterInstance<string>(Guid.NewGuid().ToString(), new ContainerControlledLifetimeManager()); var child = Container.CreateChildContainer(); child.RegisterInstance<string>(Guid.NewGuid().ToString(), new ContainerControlledLifetimeManager()); // Act/Validate Assert.AreSame(Container.Resolve<string>(), Container.Resolve<string>()); Assert.AreSame(child.Resolve<string>(), child.Resolve<string>()); Assert.AreNotSame(Container.Resolve<string>(), child.Resolve<string>()); } } }
30.684211
118
0.605489
[ "Apache-2.0" ]
unitycontainer/container-regression-tests
Container/Registration/Legacy/Instance.cs
2,334
C#
// Copyright © 2020 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp.DevTools.Log { /// <summary> /// Violation configuration setting. /// </summary> [System.Runtime.Serialization.DataContractAttribute] public class ViolationSetting : CefSharp.DevTools.DevToolsDomainEntityBase { /// <summary> /// Violation type. /// </summary> [System.Runtime.Serialization.DataMemberAttribute(Name = ("name"), IsRequired = (true))] public string Name { get; set; } /// <summary> /// Time threshold to trigger upon. /// </summary> [System.Runtime.Serialization.DataMemberAttribute(Name = ("threshold"), IsRequired = (true))] public long Threshold { get; set; } } }
29.84375
101
0.589529
[ "BSD-3-Clause" ]
campersau/CefSharp
CefSharp/DevTools/Log/ViolationSetting.cs
956
C#
using Wumpus.Entities; namespace Wumpus.Bot { public class CachedChannel : Channel { } }
11.444444
40
0.660194
[ "MIT" ]
Aux/Wumpus.Net
src/Wumpus.Net.Bot/Entities/CachedChannel.cs
105
C#
using System.CodeDom.Compiler; using System; using System.Runtime.Serialization; namespace SolidRpc.Test.Vitec.Types.PublicAdvertisement.Models { /// <summary> /// /// </summary> [GeneratedCode("OpenApiCodeGeneratorV2","1.0.0.0")] public class CommercialPropertyMarketing { /// <summary> /// Bostadsfastighet /// </summary> [DataMember(Name="residental",EmitDefaultValue=false)] public bool? Residental { get; set; } /// <summary> /// Butiksfastighet /// </summary> [DataMember(Name="retail",EmitDefaultValue=false)] public bool? Retail { get; set; } /// <summary> /// Industrifastighet /// </summary> [DataMember(Name="industrial",EmitDefaultValue=false)] public bool? Industrial { get; set; } /// <summary> /// Kontorsfastighet /// </summary> [DataMember(Name="office",EmitDefaultValue=false)] public bool? Office { get; set; } /// <summary> /// Lagerfastighet /// </summary> [DataMember(Name="warehouse",EmitDefaultValue=false)] public bool? Warehouse { get; set; } /// <summary> /// Lokalfastighet /// </summary> [DataMember(Name="premises",EmitDefaultValue=false)] public bool? Premises { get; set; } /// <summary> /// Tomt /// </summary> [DataMember(Name="plot",EmitDefaultValue=false)] public bool? Plot { get; set; } /// <summary> /// R&#246;relse /// </summary> [DataMember(Name="business",EmitDefaultValue=false)] public bool? Business { get; set; } /// <summary> /// Kommande /// </summary> [DataMember(Name="isFutureSale",EmitDefaultValue=false)] public bool? IsFutureSale { get; set; } /// <summary> /// Snart till salu /// </summary> [DataMember(Name="isSoonForSale",EmitDefaultValue=false)] public bool? IsSoonForSale { get; set; } } }
29.929577
65
0.547294
[ "MIT" ]
aarrgard/solidrpc
SolidRpc.Test.Vitec/Types/PublicAdvertisement/Models/CommercialPropertyMarketing.cs
2,125
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GildedRose.Console { /// <summary> /// An item has a name, sellin value (the number of days to sell the item), /// and a given quality. /// </summary> public class Item { public string Name { get; set; } public int SellIn { get; set; } public int Quality { get; set; } } }
20.681818
79
0.624176
[ "MIT" ]
KarimLjung/GildedRoseRefactored
src/GildedRose.Console/Item.cs
457
C#
using Omnius.Axis.Engines.Internal.Models; using Omnius.Core.Cryptography; namespace Omnius.Axis.Engines.Internal.Entities; internal record MerkleTreeSectionEntity { public int Depth { get; set; } public uint BlockLength { get; set; } public ulong Length { get; set; } public OmniHashEntity[]? Hashes { get; set; } public static MerkleTreeSectionEntity Import(MerkleTreeSection value) { return new MerkleTreeSectionEntity() { Depth = value.Depth, Hashes = value.Hashes.Select(n => OmniHashEntity.Import(n)).ToArray(), }; } public MerkleTreeSection Export() { return new MerkleTreeSection(this.Depth, this.Hashes?.Select(n => n.Export())?.ToArray() ?? Array.Empty<OmniHash>()); } }
26.133333
125
0.66199
[ "MIT" ]
OmniusLabs/Xeus
src/Omnius.Axis.Engines/Implementations/Internal/Entities/MerkleTreeSectionEntity.cs
784
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("BAPSFormControls")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BAPSFormControls")] [assembly: AssemblyCopyright("Copyright © 2007")] [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("26ce095a-b521-4d56-8822-dceb64b7eeec")] // 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.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.833333
84
0.750367
[ "BSD-3-Clause" ]
UniversityRadioYork/BAPS2
BAPSFormControls/Properties/AssemblyInfo.cs
1,363
C#
using System; using System.Collections.Generic; using System.Linq; using MarkDoc.Helpers; namespace MarkDoc.Elements.Markdown { /// <summary> /// Class for markdown tables /// </summary> public class Table : BaseElement, ITable { #region Constants private const string DEL_VERTICAL = "|"; private const string DEL_HORIZONTAL = "-"; #endregion #region Properties /// <inheritdoc /> public string Heading { get; } /// <inheritdoc /> public int Level { get; } /// <inheritdoc /> public IReadOnlyCollection<IText> Headings { get; } /// <inheritdoc /> public IReadOnlyCollection<IReadOnlyCollection<IElement>> Content { get; } #endregion /// <summary> /// Default constructor /// </summary> /// <param name="headings">Table headings</param> /// <param name="content">Collection of rows</param> /// <param name="heading">Element heading</param> /// <param name="level">Element heading level</param> public Table(IEnumerable<IText> headings, IEnumerable<IReadOnlyCollection<IElement>> content, string heading = "", int level = 0) { Headings = headings.ToReadOnlyCollection(); Content = content.ToReadOnlyCollection(); Heading = heading; Level = level; } /// <inheritdoc /> public override IEnumerable<string> Print() { // If there is a heading.. if (!string.IsNullOrEmpty(Heading)) { // print the heading yield return Heading.ToHeading(Level); // print a line break yield return Environment.NewLine; } // Begin column headers with a vertical delimiter yield return DEL_VERTICAL; // For every heading.. foreach (var heading in Headings) { // start heading with whitespace yield return " "; // for every part of a heading.. foreach (var line in heading.Print()) // print it yield return line; // finish heading with whitespace and a vertical line yield return $" {DEL_VERTICAL}"; } // Print line break from headings yield return Environment.NewLine; // Being the horizontal line with a vertical delimiter yield return DEL_VERTICAL; // For the number of headings.. for (var i = 0; i < Headings.Count; i++) // print parts of the horizontal line yield return $" {DEL_HORIZONTAL}{DEL_HORIZONTAL}{DEL_HORIZONTAL} {DEL_VERTICAL}"; // For every row.. foreach (var p in ProcessContentRows()) yield return p; } private IEnumerable<string> ProcessContentRows() { foreach (var row in Content) { // break to a new line yield return Environment.NewLine; // begin building the row with a vertical delimiter yield return DEL_VERTICAL; // assume none of columns are filled by this row var colCount = 0; // for every (but not more than headings) row item.. foreach (var item in row.Take(Headings.Count)) { // increment the filled row count colCount++; // start row item with whitespace yield return " "; // for every part of a row item.. foreach (var line in item.Print()) // fix characters and print it yield return line.ReplaceNewline(); // finish the row item with a whitespace and vertical line yield return $" {DEL_VERTICAL}"; } // if there are more headings than there are row items.. if (Headings.Count <= colCount) continue; for (var i = 0; i < Headings.Count - colCount; i++) { // print an empty row item yield return " "; // finish the row item with a vertical line yield return DEL_VERTICAL; } } // print a line break yield return Environment.NewLine; } } }
28.941606
133
0.601513
[ "MIT" ]
hailstorm75/MarkDoc.Core
src/Components/Elements/MarkDoc.Elements.Markdown/Table.cs
3,967
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.ApplicationPlugins.RegionModulesController { public class RegionModulesControllerPlugin : IRegionModulesController, IApplicationPlugin { // Logger private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // Config access private OpenSimBase m_openSim; // Our name private string m_name; // Internal lists to collect information about modules present private List<TypeExtensionNode> m_nonSharedModules = new List<TypeExtensionNode>(); private List<TypeExtensionNode> m_sharedModules = new List<TypeExtensionNode>(); // List of shared module instances, for adding to Scenes private List<ISharedRegionModule> m_sharedInstances = new List<ISharedRegionModule>(); #region IApplicationPlugin implementation public void Initialise (OpenSimBase openSim) { m_openSim = openSim; m_openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this); m_log.DebugFormat("[REGIONMODULES]: Initializing..."); // Who we are string id = AddinManager.CurrentAddin.Id; // Make friendly name int pos = id.LastIndexOf("."); if (pos == -1) m_name = id; else m_name = id.Substring(pos + 1); // The [Modules] section in the ini file IConfig modulesConfig = m_openSim.ConfigSource.Source.Configs["Modules"]; if (modulesConfig == null) modulesConfig = m_openSim.ConfigSource.Source.AddConfig("Modules"); // Scan modules and load all that aren't disabled foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes("/OpenSim/RegionModules")) { if (node.Type.GetInterface(typeof(ISharedRegionModule).ToString()) != null) { if (CheckModuleEnabled(node, modulesConfig)) { m_log.DebugFormat("[REGIONMODULES]: Found shared region module {0}, class {1}", node.Id, node.Type); m_sharedModules.Add(node); } } else if (node.Type.GetInterface(typeof(INonSharedRegionModule).ToString()) != null) { if (CheckModuleEnabled(node, modulesConfig)) { m_log.DebugFormat("[REGIONMODULES]: Found non-shared region module {0}, class {1}", node.Id, node.Type); m_nonSharedModules.Add(node); } } else { m_log.DebugFormat("[REGIONMODULES]: Found unknown type of module {0}, class {1}", node.Id, node.Type); } } // Load and init the module. We try a constructor with a port // if a port was given, fall back to one without if there is // no port or the more specific constructor fails. // This will be removed, so that any module capable of using a port // must provide a constructor with a port in the future. // For now, we do this so migration is easy. // foreach (TypeExtensionNode node in m_sharedModules) { Object[] ctorArgs = new Object[] { (uint)0 }; // Read the config again string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // Get the port number, if there is one if (moduleString != String.Empty) { // Get the port number from the string string[] moduleParts = moduleString.Split(new char[] { '/' }, 2); if (moduleParts.Length > 1) ctorArgs[0] = Convert.ToUInt32(moduleParts[0]); } // Try loading and initilaizing the module, using the // port if appropriate ISharedRegionModule module = null; try { module = (ISharedRegionModule)Activator.CreateInstance( node.Type, ctorArgs); } catch { module = (ISharedRegionModule)Activator.CreateInstance( node.Type); } // OK, we're up and running m_sharedInstances.Add(module); module.Initialise(m_openSim.ConfigSource.Source); } } public void PostInitialise () { m_log.DebugFormat("[REGIONMODULES]: PostInitializing..."); // Immediately run PostInitialise on shared modules foreach (ISharedRegionModule module in m_sharedInstances) { module.PostInitialise(); } } #endregion #region IPlugin implementation // We don't do that here // public void Initialise () { throw new System.NotImplementedException(); } #endregion #region IDisposable implementation // Cleanup // public void Dispose () { // We expect that all regions have been removed already while (m_sharedInstances.Count > 0) { m_sharedInstances[0].Close(); m_sharedInstances.RemoveAt(0); } m_sharedModules.Clear(); m_nonSharedModules.Clear(); } #endregion public string Version { get { return AddinManager.CurrentAddin.Version; } } public string Name { get { return m_name; } } #region IRegionModulesController implementation /// <summary> /// Check that the given module is no disabled in the [Modules] section of the config files. /// </summary> /// <param name="node"></param> /// <param name="modulesConfig">The config section</param> /// <returns>true if the module is enabled, false if it is disabled</returns> protected bool CheckModuleEnabled(TypeExtensionNode node, IConfig modulesConfig) { // Get the config string string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // We have a selector if (moduleString != String.Empty) { // Allow disabling modules even if they don't have // support for it if (moduleString == "disabled") return false; // Split off port, if present string[] moduleParts = moduleString.Split(new char[] { '/' }, 2); // Format is [port/][class] string className = moduleParts[0]; if (moduleParts.Length > 1) className = moduleParts[1]; // Match the class name if given if (className != String.Empty && node.Type.ToString() != className) return false; } return true; } // The root of all evil. // This is where we handle adding the modules to scenes when they // load. This means that here we deal with replaceable interfaces, // nonshared modules, etc. // public void AddRegionToModules (Scene scene) { Dictionary<Type, ISharedRegionModule> deferredSharedModules = new Dictionary<Type, ISharedRegionModule>(); Dictionary<Type, INonSharedRegionModule> deferredNonSharedModules = new Dictionary<Type, INonSharedRegionModule>(); // We need this to see if a module has already been loaded and // has defined a replaceable interface. It's a generic call, // so this can't be used directly. It will be used later Type s = scene.GetType(); MethodInfo mi = s.GetMethod("RequestModuleInterface"); // This will hold the shared modules we actually load List<ISharedRegionModule> sharedlist = new List<ISharedRegionModule>(); // Iterate over the shared modules that have been loaded // Add them to the new Scene foreach (ISharedRegionModule module in m_sharedInstances) { // Here is where we check if a replaceable interface // is defined. If it is, the module is checked against // the interfaces already defined. If the interface is // defined, we simply skip the module. Else, if the module // defines a replaceable interface, we add it to the deferred // list. Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } deferredSharedModules[replaceableInterface] = module; m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1}", scene.RegionInfo.RegionName, module.Name); module.AddRegion(scene); scene.AddRegionModule(module.Name, module); sharedlist.Add(module); } IConfig modulesConfig = m_openSim.ConfigSource.Source.Configs["Modules"]; // Scan for, and load, nonshared modules List<INonSharedRegionModule> list = new List<INonSharedRegionModule>(); foreach (TypeExtensionNode node in m_nonSharedModules) { Object[] ctorArgs = new Object[] {0}; // Read the config string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // Get the port number, if there is one if (moduleString != String.Empty) { // Get the port number from the string string[] moduleParts = moduleString.Split(new char[] {'/'}, 2); if (moduleParts.Length > 1) ctorArgs[0] = Convert.ToUInt32(moduleParts[0]); } // Actually load it INonSharedRegionModule module = null; Type[] ctorParamTypes = new Type[ctorArgs.Length]; for (int i = 0; i < ctorParamTypes.Length; i++) ctorParamTypes[i] = ctorArgs[i].GetType(); if (node.Type.GetConstructor(ctorParamTypes) != null) module = (INonSharedRegionModule)Activator.CreateInstance(node.Type, ctorArgs); else module = (INonSharedRegionModule)Activator.CreateInstance(node.Type); // Check for replaceable interfaces Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } deferredNonSharedModules[replaceableInterface] = module; m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1}", scene.RegionInfo.RegionName, module.Name); // Initialise the module module.Initialise(m_openSim.ConfigSource.Source); list.Add(module); } // Now add the modules that we found to the scene. If a module // wishes to override a replaceable interface, it needs to // register it in Initialise, so that the deferred module // won't load. foreach (INonSharedRegionModule module in list) { module.AddRegion(scene); scene.AddRegionModule(module.Name, module); } // Now all modules without a replaceable base interface are loaded // Replaceable modules have either been skipped, or omitted. // Now scan the deferred modules here foreach (ISharedRegionModule module in deferredSharedModules.Values) { // Determine if the interface has been replaced Type replaceableInterface = module.ReplaceableInterface; MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1} (deferred)", scene.RegionInfo.RegionName, module.Name); // Not replaced, load the module module.AddRegion(scene); scene.AddRegionModule(module.Name, module); sharedlist.Add(module); } // Same thing for nonshared modules, load them unless overridden List<INonSharedRegionModule> deferredlist = new List<INonSharedRegionModule>(); foreach (INonSharedRegionModule module in deferredNonSharedModules.Values) { // Check interface override Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1} (deferred)", scene.RegionInfo.RegionName, module.Name); module.Initialise(m_openSim.ConfigSource.Source); list.Add(module); deferredlist.Add(module); } // Finally, load valid deferred modules foreach (INonSharedRegionModule module in deferredlist) { module.AddRegion(scene); scene.AddRegionModule(module.Name, module); } // This is needed for all module types. Modules will register // Interfaces with scene in AddScene, and will also need a means // to access interfaces registered by other modules. Without // this extra method, a module attempting to use another modules's // interface would be successful only depending on load order, // which can't be depended upon, or modules would need to resort // to ugly kludges to attempt to request interfaces when needed // and unneccessary caching logic repeated in all modules. // The extra function stub is just that much cleaner // foreach (ISharedRegionModule module in sharedlist) { module.RegionLoaded(scene); } foreach (INonSharedRegionModule module in list) { module.RegionLoaded(scene); } } public void RemoveRegionFromModules (Scene scene) { foreach (IRegionModuleBase module in scene.RegionModules.Values) { m_log.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}", scene.RegionInfo.RegionName, module.Name); module.RemoveRegion(scene); if (module is INonSharedRegionModule) { // as we were the only user, this instance has to die module.Close(); } } scene.RegionModules.Clear(); } #endregion } }
40.492784
165
0.555069
[ "BSD-3-Clause" ]
allquixotic/opensim-autobackup
OpenSim/ApplicationPlugins/RegionModulesController/RegionModulesControllerPlugin.cs
19,639
C#