Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix d'un bug qui faisait en sorte que le showDialog ne fonctionnait pas
using MahApps.Metro.Controls; using System; using System.Collections.Generic; using System.Linq; using System.Text; 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.Shapes; namespace Lama.UI.Win { /// <summary> /// Logique d'interaction pour AjouterVolontaire.xaml /// </summary> public partial class AjouterVolontaire : MetroWindow { public AjouterVolontaire() { InitializeComponent(); } } }
using MahApps.Metro.Controls; using System; using System.Collections.Generic; using System.Linq; using System.Text; 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.Shapes; namespace Lama.UI.Win { /// <summary> /// Logique d'interaction pour AjouterVolontaire.xaml /// </summary> public partial class AjouterVolontaire { public AjouterVolontaire() { InitializeComponent(); } } }
Change how constants are defined
using System; namespace ZocMonLib { public class Constant { public static readonly DateTime MinDbDateTime = new DateTime(1753, 1, 1); public const long TicksInMillisecond = 10000; public const long MinResolutionForDbWrites = 60 * 1000; public const long MsPerDay = 24 * 60 * 60 * 1000; public const int MaxConfigNameLength = 116; public const int MaxDataPointsPerLine = 2000; // roughly 3 months of hourly data } }
using System; using System.Data.SqlTypes; namespace ZocMonLib { public class Constant { public static readonly DateTime MinDbDateTime = SqlDateTime.MinValue.Value; public const long TicksInMillisecond = TimeSpan.TicksPerMillisecond; public const long MinResolutionForDbWrites = 60 * 1000; public const long MsPerDay = TimeSpan.TicksPerDay / TimeSpan.TicksPerMillisecond; public const int MaxConfigNameLength = 116; public const int MaxDataPointsPerLine = 2000; // roughly 3 months of hourly data } }
Add a new Paused mode.
using System; using System.Collections.Generic; using System.Text; using MonoTorrent.Common; namespace MonoTorrent.Client { class PausedMode : Mode { public override TorrentState State { get { return TorrentState.Paused; } } public PausedMode(TorrentManager manager) : base(manager) { // When in the Paused mode, a special RateLimiter will // activate and disable transfers. PauseMode itself // does not need to do anything special. } public override void Tick(int counter) { // TODO: In future maybe this can be made smarter by refactoring // so that in Pause mode we set the Interested status of all peers // to false, so no data is requested. This way connections can be // kept open by sending/receiving KeepAlive messages. Currently // we 'Pause' by not sending/receiving data from the socket. } } }
Change the MSI version to 1.8
// // Copyright 2012 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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft.WindowsAzure.Configuration")] [assembly: AssemblyDescription("Configuration API for Windows Azure services.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft.WindowsAzure.Configuration")] [assembly: AssemblyCopyright("Copyright © Microsoft Corporation 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3a4d8eda-db18-4c6f-9f84-4576bb255f30")] [assembly: AssemblyVersion("1.7.0.0")] [assembly: AssemblyFileVersion("1.7.0.0")]
// // Copyright 2012 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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft.WindowsAzure.Configuration")] [assembly: AssemblyDescription("Configuration API for Windows Azure services.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft.WindowsAzure.Configuration")] [assembly: AssemblyCopyright("Copyright © Microsoft Corporation 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3a4d8eda-db18-4c6f-9f84-4576bb255f30")] [assembly: AssemblyVersion("1.8.0.0")] [assembly: AssemblyFileVersion("1.8.0.0")]
Add test coverage of `SettingsCheckbox`
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; using osu.Game.Overlays.Settings; using osuTK; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneSettingsCheckbox : OsuTestScene { [TestCase] public void TestCheckbox() { AddStep("create component", () => { FillFlowContainer flow; Child = flow = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 500, AutoSizeAxes = Axes.Y, Spacing = new Vector2(5), Direction = FillDirection.Vertical, Children = new Drawable[] { new SettingsCheckbox { LabelText = "a sample component", }, }, }; foreach (var colour1 in Enum.GetValues(typeof(OverlayColourScheme)).OfType<OverlayColourScheme>()) { flow.Add(new OverlayColourContainer(colour1) { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Child = new SettingsCheckbox { LabelText = "a sample component", } }); } }); } private class OverlayColourContainer : Container { [Cached] private OverlayColourProvider colourProvider; public OverlayColourContainer(OverlayColourScheme scheme) { colourProvider = new OverlayColourProvider(scheme); } } } }
Add unit tests for Users API controller
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Moq; using Xunit; using ISTS.Api.Controllers; using ISTS.Api.Helpers; using ISTS.Application.Users; namespace ISTS.Api.Test.Controllers { public class UsersControllerTests { private Mock<IOptions<ApplicationSettings>> _options; private Mock<IUserService> _userService; private UsersController _usersController; public UsersControllerTests() { _options = new Mock<IOptions<ApplicationSettings>>(); _userService = new Mock<IUserService>(); _usersController = new UsersController(_options.Object, _userService.Object); } [Fact] public async void Register_Returns_OkObjectResult_With_UserDto() { var dto = new UserPasswordDto { Email = "my@email.com", DisplayName = "My User", PostalCode = "11111" }; var expectedModel = new UserDto { Id = Guid.NewGuid(), Email = dto.Email, DisplayName = dto.DisplayName, PostalCode = dto.PostalCode }; _userService .Setup(s => s.CreateAsync(It.IsAny<UserPasswordDto>())) .Returns(Task.FromResult(expectedModel)); var result = await _usersController.Register(dto); Assert.IsType<OkObjectResult>(result); var okResult = result as OkObjectResult; Assert.IsType<UserDto>(okResult.Value); var model = okResult.Value as UserDto; Assert.Equal(expectedModel.Id, model.Id); Assert.Equal(expectedModel.Email, model.Email); Assert.Equal(expectedModel.DisplayName, model.DisplayName); Assert.Equal(expectedModel.PostalCode, model.PostalCode); } [Fact] public async void Authenticate_Returns_UnauthorizedResult() { var dto = new UserPasswordDto { Email = "my@email.com", Password = "BadP@ssw0rd" }; _userService .Setup(s => s.AuthenticateAsync(It.IsAny<string>(), It.IsAny<string>())) .Returns(Task.FromResult<UserDto>(null)); var result = await _usersController.Authenticate(dto); Assert.IsType<UnauthorizedResult>(result); } } }
Split out test for combo counter specifically
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play.HUD; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneComboCounter : SkinnableTestScene { private IEnumerable<SkinnableComboCounter> comboCounters => CreatedDrawables.OfType<SkinnableComboCounter>(); protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUpSteps] public void SetUpSteps() { AddStep("Create combo counters", () => SetContents(() => { var comboCounter = new SkinnableComboCounter(); comboCounter.Current.Value = 1; return comboCounter; })); } [Test] public void TestComboCounterIncrementing() { AddRepeatStep("increase combo", () => { foreach (var counter in comboCounters) counter.Current.Value++; }, 10); AddStep("reset combo", () => { foreach (var counter in comboCounters) counter.Current.Value = 0; }); } } }
Add test for racecondition issue
using System.IO; using Microsoft.Extensions.Configuration; using NUnit.Framework; using Tiver.Fowl.Drivers.Configuration; using Tiver.Fowl.Drivers.DriverBinaries; using Tiver.Fowl.Drivers.DriverDownloaders; namespace Tiver.Fowl.Drivers.Tests { [TestFixture] public class DownloadersParallel { private static DriversConfiguration Config { get { var driversConfiguration = new DriversConfiguration(); var config = new ConfigurationBuilder() .AddJsonFile("Tiver_config.json", optional: true) .Build(); config.GetSection("Tiver.Fowl.Drivers").Bind(driversConfiguration); return driversConfiguration; } } private static string[] Platforms = {"win32", "linux64"}; private static string BinaryName(string platform) { return platform switch { "win32" => "chromedriver.exe", _ => "chromedriver" }; } private static string DriverFilepath(string platform) { return Path.Combine(Config.DownloadLocation, BinaryName(platform)); } private void DeleteDriverAndVersionFilesIfExist() { foreach (var platform in Platforms) { if (File.Exists(DriverFilepath(platform))) { File.Delete(DriverFilepath(platform)); } var versionFilepath = Path.Combine(Config.DownloadLocation, $"{BinaryName(platform)}.version"); if (File.Exists(versionFilepath)) { File.Delete(versionFilepath); } } } [OneTimeSetUp] public void SetUp() { DeleteDriverAndVersionFilesIfExist(); } [Test, Parallelizable(ParallelScope.All)] [TestCase(1)] [TestCase(2)] [TestCase(3)] public void Download_ParallelTests(int threadNumber) { var downloader = new ChromeDriverDownloader(); const string versionNumber = "76.0.3809.25"; var result = downloader.DownloadBinary(versionNumber, "win32"); Assert.IsTrue(result.Successful, $"Reported error message:{result.ErrorMessage}"); Assert.AreEqual(DownloaderAction.BinaryDownloaded, result.PerformedAction); Assert.IsNull(result.ErrorMessage); var exists = File.Exists(DriverFilepath("win32")); Assert.IsTrue(exists); exists = downloader.Binary.CheckBinaryExists(); Assert.IsTrue(exists); Assert.AreEqual(versionNumber, downloader.Binary.GetExistingBinaryVersion()); } } }
Set Horizontal And Vertical Image Resolution
using Aspose.Words.Saving; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Aspose.Words.Examples.CSharp.Rendering_Printing { class SetHorizontalAndVerticalImageResolution { public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_RenderingAndPrinting(); // Load the documents Document doc = new Document(dataDir + "TestFile.doc"); //Renders a page of a Word document into a PNG image at a specific horizontal and vertical resolution. ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); options.HorizontalResolution = 300; options.VerticalResolution = 300; options.PageCount = 1; doc.Save(dataDir + "Rendering.SaveToImageResolution Out.png", options); } } }
Add interface for content validation
using Microsoft.AspNetCore.Http; using System.Threading.Tasks; namespace Porthor.ContentValidation { public interface IContentValidator { Task<bool> Validate(HttpRequest request); } }
Create view model for user
namespace DevelopmentInProgress.AuthorisationManager.ASP.Net.Core.ViewModels { public class UserViewModel { public string Id { get; set; } public string Name { get; set; } public string DisplayName { get; set; } } }
Add new parser test base
using System; using System.Linq; using JetBrains.Annotations; using JetBrains.Application.Components; using JetBrains.ProjectModel; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ExtensionsAPI; using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree; using JetBrains.ReSharper.Psi.Files; using JetBrains.ReSharper.Psi.Impl.Shared; using JetBrains.ReSharper.Psi.Tree; using JetBrains.ReSharper.TestFramework; using JetBrains.ReSharper.TestFramework.Components.Psi; using JetBrains.Util; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Yaml.Tests.Psi.Parsing { // This is a replacement for the standard ParserTestBase<TLanguage> that will check the nodes of the parsed tree // against the gold file, but will also assert that all top level chameleons are closed by default and open correctly. // It also asserts that each node correctly matches the textual content of the original document [Category("Parser")] public abstract class ParserTestBase<TLanguage> : BaseTestWithTextControl where TLanguage : PsiLanguageType { protected override void DoTest(IProject testProject) { ShellInstance.GetComponent<TestIdGenerator>().Reset(); using (var textControl = OpenTextControl(testProject)) { ExecuteWithGold(textControl.Document, sw => { var files = textControl .Document .GetPsiSourceFiles(Solution) .SelectMany(s => s.GetPsiFiles<TLanguage>()) .ToList(); files.Sort((file1, file2) => String.Compare(file1.Language.Name, file2.Language.Name, StringComparison.Ordinal)); foreach (var psiFile in files) { // Assert all chameleons are closed by default var chameleons = psiFile.ThisAndDescendants<IChameleonNode>(); while (chameleons.MoveNext()) { var chameleonNode = chameleons.Current; if (chameleonNode.IsOpened && !(chameleonNode is IComment)) Assertion.Fail("Found chameleon node that was opened after parser is invoked: '{0}'", chameleonNode.GetText()); chameleons.SkipThisNode(); } // Dump the PSI tree, opening all chameleons sw.WriteLine("Language: {0}", psiFile.Language); DebugUtil.DumpPsi(sw, psiFile); sw.WriteLine(); if (((IFileImpl) psiFile).SecondaryRangeTranslator is RangeTranslatorWithGeneratedRangeMap rangeTranslator) WriteCommentedText(sw, "//", rangeTranslator.Dump(psiFile)); // Verify textual contents var originalText = textControl.Document.GetText(); Assert.AreEqual(originalText, psiFile.GetText(), "Reconstructed text mismatch"); CheckRange(originalText, psiFile); } }); } } private static void CheckRange([NotNull] string documentText, [NotNull] ITreeNode node) { Assert.AreEqual(node.GetText(), documentText.Substring(node.GetTreeStartOffset().Offset, node.GetTextLength()), "node range text mismatch"); for (var child = node.FirstChild; child != null; child = child.NextSibling) CheckRange(documentText, child); } } }
Add AutoSave on run feature - toggle
using UnityEngine; using UnityEditor; using UnityEditor.SceneManagement; [InitializeOnLoad] public class AutoSaveOnRunMenuItem { public const string MenuName = "Tools/Autosave On Run"; private static bool isToggled; static AutoSaveOnRunMenuItem() { EditorApplication.delayCall += () => { isToggled = EditorPrefs.GetBool(MenuName, false); UnityEditor.Menu.SetChecked(MenuName, isToggled); SetMode(); }; } [MenuItem(MenuName)] private static void ToggleMode() { isToggled = !isToggled; UnityEditor.Menu.SetChecked(MenuName, isToggled); EditorPrefs.SetBool(MenuName, isToggled); SetMode(); } private static void SetMode() { if (isToggled) { EditorApplication.playModeStateChanged += AutoSaveOnRun; } else { EditorApplication.playModeStateChanged -= AutoSaveOnRun; } } private static void AutoSaveOnRun(PlayModeStateChange state) { if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying) { Debug.Log("Auto-Saving before entering Play mode"); EditorSceneManager.SaveOpenScenes(); AssetDatabase.SaveAssets(); } } }
Add vehicleType into Command Parameter Types.
// SampSharp // Copyright 2017 Tim Potze // // 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.Globalization; using System.Linq; using SampSharp.GameMode.World; namespace SampSharp.GameMode.SAMP.Commands.ParameterTypes { /// <summary> /// Represents a player command parameter. /// </summary> public class VehicleType : ICommandParameterType { #region Implementation of ICommandParameterType /// <summary> /// Gets the value for the occurance of this parameter type at the start of the commandText. The processed text will be /// removed from the commandText. /// </summary> /// <param name="commandText">The command text.</param> /// <param name="output">The output.</param> /// <returns> /// true if parsed successfully; false otherwise. /// </returns> public bool Parse(ref string commandText, out object output) { var text = commandText.TrimStart(); output = null; if (string.IsNullOrEmpty(text)) return false; var word = text.Split(' ').First(); // find a vehicle with a matching id. int id; if (int.TryParse(word, NumberStyles.Integer, CultureInfo.InvariantCulture, out id)) { var vehicle = BaseVehicle.Find(id); if (vehicle != null) { output = vehicle; commandText = commandText.Substring(word.Length).TrimStart(' '); return true; } } return false; } #endregion } }
Create server side API for single multiple answer question
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
Add useful extensions for tree operations
using System.Linq; namespace slang.Lexing.Trees { public static class TreeExtensions { public static Tree AttachChild(this Tree parent, Tree child) { var parentLeaves = parent.Leaves.ToList (); var childTransitions = child.Root.Transitions.ToList (); parentLeaves.ForEach (parentLeaf => childTransitions.ForEach (childTransition => parentLeaf .Transitions .Add (childTransition.Key, childTransition.Value))); return parent; } public static Tree Merge (this Tree left, Tree right) { var tree = new Tree (); var leftTransitions = left.Root.Transitions.ToList() ; var rightTransitions = right.Root.Transitions.ToList(); var transitions = leftTransitions.Concat (rightTransitions); transitions.ToList ().ForEach (t => tree.Root.Transitions.Add (t.Key, t.Value)); return tree; } } }
Increase version number to 1.1
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
Add extension method to prepend content to a TagHelperContent
namespace BootstrapTagHelpers { using Microsoft.AspNet.Razor.Runtime.TagHelpers; public static class TagHelperContentExtensions { public static void Prepend(this TagHelperContent content, string value) { if (content.IsEmpty) content.SetContent(value); else content.SetContent(value + content.GetContent()); } } }
Fix hang in host tests due to test parallelization
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Xunit; // Disable test parallelization to avoid port reuse issues [assembly: CollectionBehavior(DisableTestParallelization = true)]
Validate Tag Helper registration system functionality.
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using Microsoft.AspNet.Razor.TagHelpers; using Xunit; namespace Microsoft.AspNet.Razor.Test.TagHelpers { public class TagHelperDescriptorProviderTest { [Fact] public void TagHelperDescriptorProvider_GetTagHelpersReturnsNothingForUnregisteredTags() { // Arrange var divDescriptor = new TagHelperDescriptor("div", "foo1", ContentBehavior.None); var spanDescriptor = new TagHelperDescriptor("span", "foo2", ContentBehavior.None); var descriptors = new TagHelperDescriptor[] { divDescriptor, spanDescriptor }; var provider = new TagHelperDescriptorProvider(descriptors); // Act var retrievedDescriptors = provider.GetTagHelpers("foo"); // Assert Assert.Empty(retrievedDescriptors); } [Fact] public void TagHelperDescriptorProvider_GetTagHelpersDoesntReturnNonCatchAllTagsForCatchAll() { // Arrange var divDescriptor = new TagHelperDescriptor("div", "foo1", ContentBehavior.None); var spanDescriptor = new TagHelperDescriptor("span", "foo2", ContentBehavior.None); var catchAllDescriptor = new TagHelperDescriptor("*", "foo3", ContentBehavior.None); var descriptors = new TagHelperDescriptor[] { divDescriptor, spanDescriptor, catchAllDescriptor }; var provider = new TagHelperDescriptorProvider(descriptors); // Act var retrievedDescriptors = provider.GetTagHelpers("*"); // Assert var descriptor = Assert.Single(retrievedDescriptors); Assert.Same(catchAllDescriptor, descriptor); } [Fact] public void TagHelperDescriptorProvider_GetTagHelpersReturnsCatchAllsWithEveryTagName() { // Arrange var divDescriptor = new TagHelperDescriptor("div", "foo1", ContentBehavior.None); var spanDescriptor = new TagHelperDescriptor("span", "foo2", ContentBehavior.None); var catchAllDescriptor = new TagHelperDescriptor("*", "foo3", ContentBehavior.None); var descriptors = new TagHelperDescriptor[] { divDescriptor, spanDescriptor, catchAllDescriptor }; var provider = new TagHelperDescriptorProvider(descriptors); // Act var divDescriptors = provider.GetTagHelpers("div"); var spanDescriptors = provider.GetTagHelpers("span"); // Assert // For divs Assert.Equal(2, divDescriptors.Count()); Assert.Contains(divDescriptor, divDescriptors); Assert.Contains(catchAllDescriptor, divDescriptors); // For spans Assert.Equal(2, spanDescriptors.Count()); Assert.Contains(spanDescriptor, spanDescriptors); Assert.Contains(catchAllDescriptor, spanDescriptors); } [Fact] public void TagHelperDescriptorProvider_DuplicateDescriptorsAreNotPartOfTagHelperDescriptorPool() { // Arrange var divDescriptor = new TagHelperDescriptor("div", "foo1", ContentBehavior.None); var descriptors = new TagHelperDescriptor[] { divDescriptor, divDescriptor }; var provider = new TagHelperDescriptorProvider(descriptors); // Act var retrievedDescriptors = provider.GetTagHelpers("div"); // Assert var descriptor = Assert.Single(retrievedDescriptors); Assert.Same(divDescriptor, descriptor); } } }
Add test for catch hidden mod
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Rulesets.Catch.Mods; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.Objects.Drawables; using osu.Game.Rulesets.Catch.UI; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { public class TestSceneCatchModHidden : ModTestScene { [BackgroundDependencyLoader] private void load() { LocalConfig.Set(OsuSetting.IncreaseFirstObjectVisibility, false); } [Test] public void TestJuiceStream() { CreateModTest(new ModTestData { Beatmap = new Beatmap { HitObjects = new List<HitObject> { new JuiceStream { StartTime = 1000, Path = new SliderPath(PathType.Linear, new[] { Vector2.Zero, new Vector2(0, -192) }), X = CatchPlayfield.WIDTH / 2 } } }, Mod = new CatchModHidden(), PassCondition = () => Player.Results.Count > 0 && Player.ChildrenOfType<DrawableJuiceStream>().Single().Alpha > 0 && Player.ChildrenOfType<DrawableFruit>().Last().Alpha > 0 }); } protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); } }
Add a new interface for the JobService.
// *********************************************************************** // Copyright (c) 2017 Dominik Lachance // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System.Collections.Generic; using System.Threading.Tasks; using YellowJacket.Models; namespace YellowJacket.Dashboard.Services.Interfaces { internal interface IJobService { /// <summary> /// Adds the specified job to the repository. /// </summary> /// <param name="job">The job.</param> /// <returns> /// <see cref="JobModel" />. /// </returns> Task<JobModel> Add(JobModel job); /// <summary> /// Gets all jobs from the repository. /// </summary> /// <returns> /// <see cref="IEnumerable{JobModel}" />. /// </returns> Task<IEnumerable<JobModel>> GetAll(); /// <summary> /// Finds a job by its id. /// </summary> /// <param name="id">The id.</param> /// <returns> /// <see cref="JobModel" />. /// </returns> Task<JobModel> Find(string id); /// <summary> /// Removes the specified job from the repository. /// </summary> /// <param name="id">The id of the job to remove.</param> /// <returns><see cref="Task" />.</returns> Task Remove(string id); /// <summary> /// Updates the specified job. /// </summary> /// <param name="job">The job.</param> /// <returns><see cref="JobModel"/>.</returns> Task<JobModel> Update(JobModel job); } }
Add simple user state class
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.RealtimeMultiplayer { public class MultiplayerClientState { public MultiplayerClientState(in long roomId) { CurrentRoomID = roomId; } public long CurrentRoomID { get; } } }
Create abstract report to simplify creating reports
using KenticoInspector.Core.Models; using System; using System.Collections.Generic; namespace KenticoInspector.Core { public abstract class AbstractReport : IReport { public string Codename => GetCodename(this.GetType()); public static string GetCodename(Type reportType) { return GetDirectParentNamespace(reportType); } public abstract IList<Version> CompatibleVersions { get; } public virtual IList<Version> IncompatibleVersions => new List<Version>(); public abstract IList<string> Tags { get; } public abstract ReportResults GetResults(); private static string GetDirectParentNamespace(Type reportType) { var fullNameSpace = reportType.Namespace; var indexAfterLastPeriod = fullNameSpace.LastIndexOf('.') + 1; return fullNameSpace.Substring(indexAfterLastPeriod, fullNameSpace.Length - indexAfterLastPeriod); } } }
Add new document extensions file
// 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.CodeAnalysis.Editor.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class DocumentExtensions { public static bool IsInCloudEnvironmentClientContext(this Document document) { var workspaceContextService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceContextService>(); return workspaceContextService.IsCloudEnvironmentClient(); } } }
Add metadata class for the compilation root.
namespace slang.Compilation { public class CompilationMetadata { public CompilationMetadata(string projectName) { ProjectName = projectName; } public string ProjectName { get; set; } } }
Revert "moving error view to Shared from Home"
@model System.Exception @{ ViewBag.Title = "Error :)"; } <section class="container"> <div class="row area"> <div class="col-xs-12"> <h1>@ViewBag.Title</h1> <p> Rats, something unfortunate happened. Below you can find some additional, technical information which can be helpful to track down what went wrong. No additional information here? Check out the <a href="~/logs">logs</a> yourself, debug it and send us a <a href="https://github.com/planetpowershell/planetpowershell/pulls">pull request</a>! Or wait for us to do it. </p> @if (Model != null) { <div class="alert alert-warning"> @Model.Message @Model.StackTrace </div> } else { <div class="alert alert-warning"> No additional information is available. </div> } <p>To brighten your life, here is a picture of a Xamarin monkey eating a Death Star waffle!</p> <div class="text-center"> <img src="~/Content/img/deathstar_monkey.jpg" class="img-rounded" title="Awww look at it, it is so cute" alt="Xamarin monkey eating a Death Star waffle to make it all better" /> </div> </div> </div> </section>
Add default LSP initialize handler (for diagnostics).
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LiveShare.LanguageServices; using Microsoft.VisualStudio.LiveShare.LanguageServices.Protocol; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.LiveShare { /// <summary> /// Handle the initialize request and report the capabilities of the server. /// TODO Once the client side code is migrated to LSP client, this can be removed. /// </summary> [ExportLspRequestHandler(LiveShareConstants.RoslynLSPSDKContractName, LSP.Methods.InitializeName)] internal class LSPSDKInitializeHandler : ILspRequestHandler<LSP.InitializeParams, LSP.InitializeResult, Solution> { public Task<LSP.InitializeResult> HandleAsync(LSP.InitializeParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken) { var result = new LSP.InitializeResult { Capabilities = new ServerCapabilities_v40() }; return Task.FromResult(result); } } }
Fix U4-2286 - IFilteredControllerFactory classes are not resolved by Umbraco
using System; using System.Collections.Generic; using Umbraco.Core.ObjectResolution; namespace Umbraco.Web.Mvc { /// <summary> /// A resolver for storing IFilteredControllerFactories /// </summary> internal sealed class FilteredControllerFactoriesResolver : ManyObjectsResolverBase<FilteredControllerFactoriesResolver, IFilteredControllerFactory> { /// <summary> /// Constructor /// </summary> /// <param name="factories"></param> internal FilteredControllerFactoriesResolver(IEnumerable<Type> factories) : base(factories) { } public IEnumerable<IFilteredControllerFactory> Factories { get { return Values; } } } }
using System; using System.Collections.Generic; using Umbraco.Core.ObjectResolution; namespace Umbraco.Web.Mvc { /// <summary> /// A resolver for storing IFilteredControllerFactories /// </summary> public sealed class FilteredControllerFactoriesResolver : ManyObjectsResolverBase<FilteredControllerFactoriesResolver, IFilteredControllerFactory> { /// <summary> /// Constructor /// </summary> /// <param name="factories"></param> internal FilteredControllerFactoriesResolver(IEnumerable<Type> factories) : base(factories) { } public IEnumerable<IFilteredControllerFactory> Factories { get { return Values; } } } }
Add a unit test for the LedgerQueriesExtensions class
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Openchain.Ledger.Tests { public class LedgerQueriesExtensionsTests { private ILedgerQueries store; [Fact] public async Task GetRecordVersion_Success() { this.store = new TestLedgerQueries(CreateTransaction("a", "b")); Record record = await this.store.GetRecordVersion(new ByteString(Encoding.UTF8.GetBytes("b")), ByteString.Parse("1234")); Assert.Equal(new ByteString(Encoding.UTF8.GetBytes("b")), record.Key); Assert.Equal(ByteString.Parse("ab"), record.Value); Assert.Equal(ByteString.Parse("cd"), record.Version); } private ByteString CreateTransaction(params string[] keys) { Mutation mutation = new Mutation( ByteString.Empty, keys.Select(key => new Record( new ByteString(Encoding.UTF8.GetBytes(key)), ByteString.Parse("ab"), ByteString.Parse("cd"))), ByteString.Empty); byte[] serializedMutation = MessageSerializer.SerializeMutation(mutation); Transaction transaction = new Transaction( new ByteString(MessageSerializer.SerializeMutation(mutation)), new DateTime(), ByteString.Empty); return new ByteString(MessageSerializer.SerializeTransaction(transaction)); } private class TestLedgerQueries : ILedgerQueries { private readonly ByteString transaction; public TestLedgerQueries(ByteString transaction) { this.transaction = transaction; } public Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix) { throw new NotImplementedException(); } public Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey) { throw new NotImplementedException(); } public Task<ByteString> GetTransaction(ByteString mutationHash) { return Task.FromResult(this.transaction); } } } }
Fix crashing when OK button is pressed and no subtitle file is selected
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SubtitleRenamer { public partial class ZipFilesForm : Form { private List<string> zipFiles; public string selectedSubtitleFileName; public bool ok; public ZipFilesForm(List<string> zipFiles) { InitializeComponent(); this.zipFiles = zipFiles; } private void ZipFilesForm_Load(object sender, EventArgs e) { ZipListBox.Items.AddRange(zipFiles.ToArray()); } private void SubtitleSelected() { if (ZipListBox.Items.Count == 0) { MessageBox.Show("자막 파일을 선택하세요"); return; } selectedSubtitleFileName = ZipListBox.SelectedItem.ToString(); ok = true; this.Close(); } private void ZipListBox_MouseDoubleClick(object sender, MouseEventArgs e) { SubtitleSelected(); } private void OkButton_Click(object sender, EventArgs e) { SubtitleSelected(); } private void CancelButton_Click(object sender, EventArgs e) { ok = false; this.Close(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SubtitleRenamer { public partial class ZipFilesForm : Form { private List<string> zipFiles; public string selectedSubtitleFileName; public bool ok; public ZipFilesForm(List<string> zipFiles) { InitializeComponent(); this.zipFiles = zipFiles; } private void ZipFilesForm_Load(object sender, EventArgs e) { ZipListBox.Items.AddRange(zipFiles.ToArray()); } private void SubtitleSelected() { if (ZipListBox.SelectedItems.Count == 0) { MessageBox.Show("자막 파일을 선택하세요"); return; } selectedSubtitleFileName = ZipListBox.SelectedItem.ToString(); ok = true; this.Close(); } private void ZipListBox_MouseDoubleClick(object sender, MouseEventArgs e) { SubtitleSelected(); } private void OkButton_Click(object sender, EventArgs e) { SubtitleSelected(); } private void CancelButton_Click(object sender, EventArgs e) { ok = false; this.Close(); } } }
Add a very basic data adapter for building the grid cell views to show those SimpleItem objects.
using Android.Content; using Android.Views; using Android.Widget; namespace GridViewInfiniteScroll { public class MyGridViewAdapter : BaseAdapter<SimpleItem> { private readonly SimpleItemLoader _simpleItemLoader; private readonly Context _context; public MyGridViewAdapter(Context context, SimpleItemLoader simpleItemLoader) { _context = context; _simpleItemLoader = simpleItemLoader; } public override View GetView(int position, View convertView, ViewGroup parent) { var item = _simpleItemLoader.SimpleItems[position]; View itemView = convertView ?? LayoutInflater.From(_context).Inflate(Resource.Layout.GridViewCell, parent, false); var tvDisplayName = itemView.FindViewById<TextView>(Resource.Id.tvDisplayName); var imgThumbail = itemView.FindViewById<ImageView>(Resource.Id.imgThumbnail); imgThumbail.SetScaleType(ImageView.ScaleType.CenterCrop); imgThumbail.SetPadding(8, 8, 8, 8); tvDisplayName.Text = item.DisplayName; imgThumbail.SetImageResource(Resource.Drawable.Icon); return itemView; } public override long GetItemId(int position) { return position; } public override int Count { get { return _simpleItemLoader.SimpleItems.Count; } } public override SimpleItem this[int position] { get { return _simpleItemLoader.SimpleItems[position]; } } } }
Remove tests which are not actual tests but rather stress tests/means to type files automatically
using System.Diagnostics.CodeAnalysis; using System.IO; using FluentAssertions; using Microsoft.R.Editor.Application.Test.TestShell; using Microsoft.R.Editor.ContentType; using Microsoft.R.Support.RD.ContentTypes; using Microsoft.UnitTests.Core.XUnit; using Xunit; namespace Microsoft.R.Editor.Application.Test.Typing { [ExcludeFromCodeCoverage] [Collection(CollectionNames.NonParallel)] public class TypeFileTest { private readonly EditorAppTestFilesFixture _files; public TypeFileTest(EditorAppTestFilesFixture files) { _files = files; } [Test(Skip = "Unstable")] [Category.Interactive] public void TypeFile_R() { string actual = TypeFileInEditor("lsfit-part.r", RContentTypeDefinition.ContentType); string expected = ""; actual.Should().Be(expected); } [Test(Skip="Unstable")] [Category.Interactive] public void TypeFile_RD() { TypeFileInEditor("01.rd", RdContentTypeDefinition.ContentType); } /// <summary> /// Opens file in an editor window /// </summary> /// <param name="fileName">File name</param> /// <param name="contentType">File content type</param> private string TypeFileInEditor(string fileName, string contentType) { using (var script = new TestScript(contentType)) { string text = _files.LoadDestinationFile(fileName); script.Type(text, idleTime: 10); return script.EditorText; } } } }
using System.Diagnostics.CodeAnalysis; using FluentAssertions; using Microsoft.R.Editor.Application.Test.TestShell; using Microsoft.R.Editor.ContentType; using Microsoft.R.Support.RD.ContentTypes; using Microsoft.UnitTests.Core.XUnit; using Xunit; namespace Microsoft.R.Editor.Application.Test.Typing { [ExcludeFromCodeCoverage] [Collection(CollectionNames.NonParallel)] public class TypeFileTest { private readonly EditorAppTestFilesFixture _files; public TypeFileTest(EditorAppTestFilesFixture files) { _files = files; } //[Test(Skip = "Unstable")] //[Category.Interactive] public void TypeFile_R() { string actual = TypeFileInEditor("lsfit-part.r", RContentTypeDefinition.ContentType); string expected = ""; actual.Should().Be(expected); } //[Test(Skip="Unstable")] //[Category.Interactive] public void TypeFile_RD() { TypeFileInEditor("01.rd", RdContentTypeDefinition.ContentType); } /// <summary> /// Opens file in an editor window /// </summary> /// <param name="fileName">File name</param> /// <param name="contentType">File content type</param> private string TypeFileInEditor(string fileName, string contentType) { using (var script = new TestScript(contentType)) { string text = _files.LoadDestinationFile(fileName); script.Type(text, idleTime: 10); return script.EditorText; } } } }
Add models for user profile.
using CompetitionPlatform.Data.AzureRepositories.Project; using CompetitionPlatform.Models.ProjectViewModels; using System; using System.Collections.Generic; namespace CompetitionPlatform.Models.UserProfile { public class UserProfile { public string Id { get; set; } public string UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Website { get; set; } public string Bio { get; set; } public string FacebookLink { get; set; } public string TwitterLink { get; set; } public string GithubLink { get; set; } public bool ReceiveLykkeNewsletter { get; set; } } public class UserProfileViewModel { public UserProfile Profile { get; set; } public double WinningsSum { get; set; } public List<ProjectCompactViewModel> ParticipatedProjects { get; set; } public List<ProjectCompactViewModel> WonProjects { get; set; } public List<ProjectCompactViewModel> CreatedProjects { get; set; } public List<UserProfileCommentData> Comments { get; set; } } public class UserProfileCommentData { public string ProjectName { get; set; } public string ProjectId { get; set; } public string FullName { get; set; } public string Comment { get; set; } public DateTime LastModified { get; set; } } }
Add integration test for entity deletion.
using System.Threading.Tasks; using Content.Server.GameObjects.Components.GUI; using Content.Server.GameObjects.Components.Items.Clothing; using NUnit.Framework; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.Map; using Robust.Shared.IoC; using Robust.Shared.Map; using static Content.Shared.GameObjects.Components.Inventory.EquipmentSlotDefines; namespace Content.IntegrationTests.Tests { [TestFixture] public class DeleteInventoryTest : ContentIntegrationTest { // Test that when deleting an entity with an InventoryComponent, // any equipped items also get deleted. [Test] public async Task Test() { var server = StartServerDummyTicker(); server.Assert(() => { // Spawn everything. var mapMan = IoCManager.Resolve<IMapManager>(); mapMan.CreateNewMapEntity(MapId.Nullspace); var entMgr = IoCManager.Resolve<IEntityManager>(); var container = entMgr.SpawnEntity(null, MapCoordinates.Nullspace); var inv = container.AddComponent<InventoryComponent>(); var child = entMgr.SpawnEntity(null, MapCoordinates.Nullspace); var item = child.AddComponent<ClothingComponent>(); item.SlotFlags = SlotFlags.HEAD; // Equip item. Assert.That(inv.Equip(Slots.HEAD, item, false), Is.True); // Delete parent. container.Delete(); // Assert that child item was also deleted. Assert.That(item.Deleted, Is.True); }); await server.WaitIdleAsync(); } } }
Introduce generic base movement command handler
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; using SceneJect.Common; using UnityEngine; namespace Booma.Proxy { /// <summary> /// Base <see cref="BaseSubCommand60"/> handler for default movement generator /// movement command types. /// </summary> /// <typeparam name="TPositionChangeCommandType">The position changing event.</typeparam> public class BaseDefaultPositionChangedEventHandler<TPositionChangeCommandType> : Command60Handler<TPositionChangeCommandType> where TPositionChangeCommandType : BaseSubCommand60, IMessageContextIdentifiable, IWorldPositionable<float> { /// <summary> /// Service that translates the incoming position to the correct unit scale that /// Unity3D expects. /// </summary> private IUnitScalerStrategy Scaler { get; } private IEntityGuidMappable<WorldTransform> WorldTransformMappable { get; } private IEntityGuidMappable<MovementManager> MovementManagerMappable { get; } /// <inheritdoc /> public BaseDefaultPositionChangedEventHandler([NotNull] IUnitScalerStrategy scaler, ILog logger, IEntityGuidMappable<WorldTransform> worldTransformMappable, [NotNull] IEntityGuidMappable<MovementManager> movementManagerMappable) : base(logger) { Scaler = scaler ?? throw new ArgumentNullException(nameof(scaler)); WorldTransformMappable = worldTransformMappable; MovementManagerMappable = movementManagerMappable ?? throw new ArgumentNullException(nameof(movementManagerMappable)); } /// <inheritdoc /> protected override Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, TPositionChangeCommandType command) { int entityGuid = EntityGuid.ComputeEntityGuid(EntityType.Player, command.Identifier); //We can safely assume they have a known world transform or they can't have been spawned. //It's very possible, if this fails, that they are cheating/hacking or something. Vector2 position = Scaler.ScaleYasZ(command.Position); MovementManagerMappable[entityGuid].RegisterState(CreateMovementGenerator(position)); //New position commands should be direcly updating the entity's position. Even though "MovementGenerators" handle true movement by learping them. //They aren't the source of Truth since they aren't deterministic/authorative like is REAL MMOs. So, the true source of truth is the WorldTransform. Vector3 positionIn3dSpace = new Vector3(position.x, WorldTransformMappable[entityGuid].Position.y, position.y); WorldTransformMappable[entityGuid] = new WorldTransform(positionIn3dSpace, WorldTransformMappable[entityGuid].Rotation); return Task.CompletedTask; } protected virtual IMovementGeneratorState CreateMovementGenerator(Vector2 position) { //By default we use the default. return new DefaultMovementGeneratorState(new DefaultMovementGenerationStateState(position)); } } }
Move reflection initialization eager cctor order above McgModuleManager as it turns out to have a dependency on it in debug mode
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Runtime.CompilerServices { // When applied to a type this custom attribute will cause it's cctor to be executed during startup // rather being deferred.'order' define the order of execution relative to other cctor's marked with the same attribute. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)] sealed public class EagerOrderedStaticConstructorAttribute : Attribute { private EagerStaticConstructorOrder _order; public EagerOrderedStaticConstructorAttribute(EagerStaticConstructorOrder order) { _order = order; } public EagerStaticConstructorOrder Order { get { return _order; } } } // Defines all the types which require eager cctor execution ,defined order is the order of execution.The enum is // grouped by Modules and then by types. public enum EagerStaticConstructorOrder : int { // System.Private.TypeLoader RuntimeTypeHandleEqualityComparer, TypeLoaderEnvironment, SystemRuntimeTypeLoaderExports, // System.Private.CoreLib SystemString, SystemPreallocatedOutOfMemoryException, SystemEnvironment, // ClassConstructorRunner.Cctor.GetCctor use Lock which inturn use current threadID , so System.Environment // should come before CompilerServicesClassConstructorRunnerCctor CompilerServicesClassConstructorRunnerCctor, CompilerServicesClassConstructorRunner, // System.Private.Reflection.Execution ReflectionExecution, // Interop InteropHeap, VtableIUnknown, McgModuleManager } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Runtime.CompilerServices { // When applied to a type this custom attribute will cause it's cctor to be executed during startup // rather being deferred.'order' define the order of execution relative to other cctor's marked with the same attribute. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)] sealed public class EagerOrderedStaticConstructorAttribute : Attribute { private EagerStaticConstructorOrder _order; public EagerOrderedStaticConstructorAttribute(EagerStaticConstructorOrder order) { _order = order; } public EagerStaticConstructorOrder Order { get { return _order; } } } // Defines all the types which require eager cctor execution ,defined order is the order of execution.The enum is // grouped by Modules and then by types. public enum EagerStaticConstructorOrder : int { // System.Private.TypeLoader RuntimeTypeHandleEqualityComparer, TypeLoaderEnvironment, SystemRuntimeTypeLoaderExports, // System.Private.CoreLib SystemString, SystemPreallocatedOutOfMemoryException, SystemEnvironment, // ClassConstructorRunner.Cctor.GetCctor use Lock which inturn use current threadID , so System.Environment // should come before CompilerServicesClassConstructorRunnerCctor CompilerServicesClassConstructorRunnerCctor, CompilerServicesClassConstructorRunner, // Interop InteropHeap, VtableIUnknown, McgModuleManager, // System.Private.Reflection.Execution ReflectionExecution, } }
Add policy for local only requests
using System; using Glimpse.Server.Options; using Glimpse.Web; namespace Glimpse.Server.Framework { public class AllowRemoteSecureRequestPolicy : ISecureRequestPolicy { private readonly IAllowRemoteProvider _allowRemoteProvider; public AllowRemoteSecureRequestPolicy(IAllowRemoteProvider allowRemoteProvider) { _allowRemoteProvider = allowRemoteProvider; } public bool AllowUser(IHttpContext context) { return _allowRemoteProvider.AllowRemote || context.Request.IsLocal; } } }
Add tests for multiple calls
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using RawRabbit.Client; using RawRabbit.IntegrationTests.TestMessages; using Xunit; namespace RawRabbit.IntegrationTests.SimpleUse { public class MultipleRequestsTests { [Fact] public async void Should_Just_Work() { /* Setup */ const int numberOfCalls = 1000; var bag = new ConcurrentBag<Guid>(); var requester = BusClientFactory.CreateDefault(); var responder = BusClientFactory.CreateDefault(); await responder.RespondAsync<FirstRequest, FirstResponse>((req, i) => Task.FromResult(new FirstResponse { Infered = Guid.NewGuid() }) ); /* Test */ var sw = new Stopwatch(); sw.Start(); for (var i = 0; i < numberOfCalls; i++) { var response = await requester.RequestAsync<FirstRequest, FirstResponse>(); bag.Add(response.Infered); } sw.Stop(); /* Assert */ Assert.Equal(numberOfCalls, bag.Count); } } }
Remove DocValues numeric fielddata format
using System.Runtime.Serialization; namespace Nest { public enum NumericFielddataFormat { [EnumMember(Value = "array")] Array, [EnumMember(Value = "doc_values")] DocValues, [EnumMember(Value = "disabled")] Disabled } }
using System.Runtime.Serialization; namespace Nest { public enum NumericFielddataFormat { [EnumMember(Value = "array")] Array, [EnumMember(Value = "disabled")] Disabled } }
Add beatmap availability tracker component for multiplayer
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Bindables; using osu.Game.Beatmaps; namespace osu.Game.Online.Rooms { public class MultiplayerBeatmapTracker : DownloadTrackingComposite<BeatmapSetInfo, BeatmapManager> { public readonly IBindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>(); /// <summary> /// The availability state of the currently selected playlist item. /// </summary> public IBindable<BeatmapAvailability> Availability => availability; private readonly Bindable<BeatmapAvailability> availability = new Bindable<BeatmapAvailability>(); public MultiplayerBeatmapTracker() { State.BindValueChanged(_ => updateAvailability()); Progress.BindValueChanged(_ => updateAvailability()); updateAvailability(); } protected override void LoadComplete() { base.LoadComplete(); SelectedItem.BindValueChanged(item => Model.Value = item.NewValue?.Beatmap.Value.BeatmapSet, true); } protected override bool VerifyDatabasedModel(BeatmapSetInfo databasedSet) { int? beatmapId = SelectedItem.Value.Beatmap.Value.OnlineBeatmapID; string checksum = SelectedItem.Value.Beatmap.Value.MD5Hash; BeatmapInfo matchingBeatmap; if (databasedSet.Beatmaps == null) { // The given databased beatmap set is not passed in a usable state to check with. // Perform a full query instead, as per https://github.com/ppy/osu/pull/11415. matchingBeatmap = Manager.QueryBeatmap(b => b.OnlineBeatmapID == beatmapId && b.MD5Hash == checksum); return matchingBeatmap != null; } matchingBeatmap = databasedSet.Beatmaps.FirstOrDefault(b => b.OnlineBeatmapID == beatmapId && b.MD5Hash == checksum); return matchingBeatmap != null; } protected override bool IsModelAvailableLocally() { int? beatmapId = SelectedItem.Value.Beatmap.Value.OnlineBeatmapID; string checksum = SelectedItem.Value.Beatmap.Value.MD5Hash; var beatmap = Manager.QueryBeatmap(b => b.OnlineBeatmapID == beatmapId && b.MD5Hash == checksum); return beatmap?.BeatmapSet.DeletePending == false; } private void updateAvailability() { switch (State.Value) { case DownloadState.NotDownloaded: availability.Value = BeatmapAvailability.NotDownloaded(); break; case DownloadState.Downloading: availability.Value = BeatmapAvailability.Downloading(Progress.Value); break; case DownloadState.Importing: availability.Value = BeatmapAvailability.Importing(); break; case DownloadState.LocallyAvailable: availability.Value = BeatmapAvailability.LocallyAvailable(); break; default: throw new ArgumentOutOfRangeException(nameof(State)); } } } }
Add base class for path elements that has a good default implementation for Apply on Selection
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Pather.CSharp.PathElements { public abstract class PathElementBase : IPathElement { public Selection Apply(Selection target) { var results = new List<object>(); foreach (var entriy in target.Entries) { results.Add(Apply(entriy)); } var result = new Selection(results); return result; } public abstract object Apply(object target); } }
Add AutoQueryable extension on top of Iqueryable<T>
using System; using System.Linq; using AutoQueryable.Helpers; using AutoQueryable.Models; namespace AutoQueryable.Extensions { public static class QueryableExtension { public static dynamic AutoQueryable(this IQueryable<object> query, string queryString, AutoQueryableProfile profile) { Type entityType = query.GetType().GenericTypeArguments[0]; return QueryableHelper.GetAutoQuery(queryString, entityType, query, profile); } } }
Add the prim count interfaces
/* * 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 OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Region.Framework.Interfaces { public interface IPrimCountModule { void TaintPrimCount(ILandObject land); void TaintPrimCount(int x, int y); void TaintPrimCount(); } public interface IPrimCounts { int Owner { get; } int Group { get; } int Others { get; } int Simulator { get; } IUserPrimCounts Users { get; } } public interface IUserPrimCounts { int this[UUID agentID] { get; } } }
Add basic unit test for SecurityProtocolManager
using Htc.Vita.Core.Net; using Xunit; using Xunit.Abstractions; namespace Htc.Vita.Core.Tests { public class SecurityProtocolManagerTest { private readonly ITestOutputHelper _output; public SecurityProtocolManagerTest(ITestOutputHelper output) { _output = output; } [Fact] public void Default_0_GetAvailableProtocol() { var availableProtocol = SecurityProtocolManager.GetAvailableProtocol(); Assert.NotEqual(0, (int) availableProtocol); _output.WriteLine($@"availableProtocol: {availableProtocol}"); } } }
Add test case covering regression
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Mods; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.UI; using osu.Game.Rulesets.Objects; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Catch.Tests.Mods { public class TestSceneCatchModRelax : ModTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] public void TestModRelax() => CreateModTest(new ModTestData { Mod = new CatchModRelax(), Autoplay = false, PassCondition = () => { var playfield = this.ChildrenOfType<CatchPlayfield>().Single(); InputManager.MoveMouseTo(playfield.ScreenSpaceDrawQuad.Centre); return Player.ScoreProcessor.Combo.Value > 0; }, Beatmap = new Beatmap { HitObjects = new List<HitObject> { new Fruit { X = CatchPlayfield.CENTER_X } } } }); } }
Remove attribute since this is no longer a test code
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Media; namespace Microsoft.Common.Wpf.Extensions { [ExcludeFromCodeCoverage] public static class VisualTreeExtensions { public static T FindChild<T>(DependencyObject o) where T : DependencyObject { if (o is T) { return o as T; } int childrenCount = VisualTreeHelper.GetChildrenCount(o); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(o, i); var inner = FindChild<T>(child); if (inner != null) { return inner; } } return null; } public static T FindNextSibling<T>(DependencyObject o) where T : DependencyObject { var parent = VisualTreeHelper.GetParent(o); int childrenCount = VisualTreeHelper.GetChildrenCount(parent); int i = 0; for (; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child == o) { break; } } i++; for (; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child is T) { return child as T; } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Media; namespace Microsoft.Common.Wpf.Extensions { public static class VisualTreeExtensions { public static T FindChild<T>(DependencyObject o) where T : DependencyObject { if (o is T) { return o as T; } int childrenCount = VisualTreeHelper.GetChildrenCount(o); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(o, i); var inner = FindChild<T>(child); if (inner != null) { return inner; } } return null; } public static T FindNextSibling<T>(DependencyObject o) where T : DependencyObject { var parent = VisualTreeHelper.GetParent(o); int childrenCount = VisualTreeHelper.GetChildrenCount(parent); int i = 0; for (; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child == o) { break; } } i++; for (; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child is T) { return child as T; } } return null; } } }
Fix incorrect title on edit page
@using Orchard.Mvc.Html; @{ Layout.Title = T("New Blog"); } <div class="edit-item"> <div class="edit-item-primary"> @if (Model.Content != null) { <div class="edit-item-content"> @Display(Model.Content) </div> } </div> <div class="edit-item-secondary group"> @if (Model.Actions != null) { <div class="edit-item-actions"> @Display(Model.Actions) </div> } @if (Model.Sidebar != null) { <div class="edit-item-sidebar group"> @Display(Model.Sidebar) </div> } </div> </div>
@using Orchard.Mvc.Html; <div class="edit-item"> <div class="edit-item-primary"> @if (Model.Content != null) { <div class="edit-item-content"> @Display(Model.Content) </div> } </div> <div class="edit-item-secondary group"> @if (Model.Actions != null) { <div class="edit-item-actions"> @Display(Model.Actions) </div> } @if (Model.Sidebar != null) { <div class="edit-item-sidebar group"> @Display(Model.Sidebar) </div> } </div> </div>
Create Message Context Factory interface
using Lidgren.Network; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GladNet.Lidgren.Engine.Common { /// <summary> /// Factory that generates <see cref="LidgrenMessageContext"/>s. /// </summary> public interface ILidgrenMessageContextFactory { /// <summary> /// Indicates if the <see cref="NetIncomingMessageType"/> is a context /// the factory can create. /// </summary> /// <param name="messageType">The message type.</param> /// <returns>True if the context factory can produce a context for that type.</returns> bool CanCreateContext(NetIncomingMessageType messageType); /// <summary> /// Creates a <see cref="LidgrenMessageContext"/> based on the incoming /// <see cref="NetIncomingMessage"/> instance. /// </summary> /// <param name="message"></param> /// <returns>A non-null reference to a derived <see cref="LidgrenMessageContext"/>.</returns> LidgrenMessageContext CreateContext(NetIncomingMessage message); } }
Update server side API for single multiple answer question
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
Add base class for auth tests.
using System; using System.Text; namespace Rnwood.SmtpServer.Tests.Extensions.Auth { public class AuthMechanismTest { protected static bool VerifyBase64Response(string base64, string expectedString) { string decodedString = Encoding.ASCII.GetString(Convert.FromBase64String(base64)); return decodedString.Equals(expectedString); } protected static string EncodeBase64(string asciiString) { return Convert.ToBase64String(Encoding.ASCII.GetBytes(asciiString)); } } }
Add failing test for issue GH-837
using System; using System.Linq; using Marten.Schema; using Marten.Testing.Documents; using Xunit; namespace Marten.Testing.Bugs { public class Bug_837_missing_func_mt_immutable_timestamp_when_initializing_with_new_Schema : IntegratedFixture { [Fact] public void missing_func_mt_immutable_timestamp_when_initializing_with_new_Schema() { var store = DocumentStore.For(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.DatabaseSchemaName = "other1"; _.Connection(ConnectionSource.ConnectionString); }); using (var session = store.OpenSession()) { session.Query<Target>().FirstOrDefault(m => m.DateOffset > DateTimeOffset.Now); } } } }
Add missing unit test file
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using compiler.middleend.ir; namespace NUnit.Tests.Middle_End { [TestFixture] public class InstructionTests { [Test] public void ToStringTest() { var inst1 = new Instruction(IrOps.add, new Operand(Operand.OpType.Constant, 10), new Operand(Operand.OpType.Identifier, 10)); var inst2 = new Instruction(IrOps.add, new Operand(Operand.OpType.Constant, 05), new Operand(inst1)); Assert.AreEqual( inst2.Num.ToString() + " add #5 (" + inst1.Num.ToString() + ")",inst2.ToString()); } } }
Add Extension Methods for WebSocket->IGuild
using System.Collections.Generic; using System.Linq; namespace Discord.WebSocket.Extensions { // TODO: Docstrings public static class GuildExtensions { // Channels public static IGuildChannel GetChannel(this IGuild guild, ulong id) => (guild as SocketGuild).GetChannel(id); public static ITextChannel GetTextChannel(this IGuild guild, ulong id) => (guild as SocketGuild).GetChannel(id) as ITextChannel; public static IEnumerable<ITextChannel> GetTextChannels(this IGuild guild) => (guild as SocketGuild).Channels.Select(c => c as ITextChannel).Where(c => c != null); public static IVoiceChannel GetVoiceChannel(this IGuild guild, ulong id) => (guild as SocketGuild).GetChannel(id) as IVoiceChannel; public static IEnumerable<IVoiceChannel> GetVoiceChannels(this IGuild guild) => (guild as SocketGuild).Channels.Select(c => c as IVoiceChannel).Where(c => c != null); // Users public static IGuildUser GetCurrentUser(this IGuild guild) => (guild as SocketGuild).CurrentUser; public static IGuildUser GetUser(this IGuild guild, ulong id) => (guild as SocketGuild).GetUser(id); public static IEnumerable<IGuildUser> GetUsers(this IGuild guild) => (guild as SocketGuild).Members; public static int GetUserCount(this IGuild guild) => (guild as SocketGuild).MemberCount; public static int GetCachedUserCount(this IGuild guild) => (guild as SocketGuild).DownloadedMemberCount; } }
Revert "Pack nuget on build"
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("Serilog sync for Graylog")] [assembly: AssemblyDescription("The Serilog Graylog Sink project is a sink (basically a writer) for the Serilog logging framework. Structured log events are written to sinks and each sink is responsible for writing it to its own backend, database, store etc. This sink delivers the data to Graylog2, a NoSQL search engine.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Serilog.Sinks.Graylog")] [assembly: AssemblyCopyright("whirlwind432@gmail.com Copyright © 2016")] [assembly: AssemblyCompany("Anton Volkov")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyInformationalVersion("1.0.0-master")] // 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("3466c882-d569-4ca5-8db6-0ea53c5a5c57")] // 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")]
Add test for persisting cached value under different culture.
using ClosedXML.Excel; using NUnit.Framework; using System.IO; using System.Threading; namespace ClosedXML_Tests.Excel.Globalization { [TestFixture] public class GlobalizationTests { [Test] [TestCase("A1*10", "1230")] [TestCase("A1/10", "12.3")] [TestCase("A1&\" cells\"", "123 cells")] [TestCase("A1&\"000\"", "123000")] [TestCase("ISNUMBER(A1)", "True")] [TestCase("ISBLANK(A1)", "False")] [TestCase("DATE(2018,1,28)", "43128")] public void LoadFormulaCachedValue(string formula, object expectedValue) { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("ru-RU"); using (var ms = new MemoryStream()) { using (XLWorkbook book1 = new XLWorkbook()) { var sheet = book1.AddWorksheet("sheet1"); sheet.Cell("A1").Value = 123; sheet.Cell("A2").FormulaA1 = formula; var options = new SaveOptions { EvaluateFormulasBeforeSaving = true }; book1.SaveAs(ms, options); } ms.Position = 0; using (XLWorkbook book2 = new XLWorkbook(ms)) { var ws = book2.Worksheet(1); var storedValueA2 = ws.Cell("A2").ValueCached; Assert.IsTrue(ws.Cell("A2").NeedsRecalculation); Assert.AreEqual(expectedValue, storedValueA2); } } } } }
Add integration test for sitemap.xml
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Integration { using System; using System.Globalization; using System.Net; using System.Threading.Tasks; using System.Xml; using Shouldly; using Xunit; /// <summary> /// A class containing tests for the site map. /// </summary> public class SiteMapTests : IntegrationTest { /// <summary> /// Initializes a new instance of the <see cref="SiteMapTests"/> class. /// </summary> /// <param name="fixture">The fixture to use.</param> public SiteMapTests(HttpServerFixture fixture) : base(fixture) { } [Fact] public async Task Site_Map_Locations_Are_Valid() { XmlNodeList locations; // Act using (var response = await Fixture.Client.GetAsync("sitemap.xml")) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string xml = await response.Content.ReadAsStringAsync(); locations = GetSitemapLocations(xml); } // Assert locations.ShouldNotBeNull(); locations.Count.ShouldBeGreaterThan(0); foreach (XmlNode location in locations) { string url = location.InnerText; Assert.True(Uri.TryCreate(url, UriKind.Absolute, out Uri uri)); uri.Scheme.ShouldBe("https"); uri.Port.ShouldBe(443); uri.Host.ShouldBe("londontravel.martincostello.com"); uri.AbsolutePath.ShouldEndWith("/"); using (var response = await Fixture.Client.GetAsync(uri.PathAndQuery)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } private static XmlNodeList GetSitemapLocations(string xml) { string prefix = "ns"; string uri = "http://www.sitemaps.org/schemas/sitemap/0.9"; var sitemap = new XmlDocument(); sitemap.LoadXml(xml); var nsmgr = new XmlNamespaceManager(sitemap.NameTable); nsmgr.AddNamespace(prefix, uri); string xpath = string.Format(CultureInfo.InvariantCulture, "/{0}:urlset/{0}:url/{0}:loc", prefix); return sitemap.SelectNodes(xpath, nsmgr); } } }
Read file from osz archive.
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; namespace Meowtrix.osuAMT.Training.DataGenerator { class OszArchive : Archive, IDisposable { public ZipArchive archive; public OszArchive(Stream stream) { archive = new ZipArchive(stream, ZipArchiveMode.Read, false); } public void Dispose() => archive.Dispose(); public override Stream OpenFile(string filename) => archive.GetEntry(filename).Open(); public override IEnumerable<Stream> OpenOsuFiles() => archive.Entries.Where(x => x.Name.EndsWith(".osz")).Select(e => e.Open()); } }
Add foundation of integration test runner
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace SimplifiedProtocolTestWpfCore { internal static class IntegrationTest { public static Task<IntegrationTestResult[]> RunAsync(CancellationToken ct) { return Task<IntegrationTestResult[]>.Run(() => RunTestCases(testCases, ct)); } private static IntegrationTestResult[] RunTestCases( IEnumerable<IntegrationTestCase> localTestCases, CancellationToken ct) { return RunTestCases().ToArray(); IEnumerable<IntegrationTestResult> RunTestCases() { foreach (var testCase in localTestCases) { if (ct.IsCancellationRequested) { // Return a failed "cancelled" result only if // there were more test cases to work on. yield return new IntegrationTestResult { Success = false, Messages = new List<string> { "Test run cancelled" }, }; break; } yield return RunTestSafe(testCase); } } } private static IntegrationTestResult RunTestSafe(IntegrationTestCase testCase) { return new IntegrationTestResult { Success = false, TestName = testCase.Name, Messages = new List<string> { "No code to run tests yet" }, }; } private delegate IntegrationTestResult IntegrationTestRunner(string name); private struct IntegrationTestCase { public string Name; public IntegrationTestRunner IntegrationTestRunner; } private static readonly IntegrationTestCase[] testCases = { new IntegrationTestCase { Name = "Dummy test", IntegrationTestRunner = name => { return new IntegrationTestResult(); }, }, }; } }
Fix EventSource test to be aware of ArrayPoolEventSource
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; using System.Diagnostics; using Xunit; using System; namespace BasicEventSourceTests { internal class TestUtilities { /// <summary> /// Confirms that there are no EventSources running. /// </summary> /// <param name="message">Will be printed as part of the Assert</param> public static void CheckNoEventSourcesRunning(string message = "") { var eventSources = EventSource.GetSources(); string eventSourceNames = ""; foreach (var eventSource in EventSource.GetSources()) { if (eventSource.Name != "System.Threading.Tasks.TplEventSource" && eventSource.Name != "System.Diagnostics.Eventing.FrameworkEventSource") { eventSourceNames += eventSource.Name + " "; } } Debug.WriteLine(message); Assert.Equal("", eventSourceNames); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; using System.Diagnostics; using Xunit; using System; namespace BasicEventSourceTests { internal class TestUtilities { /// <summary> /// Confirms that there are no EventSources running. /// </summary> /// <param name="message">Will be printed as part of the Assert</param> public static void CheckNoEventSourcesRunning(string message = "") { var eventSources = EventSource.GetSources(); string eventSourceNames = ""; foreach (var eventSource in EventSource.GetSources()) { if (eventSource.Name != "System.Threading.Tasks.TplEventSource" && eventSource.Name != "System.Diagnostics.Eventing.FrameworkEventSource" && eventSource.Name != "System.Buffers.ArrayPoolEventSource") { eventSourceNames += eventSource.Name + " "; } } Debug.WriteLine(message); Assert.Equal("", eventSourceNames); } } }
Use using when creating game/host.
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Desktop; using osu.Framework.OS; namespace SampleGame { public static class Program { [STAThread] public static void Main() { BasicGameHost host = Host.GetSuitableHost(); host.Load(new osu.Desktop.SampleGame()); host.Run(); } } }
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using osu.Framework.Desktop; using osu.Framework.OS; using osu.Framework; namespace SampleGame { public static class Program { [STAThread] public static void Main() { using (Game game = new osu.Desktop.SampleGame()) using (BasicGameHost host = Host.GetSuitableHost()) { host.Load(game); host.Run(); } } } }
Debug view now displays the camera position and speed.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using MonoGame.Extended.BitmapFonts; namespace Citysim.Views { public class DebugView : IView { public void LoadContent(ContentManager content) { } public void Render(SpriteBatch spriteBatch, Citysim game, GameTime gameTime) { if (!game.debug) return; // Debug mode disabled StringBuilder sb = new StringBuilder(); sb.AppendLine("Citysim " + Citysim.VERSION); sb.AppendLine("Map size " + game.city.world.height + "x" + game.city.world.width); spriteBatch.DrawString(game.font, sb, new Vector2(10, 10), Color.Black, 0F, new Vector2(0,0), 0.5F, SpriteEffects.None, 1.0F); } public void Update(Citysim game, GameTime gameTime) { // F3 toggles debug mode if (KeyboardHelper.IsKeyPressed(Keys.F3)) game.debug = !game.debug; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using MonoGame.Extended.BitmapFonts; namespace Citysim.Views { public class DebugView : IView { public void LoadContent(ContentManager content) { } public void Render(SpriteBatch spriteBatch, Citysim game, GameTime gameTime) { if (!game.debug) return; // Debug mode disabled StringBuilder sb = new StringBuilder(); sb.AppendLine("Citysim " + Citysim.VERSION); sb.AppendLine("Map size " + game.city.world.height + "x" + game.city.world.width); sb.AppendLine("Camera: " + game.camera.position.X + "," + game.camera.position.Y + " [" + game.camera.speed + "]"); spriteBatch.DrawString(game.font, sb, new Vector2(10, 10), Color.Black, 0F, new Vector2(0,0), 0.5F, SpriteEffects.None, 1.0F); } public void Update(Citysim game, GameTime gameTime) { // F3 toggles debug mode if (KeyboardHelper.IsKeyPressed(Keys.F3)) game.debug = !game.debug; } } }
Add readonly in ContextKey property
using System.Web; using MvcMusicStore.Data.Context.Interfaces; namespace MvcMusicStore.Data.Context { public class ContextManager<TContext> : IContextManager<TContext> where TContext : IDbContext, new() { private string ContextKey = "ContextManager.Context"; public ContextManager() { ContextKey = "ContextKey." + typeof(TContext).Name; } public IDbContext GetContext() { if (HttpContext.Current.Items[ContextKey] == null) HttpContext.Current.Items[ContextKey] = new TContext(); return HttpContext.Current.Items[ContextKey] as IDbContext; } public void Finish() { if (HttpContext.Current.Items[ContextKey] != null) (HttpContext.Current.Items[ContextKey] as IDbContext).Dispose(); } } }
using System.Web; using MvcMusicStore.Data.Context.Interfaces; namespace MvcMusicStore.Data.Context { public class ContextManager<TContext> : IContextManager<TContext> where TContext : IDbContext, new() { private readonly string ContextKey; public ContextManager() { ContextKey = "ContextKey." + typeof(TContext).Name; } public IDbContext GetContext() { if (HttpContext.Current.Items[ContextKey] == null) HttpContext.Current.Items[ContextKey] = new TContext(); return HttpContext.Current.Items[ContextKey] as IDbContext; } public void Finish() { if (HttpContext.Current.Items[ContextKey] != null) (HttpContext.Current.Items[ContextKey] as IDbContext).Dispose(); } } }
Use Collection instead of List for consistency
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace Anabi.DataAccess.Ef.DbModels { public class AssetDb : BaseEntity { public string Name { get; set; } public int? AddressId { get; set; } public virtual AddressDb Address { get; set; } public int CategoryId { get; set; } public virtual CategoryDb Category { get; set; } public string Description { get; set; } public int? DecisionId { get; set; } public virtual DecisionDb CurrentDecision { get; set; } public string Identifier { get; set; } public decimal? NecessaryVolume { get; set; } public List<HistoricalStageDb> HistoricalStages { get; set; } = new List<HistoricalStageDb>(); public bool IsDeleted { get; set; } public int? NrOfObjects { get; set; } public string MeasureUnit { get; set; } public string Remarks { get; set; } public virtual ICollection<AssetsFileDb> FilesForAsset { get; set; } public virtual ICollection<AssetStorageSpaceDb> AssetsStorageSpaces { get; set; } public virtual ICollection<AssetDefendantDb> Defendants { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace Anabi.DataAccess.Ef.DbModels { public class AssetDb : BaseEntity { public string Name { get; set; } public int? AddressId { get; set; } public virtual AddressDb Address { get; set; } public int CategoryId { get; set; } public virtual CategoryDb Category { get; set; } public string Description { get; set; } public int? DecisionId { get; set; } public virtual DecisionDb CurrentDecision { get; set; } public string Identifier { get; set; } public decimal? NecessaryVolume { get; set; } public virtual ICollection<HistoricalStageDb> HistoricalStages { get; set; } = new Collection<HistoricalStageDb>(); public bool IsDeleted { get; set; } public int? NrOfObjects { get; set; } public string MeasureUnit { get; set; } public string Remarks { get; set; } public virtual ICollection<AssetsFileDb> FilesForAsset { get; set; } public virtual ICollection<AssetStorageSpaceDb> AssetsStorageSpaces { get; set; } public virtual ICollection<AssetDefendantDb> Defendants { get; set; } } }
Set default time zone to UTC
using System; namespace IntegrationEngine.Model { public class CronTrigger : IHasStringId, IIntegrationJobTrigger { public string Id { get; set; } public string JobType { get; set; } public string CronExpressionString { get; set; } public TimeZoneInfo TimeZone { get; set; } } }
using System; namespace IntegrationEngine.Model { public class CronTrigger : IHasStringId, IIntegrationJobTrigger { public string Id { get; set; } public string JobType { get; set; } public string CronExpressionString { get; set; } TimeZoneInfo _timeZone { get; set; } public TimeZoneInfo TimeZone { get { return _timeZone ?? TimeZoneInfo.Utc; } set { _timeZone = value; } } } }
Use ReflectionOnlyLoad() in the remote proxy reference prober
#if !CORE namespace Nancy.Helpers { using System; using System.Reflection; using Nancy.Extensions; internal class ProxyNancyReferenceProber : MarshalByRefObject { public bool HasReference(AssemblyName assemblyNameForProbing, AssemblyName referenceAssemblyName) { var assemblyForInspection = Assembly.Load(assemblyNameForProbing); return assemblyForInspection.IsReferencing(referenceAssemblyName); } } } #endif
#if !CORE namespace Nancy.Helpers { using System; using System.Reflection; using Nancy.Extensions; internal class ProxyNancyReferenceProber : MarshalByRefObject { public bool HasReference(AssemblyName assemblyNameForProbing, AssemblyName referenceAssemblyName) { var assemblyForInspection = Assembly.ReflectionOnlyLoad(assemblyNameForProbing.Name); return assemblyForInspection.IsReferencing(referenceAssemblyName); } } } #endif
Improve pipeline interface so that StartWith is now static and actually creates the pipeline for us
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using BulkWriter.Pipeline.Internal; using BulkWriter.Pipeline.Steps; namespace BulkWriter.Pipeline { public class EtlPipeline : IEtlPipeline { private readonly Stack<IEtlPipelineStep> _pipelineSteps = new Stack<IEtlPipelineStep>(); public Task ExecuteAsync() { return ExecuteAsync(CancellationToken.None); } public Task ExecuteAsync(CancellationToken cancellationToken) { var finalStep = _pipelineSteps.Pop(); var finalTask = Task.Run(() => finalStep.Run(cancellationToken), cancellationToken); while (_pipelineSteps.Count != 0) { var taskAction = _pipelineSteps.Pop(); Task.Run(() => taskAction.Run(cancellationToken), cancellationToken); } return finalTask; } public IEtlPipelineStep<T, T> StartWith<T>(IEnumerable<T> input) { var etlPipelineSetupContext = new EtlPipelineContext(this, (p, s) => _pipelineSteps.Push(s)); var step = new StartEtlPipelineStep<T>(etlPipelineSetupContext, input); _pipelineSteps.Push(step); return step; } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using BulkWriter.Pipeline.Internal; using BulkWriter.Pipeline.Steps; namespace BulkWriter.Pipeline { public sealed class EtlPipeline : IEtlPipeline { private readonly Stack<IEtlPipelineStep> _pipelineSteps = new Stack<IEtlPipelineStep>(); private EtlPipeline() { } public Task ExecuteAsync() { return ExecuteAsync(CancellationToken.None); } public Task ExecuteAsync(CancellationToken cancellationToken) { var finalStep = _pipelineSteps.Pop(); var finalTask = Task.Run(() => finalStep.Run(cancellationToken), cancellationToken); while (_pipelineSteps.Count != 0) { var taskAction = _pipelineSteps.Pop(); Task.Run(() => taskAction.Run(cancellationToken), cancellationToken); } return finalTask; } public static IEtlPipelineStep<T, T> StartWith<T>(IEnumerable<T> input) { var pipeline = new EtlPipeline(); var etlPipelineSetupContext = new EtlPipelineContext(pipeline, (p, s) => pipeline._pipelineSteps.Push(s)); var step = new StartEtlPipelineStep<T>(etlPipelineSetupContext, input); pipeline._pipelineSteps.Push(step); return step; } } }
Address an issue blocks query provider parameters being sent.
using Moegirlpedia.MediaWikiInterop.Primitives.Action.Models; using Moegirlpedia.MediaWikiInterop.Primitives.Foundation; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Moegirlpedia.MediaWikiInterop.Primitives.Transform { public class QueryRequestSerializer : IRequestSerializer<QueryInputModel> { public Task<HttpContent> SerializeRequestAsync(QueryInputModel content, CancellationToken ctkn = default(CancellationToken)) { if (content == null) throw new ArgumentNullException(nameof(content)); return Task.Factory.StartNew<HttpContent>(() => { // Intermediate Key-Value pair var kvPairs = new List<KeyValuePair<string, string>>(); // Query providers kvPairs.AddRange(content.m_queryProviders.SelectMany(k => k.ToKeyValuePairCollection())); // Base parameters kvPairs.AddRange(content.ToKeyValuePairCollection()); // Set Raw continuation to true kvPairs.Add(new KeyValuePair<string, string>("rawcontinue", "1")); // Add format config kvPairs.AddRange(JsonFormatConfig.FormatConfig); return new FormUrlEncodedContent(kvPairs); }, ctkn); } } }
using Moegirlpedia.MediaWikiInterop.Primitives.Action.Models; using Moegirlpedia.MediaWikiInterop.Primitives.Foundation; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Reflection; using Moegirlpedia.MediaWikiInterop.Primitives.Foundation.Query; namespace Moegirlpedia.MediaWikiInterop.Primitives.Transform { public class QueryRequestSerializer : IRequestSerializer<QueryInputModel> { public Task<HttpContent> SerializeRequestAsync(QueryInputModel content, CancellationToken ctkn = default(CancellationToken)) { if (content == null) throw new ArgumentNullException(nameof(content)); return Task.Factory.StartNew<HttpContent>(() => { return new FormUrlEncodedContent(GetKeyPairs(content)); }, ctkn); } internal List<KeyValuePair<string, string>> GetKeyPairs(QueryInputModel content) { // Intermediate Key-Value pair var kvPairs = new List<KeyValuePair<string, string>>(); // Query providers kvPairs.AddRange(content.m_queryProviders.SelectMany(k => k.GetParameters())); // Query providers meta kvPairs.AddRange(content.m_queryProviders.Select(i => i.GetType().GetTypeInfo().GetCustomAttribute<QueryProviderAttribute>()) .GroupBy(i => i.Category) .Select(i => new KeyValuePair<string, string>(i.Key, string.Join("|", i.Select(a => a.Name))))); // Base parameters kvPairs.AddRange(content.ToKeyValuePairCollection()); // Set Raw continuation to true kvPairs.Add(new KeyValuePair<string, string>("rawcontinue", "1")); // Add format config kvPairs.AddRange(JsonFormatConfig.FormatConfig); return kvPairs; } } }
Make the intent clearer to accept bodyless PROPFIND
using Microsoft.AspNetCore.Mvc.Formatters; namespace FubarDev.WebDavServer.AspNetCore.Formatters { public class WebDavXmlSerializerInputFormatter : XmlSerializerInputFormatter { public override bool CanRead(InputFormatterContext context) { var request = context.HttpContext.Request; if (request.ContentType == null) { var contentLength = request.ContentLength; if (request.Method == "PROPFIND" && contentLength.HasValue && contentLength.Value == 0) { return true; } } return base.CanRead(context); } } }
using Microsoft.AspNetCore.Mvc.Formatters; namespace FubarDev.WebDavServer.AspNetCore.Formatters { public class WebDavXmlSerializerInputFormatter : XmlSerializerInputFormatter { public override bool CanRead(InputFormatterContext context) { var request = context.HttpContext.Request; if (request.ContentType == null) { var contentLength = request.ContentLength; if (contentLength.HasValue && contentLength.Value == 0) { switch (request.Method) { case "PROPFIND": return true; } } } return base.CanRead(context); } } }
CHANGE CONFIG TO PRODUCTION !!!
using ApiApp.Models; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Configuration; namespace ApiApp.MongoAccess { static class MongoUtil { #region Fields private static IMongoClient _client; private static IMongoDatabase _database; #endregion Fields #region Constructors static MongoUtil() { // Production config //var connectionString = WebConfigurationManager.AppSettings["primaryConnectionString"]; //_client = new MongoClient(connectionString); //var dbName = WebConfigurationManager.AppSettings["primaryDatabaseName"]; // Test config var connectionString = WebConfigurationManager.AppSettings["testConnectionString"]; _client = new MongoClient(connectionString); var dbName = WebConfigurationManager.AppSettings["testDatabaseName"]; _database = _client.GetDatabase(dbName); } #endregion Constructors #region Methods /// <summary> /// ดึงข้อมูลจากตาราง /// </summary> /// <typeparam name="T">ข้อมูลที่ทำงานด้วย</typeparam> /// <param name="tableName">ชื่อตาราง</param> public static IMongoCollection<T> GetCollection<T>(string tableName) { return _database.GetCollection<T>(tableName); } #endregion Methods } }
using ApiApp.Models; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Configuration; namespace ApiApp.MongoAccess { static class MongoUtil { #region Fields private static IMongoClient _client; private static IMongoDatabase _database; #endregion Fields #region Constructors static MongoUtil() { // Production config var connectionString = WebConfigurationManager.AppSettings["primaryConnectionString"]; _client = new MongoClient(connectionString); var dbName = WebConfigurationManager.AppSettings["primaryDatabaseName"]; // Test config //var connectionString = WebConfigurationManager.AppSettings["testConnectionString"]; //_client = new MongoClient(connectionString); //var dbName = WebConfigurationManager.AppSettings["testDatabaseName"]; _database = _client.GetDatabase(dbName); } #endregion Constructors #region Methods /// <summary> /// ดึงข้อมูลจากตาราง /// </summary> /// <typeparam name="T">ข้อมูลที่ทำงานด้วย</typeparam> /// <param name="tableName">ชื่อตาราง</param> public static IMongoCollection<T> GetCollection<T>(string tableName) { return _database.GetCollection<T>(tableName); } #endregion Methods } }
Remove "register for more config choices"
<div ng-controller="UnregisteredDashboardController"> <div> <h2>Regular Poller?</h2> Register for more config choices. It's free! </div> <form name="quickPollForm" ng-submit="createPoll(pollQuestion)"> <div id="question-block"> Your Question <br /> <input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required /> </div> <div id="quickpoll-block"> <button type="submit" class="active-btn btn-medium shadowed" ng-disabled="quickPollForm.$invalid">Quick Poll</button> </div> </form> <h3 class="centered-text horizontal-ruled">or</h3> <div id="register-block"> <button class="active-btn btn-medium shadowed pull-left" ng-click="openLoginDialog()">Sign In</button> <button class="active-btn btn-medium shadowed pull-right" ng-click="openRegisterDialog()">Register</button> </div> </div>
<div ng-controller="UnregisteredDashboardController"> <form name="quickPollForm" ng-submit="createPoll(pollQuestion)"> <div id="question-block"> Your Question <br /> <input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required /> </div> <div id="quickpoll-block"> <button type="submit" class="active-btn btn-medium shadowed" ng-disabled="quickPollForm.$invalid">Quick Poll</button> </div> </form> <h3 class="centered-text horizontal-ruled">or</h3> <div id="register-block"> <button class="active-btn btn-medium shadowed pull-left" ng-click="openLoginDialog()">Sign In</button> <button class="active-btn btn-medium shadowed pull-right" ng-click="openRegisterDialog()">Register</button> </div> </div>
Correct regex to match only full words
using System; using System.Reflection; using System.Text.RegularExpressions; using InfluxData.Net.Common; using System.Linq; namespace InfluxData.Net.InfluxDb.Helpers { public static class QueryHelpers { public static string BuildParameterizedQuery(string query, object param) { var paramRegex = "@([A-Za-z0-9åäöÅÄÖ'_-]+)"; var matches = Regex.Matches(query, paramRegex); Type t = param.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach(Match match in matches) { if (!pi.Any(x => match.Groups[0].Value.Contains(x.Name))) throw new ArgumentException($"Missing parameter value for {match.Groups[0].Value}"); } foreach (var propertyInfo in pi) { var paramValue = propertyInfo.GetValue(param); var paramType = paramValue.GetType(); if(!paramType.IsPrimitive && paramType != typeof(String)) throw new NotSupportedException($"The type {paramType.Name} is not a supported query parameter type."); var sanitizedParamValue = paramValue; if(paramType == typeof(String)) { sanitizedParamValue = ((string)sanitizedParamValue).Sanitize(); } while (Regex.IsMatch(query, $"@{propertyInfo.Name}")) { var match = Regex.Match(query, $"@{propertyInfo.Name}"); query = query.Remove(match.Index, match.Length); query = query.Insert(match.Index, $"{sanitizedParamValue}"); } } return query; } } }
using System; using System.Reflection; using System.Text.RegularExpressions; using InfluxData.Net.Common; using System.Linq; namespace InfluxData.Net.InfluxDb.Helpers { public static class QueryHelpers { public static string BuildParameterizedQuery(string query, object param) { Type t = param.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach (var propertyInfo in pi) { var regex = $@"@{propertyInfo.Name}(?!\w)"; if(!Regex.IsMatch(query, regex) && Nullable.GetUnderlyingType(propertyInfo.GetType()) != null) throw new ArgumentException($"Missing parameter identifier for @{propertyInfo.Name}"); var paramValue = propertyInfo.GetValue(param); if (paramValue == null) continue; var paramType = paramValue.GetType(); if (!paramType.IsPrimitive && paramType != typeof(String) && paramType != typeof(DateTime)) throw new NotSupportedException($"The type {paramType.Name} is not a supported query parameter type."); var sanitizedParamValue = paramValue; if (paramType == typeof(String)) { sanitizedParamValue = ((string)sanitizedParamValue).Sanitize(); } while (Regex.IsMatch(query, regex)) { var match = Regex.Match(query, regex); query = query.Remove(match.Index, match.Length); query = query.Insert(match.Index, $"{sanitizedParamValue}"); } } return query; } } }
Add test to prove that OnActivation is syncronous
namespace FunWithNinject.Initialization { using Ninject; using NUnit.Framework; [TestFixture] public class Tests { [Test] public void OnActivation_CanCallMethodOnImplementation() { // Assemble var k = new StandardKernel(); k.Bind<IInitializable>() .To<Initializable>() .OnActivation(i => i.CallMe()); // Act var initted = k.Get<IInitializable>(); // Assert Assert.IsTrue(((Initializable)initted).CalledMe); } [Test] public void OnActivation_CanCallMethodOnInterface() { // Assemble var k = new StandardKernel(); k.Bind<IInitializable>() .To<Initializable>() .OnActivation(i => i.Init()); // Act var initted = k.Get<IInitializable>(); // Assert Assert.IsTrue(initted.IsInit); } } }
namespace FunWithNinject.Initialization { using Ninject; using NUnit.Framework; using System.Threading; [TestFixture] public class Tests { [Test] public void OnActivation_CanCallMethodOnImplementation() { // Assemble var k = new StandardKernel(); k.Bind<IInitializable>() .To<Initializable>() .OnActivation(i => i.CallMe()); // Act var initted = k.Get<IInitializable>(); // Assert Assert.IsTrue(((Initializable)initted).CalledMe); } [Test] public void OnActivation_CanCallMethodOnInterface() { // Assemble var k = new StandardKernel(); k.Bind<IInitializable>() .To<Initializable>() .OnActivation(i => i.Init()); // Act var initted = k.Get<IInitializable>(); // Assert Assert.IsTrue(initted.IsInit); } [Test] public void OnActivation_RunsSyncrhonously() { var currentId = Thread.CurrentThread.ManagedThreadId; var k = new StandardKernel(); k.Bind<IFoo>() .To<Foo>() .OnActivation(i => { Assert.AreEqual(currentId, Thread.CurrentThread.ManagedThreadId); }); } } }
Add same type twices adds 2 operations to pending
//----------------------------------------------------------------------- // <copyright file="EventWindowTest.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TraceAnalysisSample.Test.Unit { using System; using System.Threading.Tasks; using Xunit; public class EventWindowTest { public EventWindowTest() { } [Fact] public void Add_adds_operation_to_pending() { EventWindow window = new EventWindow(); int eventId = 1; Guid instanceId = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1); window.Add(eventId, instanceId); Assert.Equal(1, window.GetPendingCount(eventId)); } } }
//----------------------------------------------------------------------- // <copyright file="EventWindowTest.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TraceAnalysisSample.Test.Unit { using System; using System.Threading.Tasks; using Xunit; public class EventWindowTest { public EventWindowTest() { } [Fact] public void Add_adds_operation_to_pending() { EventWindow window = new EventWindow(); int eventId = 1; Guid instanceId = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1); window.Add(eventId, instanceId); Assert.Equal(1, window.GetPendingCount(eventId)); } [Fact] public void Add_same_type_twices_adds_2_operations_to_pending() { EventWindow window = new EventWindow(); int eventId = 1; Guid instanceId1 = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1); Guid instanceId2 = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2); window.Add(eventId, instanceId1); window.Add(eventId, instanceId2); Assert.Equal(2, window.GetPendingCount(eventId)); } } }
Copy changes and companies house link on the company search page
@{ViewBag.Title = "Search for your organisation"; } <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge">Search for your organisation</h1> <p>Use the companies house number for an organisation that your apprentices will be employed through.</p> <form method="POST" action="@Url.Action("SelectEmployer")"> <div class="form-group @(TempData["companyNumberError"] != null ? "error" : "")"> @Html.AntiForgeryToken() <label class="form-label" for="EmployerRef">Companies House number</label> @if (TempData["companyNumberError"] != null) { <legend> <span class="error-message">@TempData["companyNumberError"]</span> </legend> } <input class="form-control form-control-3-4" id="EmployerRef" name="EmployerRef" type="text" aria-required="true"/> </div> <button type="submit" class="button" id="submit">Continue</button> </form> </div> </div> @section breadcrumb { <div class="breadcrumbs"> <ol> <li><a href="/" class="back-link">Back to Your User Profile</a></li> </ol> </div> }
@{ViewBag.Title = "Search for your organisation"; } <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-xlarge">Enter Companies House number</h1> <p>Use the Companies House number for an organisation that your apprentices will be employed through.</p> <p><a href="https://beta.companieshouse.gov.uk/" rel="external" target="_blank">Find my Companies House number</a></p> <form method="POST" action="@Url.Action("SelectEmployer")"> <div class="form-group @(TempData["companyNumberError"] != null ? "error" : "")"> @Html.AntiForgeryToken() <label class="form-label" for="EmployerRef">Companies House number</label> @if (TempData["companyNumberError"] != null) { <legend> <span class="error-message">@TempData["companyNumberError"]</span> </legend> } <input class="form-control form-control-3-4" id="EmployerRef" name="EmployerRef" type="text" aria-required="true"/> </div> <button type="submit" class="button" id="submit">Continue</button> </form> </div> </div> @section breadcrumb { <div class="breadcrumbs"> <ol> <li><a href="/" class="back-link">Back to Your User Profile</a></li> </ol> </div> }
Change bar chart type to bar instead of pie
using ChartJS.NET.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChartJS.NET.Charts.Bar { public class BarChart : BaseChart<BarDataSet, BarChartOptions> { private readonly BarChartOptions _barChartOptions = new BarChartOptions(); public override Enums.ChartTypes ChartType { get { return Enums.ChartTypes.Pie; } } public override BarChartOptions ChartConfig { get { return _barChartOptions; } } } }
using ChartJS.NET.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChartJS.NET.Charts.Bar { public class BarChart : BaseChart<BarDataSet, BarChartOptions> { private readonly BarChartOptions _barChartOptions = new BarChartOptions(); public override Enums.ChartTypes ChartType { get { return Enums.ChartTypes.Bar; } } public override BarChartOptions ChartConfig { get { return _barChartOptions; } } } }
Revert "new capabilites, minor version"
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MonJobs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonJobs")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("763b7fef-ff24-407d-8dce-5313e6129941")] // 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.13.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MonJobs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonJobs")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("763b7fef-ff24-407d-8dce-5313e6129941")] // 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.12.1.0")]
Fix zero being interpreted as 1/1/1970 instead of DateTime.MinValue
using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Curse.NET { internal class MillisecondEpochConverter : DateTimeConverterBase { private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteRawValue(((int)(((DateTime)value - epoch).TotalMilliseconds)).ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value == null) { return DateTime.MinValue; } return epoch.AddMilliseconds((long)reader.Value); } } internal class NullableIntConverter : DateTimeConverterBase { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteRawValue(((int)value).ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value == null) { return 0; } // Double cast is necessary to convert a boxed long first to a long, then to an int. return (int)(long)reader.Value; } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Curse.NET { internal class MillisecondEpochConverter : DateTimeConverterBase { private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteRawValue(((int)(((DateTime)value - epoch).TotalMilliseconds)).ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value == null || (long) reader.Value == 0) { return DateTime.MinValue; } return epoch.AddMilliseconds((long)reader.Value); } } /// <summary> /// Converter for JSON integer properties that are set to null when they should've been set to zero. /// </summary> internal class NullableIntConverter : DateTimeConverterBase { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteRawValue(((int)value).ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value == null) { return 0; } // Double cast is necessary to convert a boxed long first to a long, then to an int. return (int)(long)reader.Value; } } }
Add better exceptions for invalid keys
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; namespace ShiftDrive { /// <summary> /// A simple static container, for holding game assets like textures and meshes. /// </summary> internal static class Assets { public static SpriteFont fontDefault, fontBold; public static readonly Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>(); public static Model mdlSkybox; public static Effect fxUnlit; public static SoundEffect sndUIConfirm, sndUICancel, sndUIAppear1, sndUIAppear2, sndUIAppear3, sndUIAppear4; public static Texture2D GetTexture(string name) { return textures[name.ToLowerInvariant()]; } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; namespace ShiftDrive { /// <summary> /// A simple static container, for holding game assets like textures and meshes. /// </summary> internal static class Assets { public static SpriteFont fontDefault, fontBold; public static readonly Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>(); public static Model mdlSkybox; public static Effect fxUnlit; public static SoundEffect sndUIConfirm, sndUICancel, sndUIAppear1, sndUIAppear2, sndUIAppear3, sndUIAppear4; public static Texture2D GetTexture(string name) { if (!textures.ContainsKey(name.ToLowerInvariant())) throw new KeyNotFoundException("Texture '" + name + "' was not found."); return textures[name.ToLowerInvariant()]; } } }
Change color of tank for debug purposes
namespace Game { using UnityEngine; [RequireComponent(typeof(Collider))] public class Tank : MonoBehaviour { public PlayerController player; [Range(10f, 1000f)] public float max = 100f; [Range(0.1f, 20f)] public float leakRatePerSecond = 2f; [ReadOnly] private float current = 0f; public bool isLeaking { get; set; } private void OnEnable() { this.name = string.Concat("Player ", this.player.playerIndex, " Tank"); this.current = this.max; } private void Update() { if (!this.isLeaking) { return; } this.current -= 1f / this.leakRatePerSecond; if (this.current <= 0f) { this.player.Die(); this.enabled = false; } } private void OnCollisionEnter(Collision collision) { if (this.isLeaking) { return; } var other = collision.gameObject; if (((1 << other.layer) & Layers.instance.playerLayer) == 0) { // not a player return; } Debug.Log(this.ToString() + " start leaking"); this.isLeaking = true; } } }
namespace Game { using UnityEngine; [RequireComponent(typeof(Collider))] public class Tank : MonoBehaviour { public PlayerController player; [Range(10f, 1000f)] public float max = 100f; [Range(0.1f, 20f)] public float leakRatePerSecond = 2f; [ReadOnly] private float current = 0f; public bool isLeaking { get; set; } private void OnEnable() { this.name = string.Concat("Player ", this.player.playerIndex, " Tank"); this.current = this.max; } private void Update() { if (!this.isLeaking) { return; } this.current -= 1f / this.leakRatePerSecond; if (this.current <= 0f) { this.player.Die(); this.enabled = false; } // TODO: Debug ONLY var frac = this.current / this.max; this.GetComponent<Renderer>().material.color = new Color(frac, frac, frac); } private void OnCollisionEnter(Collision collision) { if (this.isLeaking) { return; } var other = collision.gameObject; if (((1 << other.layer) & Layers.instance.playerLayer) == 0) { // not a player return; } Debug.Log(this.ToString() + " start leaking"); this.isLeaking = true; } } }
Add caching to the GetBudgetsAsync method
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using YnabApi.Files; using YnabApi.Helpers; namespace YnabApi { public class YnabApi { private readonly IFileSystem _fileSystem; public YnabApi(IFileSystem fileSystem) { this._fileSystem = fileSystem; } public async Task<IList<Budget>> GetBudgetsAsync() { string ynabSettingsFilePath = YnabPaths.YnabSettingsFile(); var ynabSettingsJson = await this._fileSystem.ReadFileAsync(ynabSettingsFilePath); var ynabSettings = JObject.Parse(ynabSettingsJson); string relativeBudgetsFolder = ynabSettings.Value<string>("relativeDefaultBudgetsFolder"); return ynabSettings .Value<JArray>("relativeKnownBudgets") .Values() .Select(f => f.Value<string>()) .Select(f => new Budget(this._fileSystem, this.ExtractBudgetName(f, relativeBudgetsFolder), f)) .ToArray(); } private string ExtractBudgetName(string budgetPath, string budgetsFolderPath) { var regex = new Regex(budgetsFolderPath + "/(.*)~.*"); if (regex.IsMatch(budgetPath)) return regex.Match(budgetPath).Groups[1].Value; return budgetPath; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using YnabApi.Files; using YnabApi.Helpers; namespace YnabApi { public class YnabApi { private readonly IFileSystem _fileSystem; private Lazy<Task<IList<Budget>>> _cachedBudgets; public YnabApi(IFileSystem fileSystem) { this._fileSystem = fileSystem; } public Task<IList<Budget>> GetBudgetsAsync() { if (this._cachedBudgets == null) { this._cachedBudgets = new Lazy<Task<IList<Budget>>>(async () => { string ynabSettingsFilePath = YnabPaths.YnabSettingsFile(); var ynabSettingsJson = await this._fileSystem.ReadFileAsync(ynabSettingsFilePath); var ynabSettings = JObject.Parse(ynabSettingsJson); string relativeBudgetsFolder = ynabSettings.Value<string>("relativeDefaultBudgetsFolder"); return ynabSettings .Value<JArray>("relativeKnownBudgets") .Values() .Select(f => f.Value<string>()) .Select(f => new Budget(this._fileSystem, this.ExtractBudgetName(f, relativeBudgetsFolder), f)) .ToArray(); }); } return this._cachedBudgets.Value; } private string ExtractBudgetName(string budgetPath, string budgetsFolderPath) { var regex = new Regex(budgetsFolderPath + "/(.*)~.*"); if (regex.IsMatch(budgetPath)) return regex.Match(budgetPath).Groups[1].Value; return budgetPath; } } }
Add filter property to popular shows request.
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common { using Base.Get; using Objects.Basic; using Objects.Get.Shows; internal class TraktShowsPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktShow>, TraktShow> { internal TraktShowsPopularRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "shows/popular{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common { using Base; using Base.Get; using Objects.Basic; using Objects.Get.Shows; internal class TraktShowsPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktShow>, TraktShow> { internal TraktShowsPopularRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "shows/popular{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internal TraktShowFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
Revert "NR Improve display of version number"
using Waf.NewsReader.Applications.Services; using Xamarin.Essentials; namespace Waf.NewsReader.Presentation.Services { public class AppInfoService : IAppInfoService { public AppInfoService() { AppName = AppInfo.Name; VersionString = AppInfo.VersionString + "." + AppInfo.BuildString; } public string AppName { get; } public string VersionString { get; } } }
using Waf.NewsReader.Applications.Services; using Xamarin.Essentials; namespace Waf.NewsReader.Presentation.Services { public class AppInfoService : IAppInfoService { public AppInfoService() { AppName = AppInfo.Name; VersionString = AppInfo.VersionString; } public string AppName { get; } public string VersionString { get; } } }
Add additional test case for package versions
using NUnit.Framework; using Rant.Resources; namespace Rant.Tests { [TestFixture] public class PackageVersions { [TestCase("1.2.5", "1.2.4", true)] [TestCase("0.2.5", "0.2.4", true)] [TestCase("0.0.3", "0.0.4", false)] [TestCase("0.3.1", "0.4.0", false)] public void VersionGreaterThan(string v1, string v2, bool expactedResult) { Assert.IsTrue(RantPackageVersion.Parse(v1) > RantPackageVersion.Parse(v2) == expactedResult, $"Expected {expactedResult}"); } [TestCase("2.2.1", "2.2.4", true)] [TestCase("0.2.3", "0.2.4", true)] [TestCase("1.3.0", "0.5.4", false)] public void VersionLessThan(string v1, string v2, bool expectedResult) { Assert.IsTrue(RantPackageVersion.Parse(v1) < RantPackageVersion.Parse(v2) == expectedResult, $"Expected {expectedResult}"); } } }
using NUnit.Framework; using Rant.Resources; namespace Rant.Tests { [TestFixture] public class PackageVersions { [TestCase("1.2.5", "1.2.4", true)] [TestCase("0.2.5", "0.2.4", true)] [TestCase("0.0.3", "0.0.4", false)] [TestCase("0.3.1", "0.4.0", false)] public void VersionGreaterThan(string v1, string v2, bool expactedResult) { Assert.IsTrue(RantPackageVersion.Parse(v1) > RantPackageVersion.Parse(v2) == expactedResult, $"Expected {expactedResult}"); } [TestCase("2.2.1", "2.2.4", true)] [TestCase("3.2.1", "2.1.4", false)] [TestCase("0.2.3", "0.2.4", true)] [TestCase("1.3.0", "0.5.4", false)] public void VersionLessThan(string v1, string v2, bool expectedResult) { Assert.IsTrue(RantPackageVersion.Parse(v1) < RantPackageVersion.Parse(v2) == expectedResult, $"Expected {expectedResult}"); } } }
FIX logger variable in PS scripts
using System.Collections.Generic; using System.Management.Automation.Runspaces; using Aggregator.Core.Interfaces; using Aggregator.Core.Monitoring; namespace Aggregator.Core { /// <summary> /// Invokes Powershell scripting engine /// </summary> public class PsScriptEngine : ScriptEngine { private readonly Dictionary<string, string> scripts = new Dictionary<string, string>(); public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug) : base(store, logger, debug) { } public override bool Load(string scriptName, string script) { this.scripts.Add(scriptName, script); return true; } public override bool LoadCompleted() { return true; } public override void Run(string scriptName, IWorkItem workItem) { string script = this.scripts[scriptName]; var config = RunspaceConfiguration.Create(); using (var runspace = RunspaceFactory.CreateRunspace(config)) { runspace.Open(); runspace.SessionStateProxy.SetVariable("self", workItem); runspace.SessionStateProxy.SetVariable("store", this.Store); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(script); // execute var results = pipeline.Invoke(); this.Logger.ResultsFromScriptRun(scriptName, results); } } } }
using System.Collections.Generic; using System.Management.Automation.Runspaces; using Aggregator.Core.Interfaces; using Aggregator.Core.Monitoring; namespace Aggregator.Core { /// <summary> /// Invokes Powershell scripting engine /// </summary> public class PsScriptEngine : ScriptEngine { private readonly Dictionary<string, string> scripts = new Dictionary<string, string>(); public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug) : base(store, logger, debug) { } public override bool Load(string scriptName, string script) { this.scripts.Add(scriptName, script); return true; } public override bool LoadCompleted() { return true; } public override void Run(string scriptName, IWorkItem workItem) { string script = this.scripts[scriptName]; var config = RunspaceConfiguration.Create(); using (var runspace = RunspaceFactory.CreateRunspace(config)) { runspace.Open(); runspace.SessionStateProxy.SetVariable("self", workItem); runspace.SessionStateProxy.SetVariable("store", this.Store); runspace.SessionStateProxy.SetVariable("logger", this.Logger); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(script); // execute var results = pipeline.Invoke(); this.Logger.ResultsFromScriptRun(scriptName, results); } } } }
Make statically typed numeric generation distinct
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace FreecraftCore.Serializer { public class RootSerializationMethodBlockEmitter<TSerializableType> : IMethodBlockEmittable, INestedClassesEmittable where TSerializableType : new() { public BlockSyntax CreateBlock() { //TODO: Figure out how we should decide which strategy to use, right now only simple and flat are supported. //TSerializableType return new FlatComplexTypeSerializationMethodBlockEmitter<TSerializableType>() .CreateBlock(); } public IEnumerable<ClassDeclarationSyntax> CreateClasses() { //Find all KnownSize types and emit classes for each one foreach (var mi in typeof(TSerializableType) .GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { KnownSizeAttribute sizeAttribute = mi.GetCustomAttribute<KnownSizeAttribute>(); if (sizeAttribute == null) continue; //This creates a class declaration for the int static type. yield return new StaticlyTypedIntegerGenericTypeClassEmitter<int>(sizeAttribute.KnownSize) .Create(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace FreecraftCore.Serializer { public class RootSerializationMethodBlockEmitter<TSerializableType> : IMethodBlockEmittable, INestedClassesEmittable where TSerializableType : new() { public BlockSyntax CreateBlock() { //TODO: Figure out how we should decide which strategy to use, right now only simple and flat are supported. //TSerializableType return new FlatComplexTypeSerializationMethodBlockEmitter<TSerializableType>() .CreateBlock(); } public IEnumerable<ClassDeclarationSyntax> CreateClasses() { SortedSet<int> alreadyCreatedSizeClasses = new SortedSet<int>(); //Find all KnownSize types and emit classes for each one foreach (var mi in typeof(TSerializableType) .GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { KnownSizeAttribute sizeAttribute = mi.GetCustomAttribute<KnownSizeAttribute>(); if (sizeAttribute == null) continue; if (alreadyCreatedSizeClasses.Contains(sizeAttribute.KnownSize)) continue; alreadyCreatedSizeClasses.Add(sizeAttribute.KnownSize); //This creates a class declaration for the int static type. yield return new StaticlyTypedIntegerGenericTypeClassEmitter<int>(sizeAttribute.KnownSize) .Create(); } } } }
Change force emulation IE10 to IE11 Изменена принудительная эмуляция IE10 на IE11
using System; using System.IO; using System.Windows.Forms; using Microsoft.Win32; namespace KryBot { internal static class Program { /// <summary> /// Главная точка входа для приложения. /// </summary> [STAThread] private static void Main() { Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true); string programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]); key?.SetValue(programName, 10001, RegistryValueKind.DWord); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } } }
using System; using System.IO; using System.Windows.Forms; using Microsoft.Win32; namespace KryBot { internal static class Program { /// <summary> /// Главная точка входа для приложения. /// </summary> [STAThread] private static void Main() { Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true); string programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]); key?.SetValue(programName, (decimal)11000, RegistryValueKind.DWord); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } } }
Add to the details page too
@model AnlabMvc.Models.Analysis.AnalysisMethodViewModel @{ ViewBag.Title = @Model.AnalysisMethod.Title; } <div class="col-md-8"> <h2>@Model.AnalysisMethod.Id</h2> <h5>@Model.AnalysisMethod.Title</h5> @Html.Raw(Model.HtmlContent) </div> <div class="col-md-4"> <ul> @foreach (var method in Model.AnalysesInCategory) { <li><a class="internal-link" target="_self" asp-controller="Analysis" asp-action="Details" asp-route-category="@Model.AnalysisMethod.Category" asp-route-id="@method.Id">@method.Title</a></li> } </ul> </div>
@model AnlabMvc.Models.Analysis.AnalysisMethodViewModel @{ ViewBag.Title = @Model.AnalysisMethod.Title; } <div class="col-md-8"> <h2>@Model.AnalysisMethod.Id</h2> <h5>@Model.AnalysisMethod.Title</h5> @Html.Raw(Model.HtmlContent) </div> <div class="col-md-4"> <ul> @foreach (var method in Model.AnalysesInCategory) { <li><a class="internal-link" target="_self" asp-controller="Analysis" asp-action="Details" asp-route-category="@Model.AnalysisMethod.Category" asp-route-id="@method.Id">@method.Id - @method.Title</a></li> } </ul> </div>
Use cell.Value instead of cell.Value2 to allow for Date formatting
using System; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Office.Interop.Excel; namespace XtabFileOpener.TableContainer.SpreadsheetTableContainer.ExcelTableContainer { /// <summary> /// Implementation of Table, that manages an Excel table /// </summary> internal class ExcelTable : Table { internal ExcelTable(string name, Range cells) : base(name) { tableArray = cells.Value2; firstRowContainsColumnNames = true; } } }
using System; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Office.Interop.Excel; namespace XtabFileOpener.TableContainer.SpreadsheetTableContainer.ExcelTableContainer { /// <summary> /// Implementation of Table, that manages an Excel table /// </summary> internal class ExcelTable : Table { internal ExcelTable(string name, Range cells) : base(name) { /* * "The only difference between this property and the Value property is that the Value2 property * doesn’t use the Currency and Date data types. You can return values formatted with these * data types as floating-point numbers by using the Double data type." * */ tableArray = cells.Value; firstRowContainsColumnNames = true; } } }
Add torque to launched planets
using UnityEngine; using System.Collections; public class PlanetSpawner : MonoBehaviour { public GameObject camera; public GameObject planetPrefab; public GravityAttractor blackHole; // public GravityAttractor blackHole1; // public GravityAttractor blackHole2; public float force = 100f; void Start() { } void Update() { if (GvrViewer.Instance.Triggered) { GetComponent<AudioSource>().Play(); GameObject planet = (GameObject) Instantiate(planetPrefab, transform.position, new Quaternion()); planet.GetComponent<GravityBody>().attractor = blackHole; // GravityAttractor[] attractors = new GravityAttractor[2]; // attractors[0] = blackHole1; // attractors[1] = blackHole2; // planet.GetComponent<GravityBody>().attractors = attractors; planet.GetComponent<Rigidbody>().AddForce(camera.transform.forward * force, ForceMode.VelocityChange); } } }
using UnityEngine; using System.Collections; public class PlanetSpawner : MonoBehaviour { public GameObject camera; public GameObject planetPrefab; public GravityAttractor blackHole; // public GravityAttractor blackHole1; // public GravityAttractor blackHole2; public float thrust = 100f; public float torque = 25000f; void Start() { } void Update() { if (GvrViewer.Instance.Triggered) { GetComponent<AudioSource>().Play(); GameObject planet = (GameObject) Instantiate(planetPrefab, transform.position, new Quaternion()); planet.GetComponent<GravityBody>().attractor = blackHole; // GravityAttractor[] attractors = new GravityAttractor[2]; // attractors[0] = blackHole1; // attractors[1] = blackHole2; // planet.GetComponent<GravityBody>().attractors = attractors; planet.GetComponent<Rigidbody>().AddForce(camera.transform.forward * thrust, ForceMode.VelocityChange); planet.GetComponent<Rigidbody>().AddTorque(transform.up * torque); } } }
Add stretchblt for copy and resize
using System; using System.Runtime.InteropServices; namespace Mamesaver.Windows { // This class contains the GDI32 APIs used... public class PlatformInvokeGdi32 { public const int SRCOPY = 13369376; [DllImport("gdi32.dll", EntryPoint = "DeleteDC")] public static extern IntPtr DeleteDC(IntPtr hDc); [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] public static extern IntPtr DeleteObject(IntPtr hDc); [DllImport("gdi32.dll", EntryPoint = "BitBlt")] public static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int RasterOp); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("gdi32.dll", EntryPoint = "SelectObject")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp); } }
using System; using System.Runtime.InteropServices; namespace Mamesaver.Windows { // This class contains the GDI32 APIs used... public class PlatformInvokeGdi32 { public const int SRCOPY = 13369376; [DllImport("gdi32.dll", EntryPoint = "DeleteDC")] public static extern IntPtr DeleteDC(IntPtr hDc); [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] public static extern IntPtr DeleteObject(IntPtr hDc); [DllImport("gdi32.dll", EntryPoint = "BitBlt")] public static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int RasterOp); [DllImport("gdi32.dll", EntryPoint = "StretchBlt")] public static extern bool StretchBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int wSrc, int hSrc, int RasterOp); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("gdi32.dll", EntryPoint = "SelectObject")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp); } }
Write command exception message to the console
using System; using System.Linq; using System.Collections.Generic; namespace AppHarbor { public class CommandDispatcher { private readonly IEnumerable<ICommand> _commands; public CommandDispatcher(IEnumerable<ICommand> commands) { _commands = commands; } public void Dispatch(string[] args) { var commandName = args[0]; var command = _commands.FirstOrDefault(x => x.GetType().Name.ToLower().StartsWith(commandName.ToLower())); if (command == null) { throw new ArgumentException(string.Format("The command \"{0}\" does not exist", commandName)); } command.Execute(args.Skip(1).ToArray()); } } }
using System; using System.Linq; using System.Collections.Generic; namespace AppHarbor { public class CommandDispatcher { private readonly IEnumerable<ICommand> _commands; public CommandDispatcher(IEnumerable<ICommand> commands) { _commands = commands; } public void Dispatch(string[] args) { var commandName = args[0]; var command = _commands.FirstOrDefault(x => x.GetType().Name.ToLower().StartsWith(commandName.ToLower())); if (command == null) { throw new ArgumentException(string.Format("The command \"{0}\" does not exist", commandName)); } try { command.Execute(args.Skip(1).ToArray()); } catch (CommandException exception) { Console.WriteLine(string.Format("Error: {0}", exception.Message)); } } } }
Rename `Option` to `Opt` in key combination output
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Input.Bindings; using osu.Framework.Platform.SDL2; using SDL2; namespace osu.Framework.Platform.MacOS { public class MacOSReadableKeyCombinationProvider : SDL2ReadableKeyCombinationProvider { protected override string GetReadableKey(InputKey key) { switch (key) { case InputKey.Super: return "Cmd"; case InputKey.Alt: return "Option"; default: return base.GetReadableKey(key); } } protected override bool TryGetNameFromKeycode(SDL.SDL_Keycode keycode, out string name) { switch (keycode) { case SDL.SDL_Keycode.SDLK_LGUI: name = "LCmd"; return true; case SDL.SDL_Keycode.SDLK_RGUI: name = "RCmd"; return true; case SDL.SDL_Keycode.SDLK_LALT: name = "LOption"; return true; case SDL.SDL_Keycode.SDLK_RALT: name = "ROption"; return true; default: return base.TryGetNameFromKeycode(keycode, out name); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Input.Bindings; using osu.Framework.Platform.SDL2; using SDL2; namespace osu.Framework.Platform.MacOS { public class MacOSReadableKeyCombinationProvider : SDL2ReadableKeyCombinationProvider { protected override string GetReadableKey(InputKey key) { switch (key) { case InputKey.Super: return "Cmd"; case InputKey.Alt: return "Opt"; default: return base.GetReadableKey(key); } } protected override bool TryGetNameFromKeycode(SDL.SDL_Keycode keycode, out string name) { switch (keycode) { case SDL.SDL_Keycode.SDLK_LGUI: name = "LCmd"; return true; case SDL.SDL_Keycode.SDLK_RGUI: name = "RCmd"; return true; case SDL.SDL_Keycode.SDLK_LALT: name = "LOpt"; return true; case SDL.SDL_Keycode.SDLK_RALT: name = "ROpt"; return true; default: return base.TryGetNameFromKeycode(keycode, out name); } } } }
Expand p tag on about screen.
@{ ViewBag.Title = "About"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <p>Use this area to provide additional information.</p>
@{ ViewBag.Title = "About"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <p>Use this area to provide additional information. Here is more groovy info.</p>
Add filter property to most watched shows request.
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common { using Base.Get; using Enums; using Objects.Basic; using Objects.Get.Shows.Common; using System.Collections.Generic; internal class TraktShowsMostWatchedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostWatchedShow>, TraktMostWatchedShow> { internal TraktShowsMostWatchedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; } internal TraktPeriod? Period { get; set; } protected override IDictionary<string, object> GetUriPathParameters() { var uriParams = base.GetUriPathParameters(); if (Period.HasValue && Period.Value != TraktPeriod.Unspecified) uriParams.Add("period", Period.Value.AsString()); return uriParams; } protected override string UriTemplate => "shows/watched{/period}{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common { using Base; using Base.Get; using Enums; using Objects.Basic; using Objects.Get.Shows.Common; using System.Collections.Generic; internal class TraktShowsMostWatchedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostWatchedShow>, TraktMostWatchedShow> { internal TraktShowsMostWatchedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; } internal TraktPeriod? Period { get; set; } protected override IDictionary<string, object> GetUriPathParameters() { var uriParams = base.GetUriPathParameters(); if (Period.HasValue && Period.Value != TraktPeriod.Unspecified) uriParams.Add("period", Period.Value.AsString()); return uriParams; } protected override string UriTemplate => "shows/watched{/period}{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internal TraktShowFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
Add async/await based pattern execution
using System; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.Extensions.Configuration; using System.Diagnostics; namespace QueueGettingStarted { public class Program { public static void Main(string[] args) { // configuration var builder = new ConfigurationBuilder() .AddJsonFile("./appsettings.json") .AddUserSecrets() .AddEnvironmentVariables(); Configuration = builder.Build(); // options ConfigurationBinder.Bind(Configuration.GetSection("Azure:Storage"), Options); Console.WriteLine("Queue encryption sample"); Console.WriteLine($"Configuration for ConnectionString: {Options.ConnectionString}"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Options.ConnectionString); CloudQueueClient client = storageAccount.CreateCloudQueueClient(); Debug.Assert(client != null, "Client created"); Console.WriteLine("Client created"); Console.WriteLine($"queue: {Options.DemoQueue}"); Console.ReadKey(); } static IConfiguration Configuration { get; set; } static AzureStorageOptions Options { get; set; } = new AzureStorageOptions(); } class AzureStorageOptions { public string ConnectionString { get; set; } public string DemoQueue { get; set; } } }
using System; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.Extensions.Configuration; using System.Diagnostics; using System.Threading.Tasks; namespace QueueGettingStarted { public class Program { public static void Main(string[] args) { AsyncTask(args) .ContinueWith((task) => { Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }).Wait(); } public async static Task AsyncTask(string[] args) { // configuration var builder = new ConfigurationBuilder() .AddJsonFile("./appsettings.json") .AddUserSecrets() .AddEnvironmentVariables(); Configuration = builder.Build(); // options ConfigurationBinder.Bind(Configuration.GetSection("Azure:Storage"), Options); Console.WriteLine("Queue encryption sample"); Console.WriteLine($"Configuration for ConnectionString: {Options.ConnectionString}"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Options.ConnectionString); CloudQueueClient client = storageAccount.CreateCloudQueueClient(); Debug.Assert(client != null, "Client created"); string hash = Guid.NewGuid().ToString("N"); CloudQueue queue = client.GetQueueReference($"{Options.DemoQueue}{hash}"); try { await queue.CreateAsync(); } finally { bool deleted = await queue.DeleteIfExistsAsync(); Console.WriteLine($"Queue deleted: {deleted}"); } } static IConfiguration Configuration { get; set; } static AzureStorageOptions Options { get; set; } = new AzureStorageOptions(); } class AzureStorageOptions { public string ConnectionString { get; set; } public string DemoQueue { get; set; } } }
Update the version for migration project
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DotNet.ProjectJsonMigration { internal class ConstantPackageVersions { public const string AspNetToolsVersion = "1.0.0-msbuild1-final"; public const string TestSdkPackageVersion = "15.0.0-preview-20161024-02"; public const string XUnitPackageVersion = "2.2.0-beta3-build3402"; public const string XUnitRunnerPackageVersion = "2.2.0-beta4-build1188"; public const string MstestTestAdapterVersion = "1.1.3-preview"; public const string MstestTestFrameworkVersion = "1.0.4-preview"; public const string BundleMinifierToolVersion = "2.2.301"; } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DotNet.ProjectJsonMigration { internal class ConstantPackageVersions { public const string AspNetToolsVersion = "1.0.0-msbuild1-final"; public const string TestSdkPackageVersion = "15.0.0-preview-20161024-02"; public const string XUnitPackageVersion = "2.2.0-beta4-build3444"; public const string XUnitRunnerPackageVersion = "2.2.0-beta4-build1194"; public const string MstestTestAdapterVersion = "1.1.3-preview"; public const string MstestTestFrameworkVersion = "1.0.4-preview"; public const string BundleMinifierToolVersion = "2.2.301"; } }
Set title of root controller (sample app)
using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace SampleApp { partial class ExampleTableViewController : UITableViewController { public ExampleTableViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); TableView.Source = new ExampleTableViewControllerSource(NavigationController); } } }
using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace SampleApp { partial class ExampleTableViewController : UITableViewController { public ExampleTableViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); Title = "Application Insights Xamarin"; TableView.Source = new ExampleTableViewControllerSource(NavigationController); } } }
Remove unused namespace which caused a build failure
using NUnit.Framework; namespace Kekiri.IoC.Autofac { public class AutofacFluentScenario : IoCFluentScenario { public AutofacFluentScenario() : base(new AutofacContainer()) { } } public class AutofacFluentScenario<TContext> : IoCFluentScenario<TContext> where TContext : new() { public AutofacFluentScenario() : base(new AutofacContainer()) { } } }
namespace Kekiri.IoC.Autofac { public class AutofacFluentScenario : IoCFluentScenario { public AutofacFluentScenario() : base(new AutofacContainer()) { } } public class AutofacFluentScenario<TContext> : IoCFluentScenario<TContext> where TContext : new() { public AutofacFluentScenario() : base(new AutofacContainer()) { } } }
Rename variable to make more sense
using Nancy; using Nancy.ModelBinding; using Schedules.API.Models; using Simpler; using Schedules.API.Tasks.Reminders; namespace Schedules.API.Modules { public class RemindersModule : NancyModule { public RemindersModule () { Post["/reminders/sms"] = _ => { var createSMSReminder = CreateAReminder("sms"); return Response.AsJson(createSMSReminder.Out.Reminder, HttpStatusCode.Created); }; Post["/reminders/email"] = _ => { var createSMSReminder = CreateAReminder("email"); return Response.AsJson(createSMSReminder.Out.Reminder, HttpStatusCode.Created); }; } private CreateReminder CreateAReminder(string reminderTypeName) { var createReminder = Task.New<CreateReminder>(); createReminder.In.ReminderTypeName = reminderTypeName; createReminder.In.Reminder = this.Bind<Reminder>(); createReminder.Execute(); return createReminder; } } }
using Nancy; using Nancy.ModelBinding; using Schedules.API.Models; using Simpler; using Schedules.API.Tasks.Reminders; namespace Schedules.API.Modules { public class RemindersModule : NancyModule { public RemindersModule () { Post["/reminders/sms"] = _ => { var createSMSReminder = CreateAReminder("sms"); return Response.AsJson(createSMSReminder.Out.Reminder, HttpStatusCode.Created); }; Post["/reminders/email"] = _ => { var createEmailReminder = CreateAReminder("email"); return Response.AsJson(createEmailReminder.Out.Reminder, HttpStatusCode.Created); }; } private CreateReminder CreateAReminder(string reminderTypeName) { var createReminder = Task.New<CreateReminder>(); createReminder.In.ReminderTypeName = reminderTypeName; createReminder.In.Reminder = this.Bind<Reminder>(); createReminder.Execute(); return createReminder; } } }