doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
e2d161a5-55cc-4748-919f-b78c1245d6db
{ "language": "C#" }
```c# /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.TestDll { using System.Linq; /// <summary> /// Extension methods for tests. /// </summary> public static class TestExtensions { /// <summary> /// Reverses the string. /// </summary> public static string ReverseString(this string str) { return new string(str.Reverse().ToArray()); } } } ``` Fix code coverage - exclude remote-only class
```c# /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.TestDll { using System.Diagnostics.CodeAnalysis; using System.Linq; /// <summary> /// Extension methods for tests. /// </summary> [ExcludeFromCodeCoverage] public static class TestExtensions { /// <summary> /// Reverses the string. /// </summary> public static string ReverseString(this string str) { return new string(str.Reverse().ToArray()); } } } ```
4c738989-aa96-4629-a1f7-e62c89c25bec
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Core.CrossDomainImagesWeb { public partial class Default : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { try { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { //set access token in hidden field for client calls hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb; //set images Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png"; Services.ImgService svc = new Services.ImgService(); Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png"); } } catch (Exception) { throw; } } } }``` Revert "added try catch, test commit"
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Core.CrossDomainImagesWeb { public partial class Default : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { //set access token in hidden field for client calls hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb; //set images Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png"; Services.ImgService svc = new Services.ImgService(); Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png"); } } } }```
08f789fd-7d6d-42e1-bff0-ef7b494c5650
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class Dialog_OutOfProc : OutOfProcComponent { public Dialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void VerifyOpen(string dialogName) { // FindDialog will wait until the dialog is open, so the return value is unused. DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: true, CancellationToken.None); // Wait for application idle to ensure the dialog is fully initialized VisualStudioInstance.WaitForApplicationIdle(CancellationToken.None); } public void VerifyClosed(string dialogName) { // FindDialog will wait until the dialog is closed, so the return value is unused. DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: false, CancellationToken.None); } public void Click(string dialogName, string buttonName) => DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), dialogName, buttonName); private IntPtr GetMainWindowHWnd() => VisualStudioInstance.Shell.GetHWnd(); } } ``` Apply hang mitigating timeout in VerifyOpen and VerifyClosed
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class Dialog_OutOfProc : OutOfProcComponent { public Dialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void VerifyOpen(string dialogName) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); // FindDialog will wait until the dialog is open, so the return value is unused. DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: true, cancellationTokenSource.Token); // Wait for application idle to ensure the dialog is fully initialized VisualStudioInstance.WaitForApplicationIdle(cancellationTokenSource.Token); } public void VerifyClosed(string dialogName) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); // FindDialog will wait until the dialog is closed, so the return value is unused. DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: false, cancellationTokenSource.Token); } public void Click(string dialogName, string buttonName) => DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), dialogName, buttonName); private IntPtr GetMainWindowHWnd() => VisualStudioInstance.Shell.GetHWnd(); } } ```
850e38bd-f47c-40a8-86f1-77e4da77f371
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osuTK; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist { /// <summary> /// A historically-ordered list of <see cref="DrawableRoomPlaylistItem"/>s. /// </summary> public class MultiplayerHistoryList : DrawableRoomPlaylist { public MultiplayerHistoryList() : base(false, false, true) { } protected override FillFlowContainer<RearrangeableListItem<PlaylistItem>> CreateListFillFlowContainer() => new HistoryFillFlowContainer { Spacing = new Vector2(0, 2) }; private class HistoryFillFlowContainer : FillFlowContainer<RearrangeableListItem<PlaylistItem>> { public override IEnumerable<Drawable> FlowingChildren => base.FlowingChildren.Reverse(); } } } ``` Update history list to also sort by gameplay order
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osuTK; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist { /// <summary> /// A historically-ordered list of <see cref="DrawableRoomPlaylistItem"/>s. /// </summary> public class MultiplayerHistoryList : DrawableRoomPlaylist { public MultiplayerHistoryList() : base(false, false, true) { } protected override FillFlowContainer<RearrangeableListItem<PlaylistItem>> CreateListFillFlowContainer() => new HistoryFillFlowContainer { Spacing = new Vector2(0, 2) }; private class HistoryFillFlowContainer : FillFlowContainer<RearrangeableListItem<PlaylistItem>> { public override IEnumerable<Drawable> FlowingChildren => base.FlowingChildren.OfType<RearrangeableListItem<PlaylistItem>>().OrderByDescending(item => item.Model.GameplayOrder); } } } ```
3ca189cd-e6d1-4250-a863-6756189311ee
{ "language": "C#" }
```c# using System; using System.Data; using NHibernate.Engine; namespace NHibernate.Impl { /// <summary> /// Summary description for BatchingBatcher. /// </summary> internal class BatchingBatcher : BatcherImpl { private int batchSize; private int[] expectedRowCounts; /// <summary> /// /// </summary> /// <param name="session"></param> public BatchingBatcher( ISessionImplementor session ) : base( session ) { expectedRowCounts = new int[ Factory.BatchSize ]; } /// <summary> /// /// </summary> /// <param name="expectedRowCount"></param> public override void AddToBatch( int expectedRowCount ) { throw new NotImplementedException( "Batching not implemented yet" ); /* log.Info( "Adding to batch" ); IDbCommand batchUpdate = CurrentStatment; */ } /// <summary> /// /// </summary> /// <param name="ps"></param> protected override void DoExecuteBatch( IDbCommand ps ) { throw new NotImplementedException( "Batching not implemented yet" ); } } } ``` Comment out batchSize for now as not used
```c# using System; using System.Data; using NHibernate.Engine; namespace NHibernate.Impl { /// <summary> /// Summary description for BatchingBatcher. /// </summary> internal class BatchingBatcher : BatcherImpl { //private int batchSize; private int[] expectedRowCounts; /// <summary> /// /// </summary> /// <param name="session"></param> public BatchingBatcher( ISessionImplementor session ) : base( session ) { expectedRowCounts = new int[ Factory.BatchSize ]; } /// <summary> /// /// </summary> /// <param name="expectedRowCount"></param> public override void AddToBatch( int expectedRowCount ) { throw new NotImplementedException( "Batching not implemented yet" ); /* log.Info( "Adding to batch" ); IDbCommand batchUpdate = CurrentStatment; */ } /// <summary> /// /// </summary> /// <param name="ps"></param> protected override void DoExecuteBatch( IDbCommand ps ) { throw new NotImplementedException( "Batching not implemented yet" ); } } } ```
3cf88777-d8cd-4587-b63b-8b5a1c5b593f
{ "language": "C#" }
```c# using Microsoft.AspNet.Http; using Microsoft.AspNet.Mvc; using MvcSample.Web.Models; namespace MvcSample.Web.RandomNameSpace { public class Home2Controller { private User _user = new User() { Name = "User Name", Address = "Home Address" }; [Activate] public HttpResponse Response { get; set; } public ActionContext ActionContext { get; set; } public string Index() { return "Hello World: my namespace is " + this.GetType().Namespace; } public ActionResult Something() { return new ContentResult { Content = "Hello World From Content" }; } public ActionResult Hello() { return new ContentResult { Content = "Hello World", }; } public void Raw() { Response.WriteAsync("Hello World raw"); } public ActionResult UserJson() { var jsonResult = new JsonResult(_user); return jsonResult; } public User User() { return _user; } } }``` Fix the sample to await when writing directly to the output stream in a controller.
```c# using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.AspNet.Mvc; using MvcSample.Web.Models; namespace MvcSample.Web.RandomNameSpace { public class Home2Controller { private User _user = new User() { Name = "User Name", Address = "Home Address" }; [Activate] public HttpResponse Response { get; set; } public ActionContext ActionContext { get; set; } public string Index() { return "Hello World: my namespace is " + this.GetType().Namespace; } public ActionResult Something() { return new ContentResult { Content = "Hello World From Content" }; } public ActionResult Hello() { return new ContentResult { Content = "Hello World", }; } public async Task Raw() { await Response.WriteAsync("Hello World raw"); } public ActionResult UserJson() { var jsonResult = new JsonResult(_user); return jsonResult; } public User User() { return _user; } } }```
f9d6d937-5b76-477e-88d0-0ca847b05d7e
{ "language": "C#" }
```c# using System; using System.Linq; using Nest; using Tests.Framework.ManagedElasticsearch.Nodes; using Tests.Framework.ManagedElasticsearch.Plugins; namespace Tests.Framework.ManagedElasticsearch.Tasks.ValidationTasks { public class ValidatePluginsTask : NodeValidationTaskBase { public override void Validate(IElasticClient client, NodeConfiguration configuration) { var v = configuration.ElasticsearchVersion; var requiredMonikers = ElasticsearchPluginCollection.Supported .Where(plugin => plugin.IsValid(v) && configuration.RequiredPlugins.Contains(plugin.Plugin)) .Select(plugin => plugin.Moniker) .ToList(); if (!requiredMonikers.Any()) return; var checkPlugins = client.CatPlugins(); if (!checkPlugins.IsValid) throw new Exception($"Failed to check plugins: {checkPlugins.DebugInformation}."); var missingPlugins = requiredMonikers .Except((checkPlugins.Records ?? Enumerable.Empty<CatPluginsRecord>()).Select(r => r.Component)) .ToList(); if (!missingPlugins.Any()) return; var pluginsString = string.Join(", ", missingPlugins); throw new Exception($"Already running elasticsearch missed the following plugin(s): {pluginsString}."); } } } ``` Validate existence of x-pack-core for 6.2.4+
```c# using System; using System.Linq; using Nest; using Tests.Document.Multiple.UpdateByQuery; using Tests.Framework.ManagedElasticsearch.Nodes; using Tests.Framework.ManagedElasticsearch.Plugins; namespace Tests.Framework.ManagedElasticsearch.Tasks.ValidationTasks { public class ValidatePluginsTask : NodeValidationTaskBase { public override void Validate(IElasticClient client, NodeConfiguration configuration) { var v = configuration.ElasticsearchVersion; var requiredMonikers = ElasticsearchPluginCollection.Supported .Where(plugin => plugin.IsValid(v) && configuration.RequiredPlugins.Contains(plugin.Plugin)) .Select(plugin => plugin.Moniker) .ToList(); if (!requiredMonikers.Any()) return; // 6.2.4 splits out X-Pack into separate plugin names if (requiredMonikers.Contains(ElasticsearchPlugin.XPack.Moniker()) && TestClient.VersionUnderTestSatisfiedBy(">=6.2.4")) { requiredMonikers.Remove(ElasticsearchPlugin.XPack.Moniker()); requiredMonikers.Add(ElasticsearchPlugin.XPack.Moniker() + "-core"); } var checkPlugins = client.CatPlugins(); if (!checkPlugins.IsValid) throw new Exception($"Failed to check plugins: {checkPlugins.DebugInformation}."); var missingPlugins = requiredMonikers .Except((checkPlugins.Records ?? Enumerable.Empty<CatPluginsRecord>()).Select(r => r.Component)) .ToList(); if (!missingPlugins.Any()) return; var pluginsString = string.Join(", ", missingPlugins); throw new Exception($"Already running elasticsearch missed the following plugin(s): {pluginsString}."); } } } ```
216b81cb-0363-4f16-8e1d-e370096bc651
{ "language": "C#" }
```c# using System.Reflection; using P2E.Interfaces.DataObjects; namespace P2E.DataObjects { public class ApplicationInformation : IApplicationInformation { public string Name { get; } public string Version { get; } public ApplicationInformation() { Name = Assembly.GetEntryAssembly().GetName().Name; Version = Assembly.GetEntryAssembly().GetName().Version.ToString(); } } }``` Rewrite with expression bodies properties syntax.
```c# using System.Reflection; using P2E.Interfaces.DataObjects; namespace P2E.DataObjects { public class ApplicationInformation : IApplicationInformation { public string Name => Assembly.GetEntryAssembly().GetName().Name; public string Version => Assembly.GetEntryAssembly().GetName().Version.ToString(); } }```
583bcd7b-b4c8-4fe6-a4ec-510364d90f5d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; namespace BitDiffer.Common.Misc { public class Constants { public const string ProductName = "BitDiffer"; public const string ProductSubTitle = "Assembly Comparison Tool"; public const string HelpUrl = "https://github.com/grennis/bitdiffer/wiki"; public const string ExtractionDomainPrefix = "Temp App Domain"; public const string ComparisonEmailSubject = "BitDiffer Assembly Comparison Report"; } } ``` Use correct URL for help
```c# using System; using System.Collections.Generic; using System.Text; namespace BitDiffer.Common.Misc { public class Constants { public const string ProductName = "BitDiffer"; public const string ProductSubTitle = "Assembly Comparison Tool"; public const string HelpUrl = "https://github.com/bitdiffer/bitdiffer/wiki"; public const string ExtractionDomainPrefix = "Temp App Domain"; public const string ComparisonEmailSubject = "BitDiffer Assembly Comparison Report"; } } ```
951fdbb4-3f68-42f6-bd83-fd7dd01df77e
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [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("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.2.3.0")] [assembly: AssemblyFileVersion("1.2.3.0")] ``` Bump assembly info for 1.3.0 release
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [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("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] ```
204513b4-a3c0-4235-9d73-855aac5889b4
{ "language": "C#" }
```c# using ZobShop.Data.Contracts; using ZobShop.Factories; using ZobShop.Models; using ZobShop.Services.Contracts; namespace ZobShop.Services { public class ProductRatingService : IProductRatingService { private readonly IRepository<User> userRepository; private readonly IRepository<ProductRating> productRatingRepository; private readonly IRepository<Product> productRepository; private readonly IUnitOfWork unitOfWork; private readonly IProductRatingFactory factory; public ProductRatingService(IRepository<User> userRepository, IRepository<Product> productRepository, IRepository<ProductRating> productRatingRepository, IUnitOfWork unitOfWork, IProductRatingFactory factory) { this.userRepository = userRepository; this.productRepository = productRepository; this.productRatingRepository = productRatingRepository; this.unitOfWork = unitOfWork; this.factory = factory; } public ProductRating CreateProductRating(int rating, string content, int productId, string userId) { var product = this.productRepository.GetById(productId); var user = this.userRepository.GetById(userId); var newRating = this.factory.CreateProductRating(rating, content, product, user); this.productRatingRepository.Add(newRating); this.unitOfWork.Commit(); return newRating; } } } ``` Add checks in product rating service
```c# using System; using ZobShop.Data.Contracts; using ZobShop.Factories; using ZobShop.Models; using ZobShop.Services.Contracts; namespace ZobShop.Services { public class ProductRatingService : IProductRatingService { private readonly IRepository<User> userRepository; private readonly IRepository<ProductRating> productRatingRepository; private readonly IRepository<Product> productRepository; private readonly IUnitOfWork unitOfWork; private readonly IProductRatingFactory factory; public ProductRatingService(IRepository<User> userRepository, IRepository<Product> productRepository, IRepository<ProductRating> productRatingRepository, IUnitOfWork unitOfWork, IProductRatingFactory factory) { if (userRepository == null) { throw new ArgumentNullException("user repository cannot be null"); } if (productRepository == null) { throw new ArgumentNullException("product repository cannot be null"); } if (productRatingRepository == null) { throw new ArgumentNullException("product rating repository cannot be null"); } if (unitOfWork == null) { throw new ArgumentNullException("unit of work repository cannot be null"); } if (factory == null) { throw new ArgumentNullException("factory repository cannot be null"); } this.userRepository = userRepository; this.productRepository = productRepository; this.productRatingRepository = productRatingRepository; this.unitOfWork = unitOfWork; this.factory = factory; } public ProductRating CreateProductRating(int rating, string content, int productId, string userId) { var product = this.productRepository.GetById(productId); var user = this.userRepository.GetById(userId); var newRating = this.factory.CreateProductRating(rating, content, product, user); this.productRatingRepository.Add(newRating); this.unitOfWork.Commit(); return newRating; } } } ```
1d0ddda6-7f51-4362-8be5-c9c8e8bf923a
{ "language": "C#" }
```c# using System; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer { public interface INumberProvider { double NextNumber(); } public class LiteralNumberProvider : INumberProvider { private readonly double value; public LiteralNumberProvider(double value) { this.value = value; } public double NextNumber() => value; } public static class INumberProviderExtensions { public static INumberProvider GetNumberProvider(this IKeyValueCollection keyValues, string propertyName) { var property = keyValues.GetProperty<object>(propertyName); if (property is IKeyValueCollection numberProviderParameters) { var type = numberProviderParameters.GetProperty<string>("m_nType"); switch (type) { case "PF_TYPE_LITERAL": return new LiteralNumberProvider(numberProviderParameters.GetDoubleProperty("m_flLiteralValue")); default: throw new InvalidCastException($"Could not create number provider of type {type}."); } } else { return new LiteralNumberProvider(Convert.ToDouble(property)); } } public static int NextInt(this INumberProvider numberProvider) { return (int)numberProvider.NextNumber(); } } } ``` Support all particle num providers with m_flLiteralValue
```c# using System; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer { public interface INumberProvider { double NextNumber(); } public class LiteralNumberProvider : INumberProvider { private readonly double value; public LiteralNumberProvider(double value) { this.value = value; } public double NextNumber() => value; } public static class INumberProviderExtensions { public static INumberProvider GetNumberProvider(this IKeyValueCollection keyValues, string propertyName) { var property = keyValues.GetProperty<object>(propertyName); if (property is IKeyValueCollection numberProviderParameters) { var type = numberProviderParameters.GetProperty<string>("m_nType"); switch (type) { case "PF_TYPE_LITERAL": return new LiteralNumberProvider(numberProviderParameters.GetDoubleProperty("m_flLiteralValue")); default: if (numberProviderParameters.ContainsKey("m_flLiteralValue")) { Console.Error.WriteLine($"Number provider of type {type} is not directly supported, but it has m_flLiteralValue."); return new LiteralNumberProvider(numberProviderParameters.GetDoubleProperty("m_flLiteralValue")); } throw new InvalidCastException($"Could not create number provider of type {type}."); } } else { return new LiteralNumberProvider(Convert.ToDouble(property)); } } public static int NextInt(this INumberProvider numberProvider) { return (int)numberProvider.NextNumber(); } } } ```
1b80d5b7-0ded-4220-b7cb-87d7f862b066
{ "language": "C#" }
```c#  namespace LINQToTreeHelpers { public static class Utils { /// <summary> /// Write out an object. Eventually, with ROOTNET improvements this will work better and perahps /// won't be needed! /// </summary> /// <param name="obj"></param> /// <param name="dir"></param> internal static void InternalWriteObject(this ROOTNET.Interface.NTObject obj, ROOTNET.Interface.NTDirectory dir) { var h = obj as ROOTNET.Interface.NTH1; if (h != null) { var copy = h.Clone(); dir.WriteTObject(copy); // Ugly from a memory pov, but... copy.SetNull(); } else { dir.WriteTObject(obj); obj.SetNull(); } } /// <summary> /// Take a string and "sanatize" it for a root name. /// </summary> /// <param name="name">Text name to be used as a ROOT name</param> /// <returns>argument name with spaces removes, as well as other characters</returns> public static string FixupForROOTName(this string name) { var result = name.Replace(" ", ""); result = result.Replace("_{", ""); result = result.Replace("{", ""); result = result.Replace("}", ""); result = result.Replace("-", ""); result = result.Replace("\\", ""); result = result.Replace("%", ""); result = result.Replace("<", ""); result = result.Replace(">", ""); return result; } } } ``` Improve translation when removing strings from names!
```c#  namespace LINQToTreeHelpers { public static class Utils { /// <summary> /// Write out an object. Eventually, with ROOTNET improvements this will work better and perahps /// won't be needed! /// </summary> /// <param name="obj"></param> /// <param name="dir"></param> internal static void InternalWriteObject(this ROOTNET.Interface.NTObject obj, ROOTNET.Interface.NTDirectory dir) { var h = obj as ROOTNET.Interface.NTH1; if (h != null) { var copy = h.Clone(); dir.WriteTObject(copy); // Ugly from a memory pov, but... copy.SetNull(); } else { dir.WriteTObject(obj); obj.SetNull(); } } /// <summary> /// Take a string and "sanatize" it for a root name. /// </summary> /// <param name="name">Text name to be used as a ROOT name</param> /// <returns>argument name with spaces removes, as well as other characters</returns> public static string FixupForROOTName(this string name) { var result = name.Replace(" ", ""); result = result.Replace("_{", ""); result = result.Replace("{", ""); result = result.Replace("}", ""); result = result.Replace("-", ""); result = result.Replace("\\", ""); result = result.Replace("%", ""); result = result.Replace("<", "lt"); result = result.Replace(">", "gt"); return result; } } } ```
b8fc028e-a7ba-4922-b7c2-dca9d6b4b7f2
{ "language": "C#" }
```c# using System.Diagnostics; using System.Windows; using System.Windows.Input; using DesktopWidgets.Classes; using DesktopWidgets.Helpers; using DesktopWidgets.ViewModelBase; using GalaSoft.MvvmLight.Command; namespace DesktopWidgets.Widgets.Search { public class ViewModel : WidgetViewModelBase { private string _searchText; public ViewModel(WidgetId id) : base(id) { Settings = id.GetSettings() as Settings; if (Settings == null) return; Go = new RelayCommand(GoExecute); OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute); } public Settings Settings { get; } public ICommand Go { get; set; } public ICommand OnKeyUp { get; set; } public string SearchText { get { return _searchText; } set { if (_searchText != value) { _searchText = value; RaisePropertyChanged(nameof(SearchText)); } } } private void GoExecute() { if (string.IsNullOrWhiteSpace(Settings.BaseUrl)) { Popup.Show("You must set up a base URL first.", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } var searchText = SearchText; SearchText = string.Empty; Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}"); } private void OnKeyUpExecute(KeyEventArgs args) { if (args.Key == Key.Enter) GoExecute(); } } }``` Remove "Search" widget base URL warning
```c# using System.Diagnostics; using System.Windows.Input; using DesktopWidgets.Classes; using DesktopWidgets.Helpers; using DesktopWidgets.ViewModelBase; using GalaSoft.MvvmLight.Command; namespace DesktopWidgets.Widgets.Search { public class ViewModel : WidgetViewModelBase { private string _searchText; public ViewModel(WidgetId id) : base(id) { Settings = id.GetSettings() as Settings; if (Settings == null) return; Go = new RelayCommand(GoExecute); OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute); } public Settings Settings { get; } public ICommand Go { get; set; } public ICommand OnKeyUp { get; set; } public string SearchText { get { return _searchText; } set { if (_searchText != value) { _searchText = value; RaisePropertyChanged(nameof(SearchText)); } } } private void GoExecute() { var searchText = SearchText; SearchText = string.Empty; Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}"); } private void OnKeyUpExecute(KeyEventArgs args) { if (args.Key == Key.Enter) GoExecute(); } } }```
92d87fd8-e73e-45d2-b9d5-478586fc5a9b
{ "language": "C#" }
```c# // #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2014 SmartsheetClient // %% // 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. // %[license] using System.Runtime.Serialization; namespace Smartsheet.Api.Models { /// <summary> /// Represents specific objects that can be excluded in some responses. /// </summary> public enum ObjectExclusion { /// <summary> /// The discussions /// </summary> [EnumMember(Value = "nonexistentCells")] NONEXISTENT_CELLS } }``` Make sure NONEXISTENT_CELLS is serialized into nonexistentCells
```c# // #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2014 SmartsheetClient // %% // 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. // %[license] using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; namespace Smartsheet.Api.Models { /// <summary> /// Represents specific objects that can be excluded in some responses. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ObjectExclusion { /// <summary> /// The discussions /// </summary> [EnumMember(Value = "nonexistentCells")] NONEXISTENT_CELLS } }```
3b6d0a16-5d8a-4965-8992-5d949d329454
{ "language": "C#" }
```c# using System; namespace FilterLists.Agent.Entities { public class ListInfo { public int Id { get; } public Uri ViewUrl { get; } } }``` Revert "remove unused private setters"
```c# using System; namespace FilterLists.Agent.Entities { public class ListInfo { public int Id { get; private set; } public Uri ViewUrl { get; private set; } } }```
ac78eb4a-22ee-49fa-b5e8-83d9576ac5d9
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { public int bulletSpeed = 715; void Start () { GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * bulletSpeed); } } ``` Destroy bullets on trigger event
```c# using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { public int bulletSpeed = 715; void Start() { GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * bulletSpeed); } void OnTriggerEnter(Collider other) { Destroy(gameObject); } } ```
90752ed9-99a4-4dc7-a8eb-54c23a8c78d4
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DropdownLanguageFontUpdater : MonoBehaviour { [SerializeField] private Text textComponent; void Start () { Font overrideFont = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1].overrideFont; if (overrideFont != null) textComponent.font = overrideFont; } void Update () { } } ``` Apply force unbold to dropdown options
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DropdownLanguageFontUpdater : MonoBehaviour { [SerializeField] private Text textComponent; void Start () { var language = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1]; if (language.overrideFont != null) { textComponent.font = language.overrideFont; if (language.forceUnbold) textComponent.fontStyle = FontStyle.Normal; } } void Update () { } } ```
8e159c92-e3fd-421d-871e-d889835eed55
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Reflection; using System.Runtime.Loader; using Microsoft.AspNetCore.Mvc.ApplicationParts; namespace Microsoft.AspNetCore.Mvc.Razor.Compilation { public static class CompiledViewManfiest { public static readonly string PrecompiledViewsAssemblySuffix = ".PrecompiledViews"; public static Type GetManifestType(AssemblyPart assemblyPart, string typeName) { EnsureFeatureAssembly(assemblyPart); var precompiledAssemblyName = new AssemblyName(assemblyPart.Assembly.FullName); precompiledAssemblyName.Name = precompiledAssemblyName.Name + PrecompiledViewsAssemblySuffix; return Type.GetType($"{typeName},{precompiledAssemblyName}"); } private static void EnsureFeatureAssembly(AssemblyPart assemblyPart) { if (assemblyPart.Assembly.IsDynamic || string.IsNullOrEmpty(assemblyPart.Assembly.Location)) { return; } var precompiledAssemblyFileName = assemblyPart.Assembly.GetName().Name + PrecompiledViewsAssemblySuffix + ".dll"; var precompiledAssemblyFilePath = Path.Combine( Path.GetDirectoryName(assemblyPart.Assembly.Location), precompiledAssemblyFileName); if (File.Exists(precompiledAssemblyFilePath)) { try { Assembly.LoadFile(precompiledAssemblyFilePath); } catch (FileLoadException) { // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly. } } } } } ``` Load the precompilation type from the loaded assembly
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Reflection; using System.Runtime.Loader; using Microsoft.AspNetCore.Mvc.ApplicationParts; namespace Microsoft.AspNetCore.Mvc.Razor.Compilation { public static class CompiledViewManfiest { public static readonly string PrecompiledViewsAssemblySuffix = ".PrecompiledViews"; public static Type GetManifestType(AssemblyPart assemblyPart, string typeName) { var assembly = GetFeatureAssembly(assemblyPart); return assembly?.GetType(typeName); } private static Assembly GetFeatureAssembly(AssemblyPart assemblyPart) { if (assemblyPart.Assembly.IsDynamic || string.IsNullOrEmpty(assemblyPart.Assembly.Location)) { return null; } var precompiledAssemblyFileName = assemblyPart.Assembly.GetName().Name + PrecompiledViewsAssemblySuffix + ".dll"; var precompiledAssemblyFilePath = Path.Combine( Path.GetDirectoryName(assemblyPart.Assembly.Location), precompiledAssemblyFileName); if (File.Exists(precompiledAssemblyFilePath)) { try { return Assembly.LoadFile(precompiledAssemblyFilePath); } catch (FileLoadException) { // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly. } } return null; } } } ```
21f3bc08-6fba-4c77-8f46-b8060f191108
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Elasticsearch.Net; using FluentAssertions; using Nest; using Nest.Tests.MockData.Domain; using NUnit.Framework; namespace Nest.Tests.Unit.ObjectInitializer.Index { [TestFixture] public class IndexRequestTests : BaseJsonTests { private readonly IElasticsearchResponse _status; public IndexRequestTests() { var newProject = new ElasticsearchProject { Id = 15, Name = "Some awesome new elasticsearch project" }; var request = new IndexRequest<ElasticsearchProject>(newProject) { Replication = Replication.Async }; //TODO Index(request) does not work as expected var response = this._client.Index<ElasticsearchProject>(request); this._status = response.ConnectionStatus; } public void SettingsTest() { } [Test] public void Url() { this._status.RequestUrl.Should().EndWith("/nest_test_data/elasticsearchprojects/15?replication=async"); this._status.RequestMethod.Should().Be("PUT"); } [Test] public void IndexBody() { this.JsonEquals(this._status.Request, MethodBase.GetCurrentMethod()); } } } ``` Remove empty method checked in by mistake
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Elasticsearch.Net; using FluentAssertions; using Nest; using Nest.Tests.MockData.Domain; using NUnit.Framework; namespace Nest.Tests.Unit.ObjectInitializer.Index { [TestFixture] public class IndexRequestTests : BaseJsonTests { private readonly IElasticsearchResponse _status; public IndexRequestTests() { var newProject = new ElasticsearchProject { Id = 15, Name = "Some awesome new elasticsearch project" }; var request = new IndexRequest<ElasticsearchProject>(newProject) { Replication = Replication.Async }; //TODO Index(request) does not work as expected var response = this._client.Index<ElasticsearchProject>(request); this._status = response.ConnectionStatus; } [Test] public void Url() { this._status.RequestUrl.Should().EndWith("/nest_test_data/elasticsearchprojects/15?replication=async"); this._status.RequestMethod.Should().Be("PUT"); } [Test] public void IndexBody() { this.JsonEquals(this._status.Request, MethodBase.GetCurrentMethod()); } } } ```
064c4780-9062-49d9-afa7-9149f2418926
{ "language": "C#" }
```c# // Copyright 2017 by PeopleWare n.v.. // // 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 NHibernate.Mapping.ByCode.Conformist; using PPWCode.Vernacular.NHibernate.I.Tests.DictionariesAndLists.Models; namespace PPWCode.Vernacular.NHibernate.I.Tests.DictionariesAndLists.Mappers { public class PlaneMapper : ComponentMapping<Plane> { public PlaneMapper() { Component(p => p.Normal); Component(p => p.Translation); } } }``` Fix wrong mapping for Translation, should be mapped as a property instead of Component
```c# // Copyright 2017 by PeopleWare n.v.. // // 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 NHibernate.Mapping.ByCode.Conformist; using PPWCode.Vernacular.NHibernate.I.Tests.DictionariesAndLists.Models; namespace PPWCode.Vernacular.NHibernate.I.Tests.DictionariesAndLists.Mappers { public class PlaneMapper : ComponentMapping<Plane> { public PlaneMapper() { Component(p => p.Normal); Property(p => p.Translation); } } }```
a2928106-8260-42a3-96d4-3002e69cdeea
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets.Mods; namespace osu.Game.Tests.Visual.Gameplay { [HeadlessTest] public class TestSceneModValidity : TestSceneAllRulesetPlayers { protected override void AddCheckSteps() { AddStep("Check all mod acronyms are unique", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<string> acronyms = mods.Select(m => m.Acronym); Assert.That(acronyms, Is.Unique); }); AddStep("Check all mods are two-way incompatible", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<Mod> modInstances = mods.Select(mod => mod.CreateInstance()); foreach (var mod in modInstances) { var modIncompatibilities = mod.IncompatibleMods; foreach (var incompatibleModType in modIncompatibilities) { var incompatibleMod = modInstances.First(m => incompatibleModType.IsInstanceOfType(m)); Assert.That( incompatibleMod.IncompatibleMods.Any(m => m.IsInstanceOfType(mod)), $"{mod} has {incompatibleMod} in it's incompatible mods, but {incompatibleMod} does not have {mod} in it's incompatible mods." ); } } }); } } } ``` Fix check not accounting for mods not existing in certain rulesets
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets.Mods; namespace osu.Game.Tests.Visual.Gameplay { [HeadlessTest] public class TestSceneModValidity : TestSceneAllRulesetPlayers { protected override void AddCheckSteps() { AddStep("Check all mod acronyms are unique", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<string> acronyms = mods.Select(m => m.Acronym); Assert.That(acronyms, Is.Unique); }); AddStep("Check all mods are two-way incompatible", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<Mod> modInstances = mods.Select(mod => mod.CreateInstance()); foreach (var modToCheck in modInstances) { var incompatibleMods = modToCheck.IncompatibleMods; foreach (var incompatible in incompatibleMods) { foreach (var incompatibleMod in modInstances.Where(m => incompatible.IsInstanceOfType(m))) { Assert.That( incompatibleMod.IncompatibleMods.Any(m => m.IsInstanceOfType(modToCheck)), $"{modToCheck} has {incompatibleMod} in it's incompatible mods, but {incompatibleMod} does not have {modToCheck} in it's incompatible mods." ); } } } }); } } } ```
0f79e3c2-7fa8-4ea4-ad31-b2626b574cb0
{ "language": "C#" }
```c# // ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.CloudService.Test.Utilities { using System.Management.Automation; using VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.Test.Tests.Utilities; [TestClass] public class PowerShellTest { protected PowerShell powershell; protected string[] modules; public PowerShellTest(params string[] modules) { this.modules = modules; } protected void AddScenarioScript(string script) { powershell.AddScript(Testing.GetTestResourceContents(script)); } [TestInitialize] public virtual void SetupTest() { powershell = PowerShell.Create(); foreach (string moduleName in modules) { powershell.AddScript(string.Format("Import-Module \"{0}\"", Testing.GetTestResourcePath(moduleName))); } powershell.AddScript("$verbosepreference='continue'"); } [TestCleanup] public virtual void TestCleanup() { powershell.Dispose(); } } } ``` Enable debug by default in scenario tests
```c# // ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.CloudService.Test.Utilities { using System.Management.Automation; using VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.Test.Tests.Utilities; [TestClass] public class PowerShellTest { protected PowerShell powershell; protected string[] modules; public PowerShellTest(params string[] modules) { this.modules = modules; } protected void AddScenarioScript(string script) { powershell.AddScript(Testing.GetTestResourceContents(script)); } [TestInitialize] public virtual void SetupTest() { powershell = PowerShell.Create(); foreach (string moduleName in modules) { powershell.AddScript(string.Format("Import-Module \"{0}\"", Testing.GetTestResourcePath(moduleName))); } powershell.AddScript("$VerbosePreference='Continue'"); powershell.AddScript("$DebugPreference='Continue'"); } [TestCleanup] public virtual void TestCleanup() { powershell.Dispose(); } } } ```
e5f141c0-ecd0-4776-affe-07aec65f2dff
{ "language": "C#" }
```c# <?xml version="1.0"?> <!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> --> <rss version="2.0"> <channel><?cs if:project.name_encoded ?> <title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs else ?> <title>Revisions of <?cs var:log.path ?></title><?cs /if ?> <link><?cs var:base_host ?><?cs var:log.log_href ?></link> <description>Trac Log - Revisions of <?cs var:log.path ?></description> <language>en-us</language> <generator>Trac v<?cs var:trac.version ?></generator><?cs each:item = log.items ?><?cs with:change = log.changes[item.rev] ?> <item> <author><?cs var:change.author ?></author> <pubDate><?cs var:change.date ?></pubDate> <title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title> <link><?cs var:base_host ?><?cs var:item.changeset_href ?></link> <description><?cs var:change.message ?></description> <category>Report</category> </item><?cs /with ?><?cs /each ?> </channel> </rss> ``` Fix category of revision log RSS feeds.
```c# <?xml version="1.0"?> <!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> --> <rss version="2.0"> <channel><?cs if:project.name_encoded ?> <title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs else ?> <title>Revisions of <?cs var:log.path ?></title><?cs /if ?> <link><?cs var:base_host ?><?cs var:log.log_href ?></link> <description>Trac Log - Revisions of <?cs var:log.path ?></description> <language>en-us</language> <generator>Trac v<?cs var:trac.version ?></generator><?cs each:item = log.items ?><?cs with:change = log.changes[item.rev] ?> <item> <author><?cs var:change.author ?></author> <pubDate><?cs var:change.date ?></pubDate> <title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title> <link><?cs var:base_host ?><?cs var:item.changeset_href ?></link> <description><?cs var:change.message ?></description> <category>Log</category> </item><?cs /with ?><?cs /each ?> </channel> </rss> ```
d8b8b956-ac35-4e29-b5b6-95dd9eb0f4e8
{ "language": "C#" }
```c# using System.ComponentModel; namespace SFA.DAS.EAS.Account.Api.Types { public enum EmployerAgreementStatus { [Description("Not signed")] Pending = 1, [Description("Signed")] Signed = 2, [Description("Expired")] Expired = 3, [Description("Superceded")] Superceded = 4 } }``` Update spelling mistake in api types
```c# using System.ComponentModel; namespace SFA.DAS.EAS.Account.Api.Types { public enum EmployerAgreementStatus { [Description("Not signed")] Pending = 1, [Description("Signed")] Signed = 2, [Description("Expired")] Expired = 3, [Description("Superseded")] Superceded = 4 } } ```
ccb46cf3-6824-4bee-a10c-7bbcbb7d3c0f
{ "language": "C#" }
```c# using System; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace Countdown.Views { internal class ScrollTo { public static void SetItem(UIElement element, object value) { element.SetValue(ItemProperty, value); } public static object GetItem(UIElement element) { return element.GetValue(ItemProperty); } public static readonly DependencyProperty ItemProperty = DependencyProperty.RegisterAttached("Item", typeof(object), typeof(ScrollTo), new FrameworkPropertyMetadata(OnScrollToItemPropertyChanged)); private static void OnScrollToItemPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { if ((e.NewValue is not null) && (source is ListBox list)) { list.SelectedItem = e.NewValue; if (list.IsGrouping) { // Work around a bug that stops ScrollIntoView() working on Net5.0 // see https://github.com/dotnet/wpf/issues/4797 _ = list.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => list.ScrollIntoView(e.NewValue))); } else { list.ScrollIntoView(e.NewValue); } } } } } ``` Add a list focus call
```c# using System; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace Countdown.Views { internal class ScrollTo { public static void SetItem(UIElement element, object value) { element.SetValue(ItemProperty, value); } public static object GetItem(UIElement element) { return element.GetValue(ItemProperty); } public static readonly DependencyProperty ItemProperty = DependencyProperty.RegisterAttached("Item", typeof(object), typeof(ScrollTo), new FrameworkPropertyMetadata(OnScrollToItemPropertyChanged)); private static void OnScrollToItemPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { if ((e.NewValue is not null) && (source is ListBox list)) { list.SelectedItem = e.NewValue; if (list.IsGrouping) { // Work around a bug that stops ScrollIntoView() working on Net5.0 // see https://github.com/dotnet/wpf/issues/4797 _ = list.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => { list.ScrollIntoView(e.NewValue); _ = list.Focus(); })); } else { list.ScrollIntoView(e.NewValue); _ = list.Focus(); } } } } } ```
5c715ca9-3bdb-489e-81f2-a14bfa0ee651
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace BatteryCommander.Web.Models { public class EvaluationListViewModel { public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>(); [Display(Name = "Delinquent > 60 Days")] public int Delinquent => Evaluations.Where(_ => _.IsDelinquent).Count(); public int Due => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count(); [Display(Name = "Next 30")] public int Next30 => Evaluations.Where(_ => 0 <= _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 30).Count(); [Display(Name = "Next 60")] public int Next60 => Evaluations.Where(_ => 30 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 60).Count(); [Display(Name = "Next 90")] public int Next90 => Evaluations.Where(_ => 60 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 90).Count(); } }``` Make sure to take into account completed when looking at ALL
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace BatteryCommander.Web.Models { public class EvaluationListViewModel { public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>(); [Display(Name = "Delinquent > 60 Days")] public int Delinquent => Evaluations.Where(_ => !_.IsCompleted).Where(_ => _.IsDelinquent).Count(); public int Due => Evaluations.Where(_ => !_.IsCompleted).Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count(); [Display(Name = "Next 30")] public int Next30 => Evaluations.Where(_ => !_.IsCompleted).Where(_ => 0 <= _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 30).Count(); [Display(Name = "Next 60")] public int Next60 => Evaluations.Where(_ => !_.IsCompleted).Where(_ => 30 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 60).Count(); [Display(Name = "Next 90")] public int Next90 => Evaluations.Where(_ => !_.IsCompleted).Where(_ => 60 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 90).Count(); } }```
4a1f26fa-aadb-4e4c-855b-1032b2354557
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Luval.Common; namespace Luval.Orm { public class SqlServerLanguageProvider : AnsiSqlLanguageProvider { public SqlServerLanguageProvider() : this(DbConfiguration.Get<ISqlExpressionProvider>(), DbConfiguration.Get<IObjectAccesor>()) { } public SqlServerLanguageProvider(ISqlExpressionProvider expressionProvider, IObjectAccesor objectAccesor) : base(expressionProvider, new SqlServerDialectProvider(), objectAccesor) { } } } ``` Fix bug in the Sql Server implementation
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Luval.Common; namespace Luval.Orm { public class SqlServerLanguageProvider : AnsiSqlLanguageProvider { public SqlServerLanguageProvider() : this(DbConfiguration.Get<ISqlExpressionProvider>(), DbConfiguration.Get<IObjectAccesor>()) { } public SqlServerLanguageProvider(ISqlExpressionProvider expressionProvider, IObjectAccesor objectAccesor) : base(expressionProvider, new SqlServerDialectProvider(), objectAccesor) { } public override string GetLastIdentityInsert() { return "SELECT SCOPE_IDENTITY()"; } } } ```
26a16229-0fcd-4d29-aa74-fa018b662197
{ "language": "C#" }
```c# @model IEnumerable<Discord.WebSocket.SocketGuild> <table class="table"> <thead> <tr> <th> @Html.DisplayName("GuildId") </th> <th> @Html.DisplayName("GuildName") </th> <th></th> </tr> </thead> <tbody> @foreach(var guild in Model) { <tr> <td> @Html.DisplayFor(modelItem => guild.Id) </td> <td> @Html.DisplayFor(modelItem => guild.Name) </td> <td> <a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">Details</a> </td> </tr> } </tbody> </table>``` Use list-group instead of a table.
```c# @model IEnumerable<Discord.WebSocket.SocketGuild> <div class="list-group"> @foreach(var guild in Model) { <a class="list-group-item list-group-item-action" asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a> } </div>```
237893a9-4469-45dd-9652-f4a986d68e01
{ "language": "C#" }
```c# using System; using System.Web.Mvc; using System.Web.Routing; using Castle.MicroKernel; namespace SnittListan.IoC { public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKernel kernel; public WindsorControllerFactory(IKernel kernel) { this.kernel = kernel; } public override IController CreateController(RequestContext requestContext, string controllerName) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } try { return kernel.Resolve<IController>(controllerName + "controller"); } catch (ComponentNotFoundException ex) { throw new ApplicationException(string.Format("No controller with name '{0}' found", controllerName), ex); } } public override void ReleaseController(IController controller) { if (controller == null) { throw new ArgumentNullException("controller"); } kernel.ReleaseComponent(controller); } } } ``` Throw HttpException when trying to resolve unknown controller
```c# using System; using System.Web.Mvc; using System.Web.Routing; using Castle.MicroKernel; using System.Web; namespace SnittListan.IoC { public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKernel kernel; public WindsorControllerFactory(IKernel kernel) { this.kernel = kernel; } public override IController CreateController(RequestContext requestContext, string controllerName) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } if (controllerName == null) { throw new HttpException(404, string.Format("The controller path '{0}' could not be found.", controllerName)); } try { return kernel.Resolve<IController>(controllerName + "controller"); } catch (ComponentNotFoundException ex) { throw new ApplicationException(string.Format("No controller with name '{0}' found", controllerName), ex); } } public override void ReleaseController(IController controller) { if (controller == null) { throw new ArgumentNullException("controller"); } kernel.ReleaseComponent(controller); } } } ```
220a41f9-ed95-4689-b5fd-64c9490c06e2
{ "language": "C#" }
```c# using System.Security.Cryptography.X509Certificates; using PeNet.Structures; namespace PeNet.Parser { internal class PKCS7Parser : SafeParser<X509Certificate2> { private readonly WIN_CERTIFICATE _winCertificate; internal PKCS7Parser(WIN_CERTIFICATE winCertificate) : base(null, 0) { _winCertificate = winCertificate; } protected override X509Certificate2 ParseTarget() { if (_winCertificate?.wCertificateType != (ushort) Constants.WinCertificateType.WIN_CERT_TYPE_PKCS_SIGNED_DATA) { return null; } var cert = _winCertificate.bCertificate; return new X509Certificate2(cert); } } }``` Use collection of certificates to parse pkcs7
```c# using System.Security.Cryptography.X509Certificates; using PeNet.Structures; namespace PeNet.Parser { internal class PKCS7Parser : SafeParser<X509Certificate2> { private readonly WIN_CERTIFICATE _winCertificate; internal PKCS7Parser(WIN_CERTIFICATE winCertificate) : base(null, 0) { _winCertificate = winCertificate; } protected override X509Certificate2 ParseTarget() { if (_winCertificate?.wCertificateType != (ushort) Constants.WinCertificateType.WIN_CERT_TYPE_PKCS_SIGNED_DATA) { return null; } var pkcs7 = _winCertificate.bCertificate; var collection = new X509Certificate2Collection(); collection.Import(pkcs7); if (collection.Count == 0) return null; return collection[0]; } } }```
59e18c10-6eb2-4fb2-8ac2-d07bae001d4f
{ "language": "C#" }
```c# using System; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace ScriptSharp.ScriptEngine { public class CSharpScriptEngine { private static ScriptState<object> scriptState = null; public static object Execute(string code) { scriptState = scriptState == null ? CSharpScript.RunAsync(code).Result : scriptState.ContinueWithAsync(code).Result; if (scriptState.ReturnValue != null && !string.IsNullOrEmpty(scriptState.ReturnValue.ToString())) return scriptState.ReturnValue; return ""; } } } ``` Change return type of script engine
```c# using System; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace ScriptSharp.ScriptEngine { public class CSharpScriptEngine { private static ScriptState<object> scriptState = null; public static object Execute(string code) { scriptState = scriptState == null ? CSharpScript.RunAsync(code).Result : scriptState.ContinueWithAsync(code).Result; if (scriptState.ReturnValue != null && !string.IsNullOrEmpty(scriptState.ReturnValue.ToString())) return scriptState.ReturnValue; return null; } } } ```
8f58b70a-62bc-4118-a9ca-663b31bda2de
{ "language": "C#" }
```c# using Starcounter; using System; namespace RealEstateAgencyFranchise.Controllers { internal class OfficeController { public Json Get(long officeObjectNo) { throw new NotImplementedException(); } } } ``` Implement getting data for office details
```c# using RealEstateAgencyFranchise.Database; using Starcounter; using System.Linq; namespace RealEstateAgencyFranchise.Controllers { internal class OfficeController { public Json Get(ulong officeObjectNo) { return Db.Scope(() => { var offices = Db.SQL<Office>( "select o from Office o where o.ObjectNo = ?", officeObjectNo); if (offices == null || !offices.Any()) { return new Response() { StatusCode = 404, StatusDescription = "Office not found" }; } var office = offices.First; var json = new OfficeListJson { Data = office }; if (Session.Current == null) { Session.Current = new Session(SessionOptions.PatchVersioning); } json.Session = Session.Current; return json; }); } } } ```
78916559-3648-4abf-a903-d0085734a98b
{ "language": "C#" }
```c# using System; namespace Criteo.Profiling.Tracing.Utils { internal static class TimeUtils { private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static DateTime UtcNow { get { return HighResolutionDateTime.IsAvailable ? HighResolutionDateTime.UtcNow : DateTime.UtcNow; } } /// <summary> /// Create a UNIX timestamp from a UTC date time. Time is expressed in microseconds and not seconds. /// </summary> /// <see href="https://en.wikipedia.org/wiki/Unix_time"/> /// <param name="utcDateTime"></param> /// <returns></returns> public static long ToUnixTimestamp(DateTime utcDateTime) { return (long)(utcDateTime.Subtract(Epoch).TotalMilliseconds * 1000L); } } } ``` Change time utils visibility from internal to public
```c# using System; namespace Criteo.Profiling.Tracing.Utils { public static class TimeUtils { private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static DateTime UtcNow { get { return HighResolutionDateTime.IsAvailable ? HighResolutionDateTime.UtcNow : DateTime.UtcNow; } } /// <summary> /// Create a UNIX timestamp from a UTC date time. Time is expressed in microseconds and not seconds. /// </summary> /// <see href="https://en.wikipedia.org/wiki/Unix_time"/> /// <param name="utcDateTime"></param> /// <returns></returns> public static long ToUnixTimestamp(DateTime utcDateTime) { return (long)(utcDateTime.Subtract(Epoch).TotalMilliseconds * 1000L); } } } ```
82f72131-72ea-4fd8-aee5-6aa576193b7a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using SharpGraphEditor.Graph.Core.Elements; namespace SharpGraphEditor.Graph.Core.Algorithms { public class DepthFirstSearchAlgorithm : IAlgorithm { public string Name => "Depth first search"; public string Description => "Depth first search"; public void Run(IGraph graph, AlgorithmParameter p) { if (graph.Vertices.Count() == 0) { return; } graph.ChangeColor(graph.Vertices.ElementAt(0), VertexColor.Gray); var dfs = new Helpers.DepthFirstSearch(graph) { ProcessEdge = (v1, v2) => { graph.ChangeColor(v2, VertexColor.Gray); }, ProcessVertexLate = (v) => { graph.ChangeColor(v, VertexColor.Black); } }; dfs.Run(graph.Vertices.First()); } } } ``` Fix bug with DFS when some vertices painted in gray twice
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using SharpGraphEditor.Graph.Core.Elements; namespace SharpGraphEditor.Graph.Core.Algorithms { public class DepthFirstSearchAlgorithm : IAlgorithm { public string Name => "Depth first search"; public string Description => "Depth first search"; public void Run(IGraph graph, AlgorithmParameter p) { if (graph.Vertices.Count() == 0) { return; } graph.ChangeColor(graph.Vertices.ElementAt(0), VertexColor.Gray); var dfs = new Helpers.DepthFirstSearch(graph) { ProcessEdge = (v1, v2) => { if (v2.Color != VertexColor.Gray) { graph.ChangeColor(v2, VertexColor.Gray); } }, ProcessVertexLate = (v) => { graph.ChangeColor(v, VertexColor.Black); } }; dfs.Run(graph.Vertices.First()); } } } ```
8766f7f3-4ac9-4806-bbc8-acb363eb7d2f
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.AggregateService")] [assembly: AssemblyDescription("Autofac Aggregate Service Module")] [assembly: ComVisible(false)]``` Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.AggregateService")] [assembly: ComVisible(false)]```
32007987-12da-42c6-8b74-e6af9669dd2f
{ "language": "C#" }
```c# using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using NLog; using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration; using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HttpClientWrapper : IHttpClientWrapper { private readonly ILogger _logger; private readonly EmployerApprenticeshipsServiceConfiguration _configuration; public HttpClientWrapper(ILogger logger, EmployerApprenticeshipsServiceConfiguration configuration) { _logger = logger; _configuration = configuration; } public async Task<string> SendMessage<T>(T content, string url) { try { using (var httpClient = CreateHttpClient()) { var serializeObject = JsonConvert.SerializeObject(content); var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(serializeObject, Encoding.UTF8, "application/json") }); return response.Content.ToString(); } } catch (Exception ex) { _logger.Error(ex); } return null; } private HttpClient CreateHttpClient() { return new HttpClient { BaseAddress = new Uri(_configuration.Hmrc.BaseUrl) }; } } }``` Change httpclientwrapper to return the content as string async.
```c# using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using NLog; using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration; using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HttpClientWrapper : IHttpClientWrapper { private readonly ILogger _logger; private readonly EmployerApprenticeshipsServiceConfiguration _configuration; public HttpClientWrapper(ILogger logger, EmployerApprenticeshipsServiceConfiguration configuration) { _logger = logger; _configuration = configuration; } public async Task<string> SendMessage<T>(T content, string url) { try { using (var httpClient = CreateHttpClient()) { var serializeObject = JsonConvert.SerializeObject(content); var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(serializeObject, Encoding.UTF8, "application/json") }); return await response.Content.ReadAsStringAsync(); } } catch (Exception ex) { _logger.Error(ex); } return null; } private HttpClient CreateHttpClient() { return new HttpClient { BaseAddress = new Uri(_configuration.Hmrc.BaseUrl) }; } } }```
c57d47f3-ce84-4298-adde-669d12fd0186
{ "language": "C#" }
```c# using System; using RestSharp; using Newtonsoft.Json; using RestSharp.Portable; using RestSharp.Portable.Authenticators; using RestSharp.Portable.HttpClient; namespace AsterNET.ARI.Middleware.Default { public class Command : IRestCommand { internal RestClient Client; internal RestRequest Request; public Command(StasisEndpoint info, string path) { Client = new RestClient(info.AriEndPoint) { Authenticator = new HttpBasicAuthenticator(info.Username, info.Password) }; Request = new RestRequest(path); } public string UniqueId { get; set; } public string Url { get; set; } public string Method { get { return Request.Method.ToString(); } set { Request.Method = (RestSharp.Portable.Method) Enum.Parse(typeof (RestSharp.Portable.Method), value); } } public string Body { get; private set; } public void AddUrlSegment(string segName, string value) { Request.AddUrlSegment(segName, value); } public void AddParameter(string name, object value, Middleware.ParameterType type) { if (type == ParameterType.RequestBody) { Request.Serializer = new RestSharp.Portable.Serializers.JsonSerializer(); Request.AddParameter(name, JsonConvert.SerializeObject(value), (RestSharp.Portable.ParameterType)Enum.Parse(typeof(RestSharp.Portable.ParameterType), type.ToString())); } else { Request.AddParameter(name, value, (RestSharp.Portable.ParameterType)Enum.Parse(typeof(RestSharp.Portable.ParameterType), type.ToString())); } } } } ``` Fix bug with double serialization
```c# using System; using RestSharp.Portable; using RestSharp.Portable.Authenticators; using RestSharp.Portable.HttpClient; namespace AsterNET.ARI.Middleware.Default { public class Command : IRestCommand { internal RestClient Client; internal RestRequest Request; public Command(StasisEndpoint info, string path) { Client = new RestClient(info.AriEndPoint) { Authenticator = new HttpBasicAuthenticator(info.Username, info.Password) }; Request = new RestRequest(path) {Serializer = new RestSharp.Portable.Serializers.JsonSerializer()}; } public string UniqueId { get; set; } public string Url { get; set; } public string Method { get { return Request.Method.ToString(); } set { Request.Method = (RestSharp.Portable.Method) Enum.Parse(typeof (RestSharp.Portable.Method), value); } } public string Body { get; private set; } public void AddUrlSegment(string segName, string value) { Request.AddUrlSegment(segName, value); } public void AddParameter(string name, object value, Middleware.ParameterType type) { Request.AddParameter(name, value, (RestSharp.Portable.ParameterType)Enum.Parse(typeof(RestSharp.Portable.ParameterType), type.ToString())); } } } ```
e48d0284-69be-476b-9cd2-c73f8d40645c
{ "language": "C#" }
```c# using System; using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; using Object = UnityEngine.Object; [CreateAssetMenu(fileName = "Example.asset", menuName = "New Example ScriptableObject")] public class ScriptableObjectExample : ScriptableObject { [EasyButtons.Button] public void SayHello() { Debug.Log("Hello"); } } ``` Remove unnecessary usings in example script
```c# using UnityEngine; [CreateAssetMenu(fileName = "Example.asset", menuName = "New Example ScriptableObject")] public class ScriptableObjectExample : ScriptableObject { [EasyButtons.Button] public void SayHello() { Debug.Log("Hello"); } } ```
d635e72b-4f2f-4e02-ba21-04942269a202
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using ExpressionToCodeLib; using Xunit; namespace ExpressionToCodeTest { public class ValueTupleTests { [Fact] public void ExpressionCompileValueTupleEqualsWorks() { var tuple = (1, 3); var tuple2 = (1, "123".Length); Expression<Func<bool>> expr = () => tuple.Equals(tuple2); Assert.True(expr.Compile()()); } [Fact] public void FastExpressionCompileValueTupleEqualsWorks() { var tuple = (1, 3); (int, int Length) tuple2 = (1, "123".Length); ValueTuple<int,int> x; var expr = FastExpressionCompiler.ExpressionCompiler.Compile(() => tuple.Equals(tuple2)); Assert.True(expr()); } [Fact] public void AssertingOnValueTupleEqualsWorks() { var tuple = (1, 3); var tuple2 = (1, "123".Length); Expression<Func<bool>> expr = () => tuple.Equals(tuple2); Assert.True(expr.Compile()()); PAssert.That(() => tuple.Equals(tuple2)); } } } ``` Rearrange test to better self-document what currently works and what does not.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using ExpressionToCodeLib; using Xunit; namespace ExpressionToCodeTest { public class ValueTupleTests { [Fact] public void ExpressionWithValueTupleEqualsCanCompile() { var tuple = (1, 3); var tuple2 = (1, "123".Length); Expression<Func<int>> ok1 = () => tuple.Item1; Expression<Func<int>> ok2 = () => tuple.GetHashCode(); Expression<Func<Tuple<int, int>>> ok3 = () => tuple.ToTuple(); ok1.Compile(); ok2.Compile(); ok3.Compile(); Expression<Func<bool>> err1 = () => tuple.Equals(tuple2); Expression<Func<int>> err2 = () => tuple.CompareTo(tuple2); err1.Compile();//crash err2.Compile();//crash } [Fact] public void FastExpressionCompileValueTupleEqualsWorks() { var tuple = (1, 3); (int, int Length) tuple2 = (1, "123".Length); var expr = FastExpressionCompiler.ExpressionCompiler.Compile(() => tuple.Equals(tuple2)); Assert.True(expr()); } [Fact] public void AssertingOnValueTupleEqualsWorks() { var tuple = (1, 3); var tuple2 = (1, "123".Length); Expression<Func<bool>> expr = () => tuple.Equals(tuple2); Assert.True(expr.Compile()()); PAssert.That(() => tuple.Equals(tuple2)); } } } ```
9748d496-36d3-4d89-a5d0-eb56fa0a34fa
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Objects.Types; using osu.Game.Database; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Osu.Objects { public class Spinner : OsuHitObject, IHasEndTime { public double EndTime { get; set; } public double Duration => EndTime - StartTime; /// <summary> /// Number of spins required to finish the spinner without miss. /// </summary> public int SpinsRequired { get; protected set; } = 1; public override bool NewCombo => true; public override void ApplyDefaults(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaults(controlPointInfo, difficulty); SpinsRequired = (int)(Duration / 1000 * BeatmapDifficulty.DifficultyRange(difficulty.OverallDifficulty, 3, 5, 7.5)); } } } ``` Make spinners easier for now
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Objects.Types; using osu.Game.Database; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Osu.Objects { public class Spinner : OsuHitObject, IHasEndTime { public double EndTime { get; set; } public double Duration => EndTime - StartTime; /// <summary> /// Number of spins required to finish the spinner without miss. /// </summary> public int SpinsRequired { get; protected set; } = 1; public override bool NewCombo => true; public override void ApplyDefaults(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaults(controlPointInfo, difficulty); SpinsRequired = (int)(Duration / 1000 * BeatmapDifficulty.DifficultyRange(difficulty.OverallDifficulty, 3, 5, 7.5)); // spinning doesn't match 1:1 with stable, so let's fudge them easier for the time being. SpinsRequired = (int)(SpinsRequired * 0.6); } } } ```
b8e51d35-505a-4d56-88e5-6631bffb2ca3
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Editor.Razor; using Microsoft.VisualStudio.Text.Editor; using MonoDevelop.Ide.CodeCompletion; namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor.Editor { internal class DefaultVisualStudioCompletionBroker : VisualStudioCompletionBroker { public override bool IsCompletionActive(ITextView textView) { if (textView == null) { throw new ArgumentNullException(nameof(textView)); } if (textView.HasAggregateFocus) { return CompletionWindowManager.IsVisible || (textView.Properties.TryGetProperty<bool>("RoslynCompletionPresenterSession.IsCompletionActive", out var visible) && visible); } // Text view does not have focus, if the completion window is visible it's for a different text view. return false; } } } ``` Clean up mac completion broker.
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Editor.Razor; using Microsoft.VisualStudio.Text.Editor; using MonoDevelop.Ide.CodeCompletion; namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor.Editor { internal class DefaultVisualStudioCompletionBroker : VisualStudioCompletionBroker { private const string IsCompletionActiveKey = "RoslynCompletionPresenterSession.IsCompletionActive"; public override bool IsCompletionActive(ITextView textView) { if (textView == null) { throw new ArgumentNullException(nameof(textView)); } if (!textView.HasAggregateFocus) { // Text view does not have focus, if the completion window is visible it's for a different text view. return false; } if (CompletionWindowManager.IsVisible) { return true; } if (textView.Properties.TryGetProperty<bool>(IsCompletionActiveKey, out var visible)) { return visible; } return false; } } } ```
05da0872-c303-4dc8-ab34-6ac9aafcb4dc
{ "language": "C#" }
```c# using Contentful.Core.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { [JsonConverter(typeof(EditorInterfaceControlJsonConverter))] public class EditorInterfaceControl { public string FieldId { get; set; } public string WidgetId { get; set; } public EditorInterfaceControlSettings Settings { get; set; } } } ``` Add null handling for editorinterface settings
```c# using Contentful.Core.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { [JsonConverter(typeof(EditorInterfaceControlJsonConverter))] public class EditorInterfaceControl { public string FieldId { get; set; } public string WidgetId { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public EditorInterfaceControlSettings Settings { get; set; } } } ```
1a1751c9-1997-4999-8581-0e6cc946a37b
{ "language": "C#" }
```c# // AssemblyInfo.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("mscorlib")] [assembly: AssemblyDescription("Script# Core Assembly")] [assembly: ScriptAssembly("core")] ``` Update mscorlib assembly name to match eventual module name
```c# // AssemblyInfo.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("mscorlib")] [assembly: AssemblyDescription("Script# Core Assembly")] [assembly: ScriptAssembly("ss")] ```
b62a5449-14f4-4642-baa0-379ce34d3203
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; // Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show // up in the Load context, which means that we can use ServiceHub and other nice things. [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.AspNetCore.Blazor.AngleSharp", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "0.9.9.0", NewVersion = "0.9.9.0")] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.AspNetCore.Blazor.Razor.Extensions", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "1.0.0.0", NewVersion = "1.0.0.0")] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "1.0.0.0", NewVersion = "1.0.0.0")] ``` Remove binding redirects for missing assemblies
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; // Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show // up in the Load context, which means that we can use ServiceHub and other nice things. [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "1.0.0.0", NewVersion = "1.0.0.0")] ```
165146b5-4853-4517-80a9-0d4fff468dbc
{ "language": "C#" }
```c# using System; using NUnit.Framework; namespace Atata.Tests { public class AtataContextBuilderTests : UITestFixtureBase { [Test] public void AtataContextBuilder_Build_WithoutDriver() { InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => AtataContext.Configure().Build()); Assert.That(exception.Message, Does.Contain("no driver is specified")); } [Test] public void AtataContextBuilder_OnDriverCreated() { int executionsCount = 0; AtataContext.Configure(). UseChrome(). OnDriverCreated(driver => { executionsCount++; }). Build(); Assert.That(executionsCount, Is.EqualTo(1)); } [Test] public void AtataContextBuilder_OnDriverCreated_RestartDriver() { int executionsCount = 0; AtataContext.Configure(). UseChrome(). OnDriverCreated(() => { executionsCount++; }). Build(); AtataContext.Current.RestartDriver(); Assert.That(executionsCount, Is.EqualTo(2)); } } } ``` Add AtataContextBuilder_OnBuilding and AtataContextBuilder_OnBuilding_WithoutDriver tests
```c# using System; using NUnit.Framework; namespace Atata.Tests { public class AtataContextBuilderTests : UITestFixtureBase { [Test] public void AtataContextBuilder_Build_WithoutDriver() { InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => AtataContext.Configure().Build()); Assert.That(exception.Message, Does.Contain("no driver is specified")); } [Test] public void AtataContextBuilder_OnBuilding() { int executionsCount = 0; AtataContext.Configure(). UseChrome(). OnBuilding(() => executionsCount++). Build(); Assert.That(executionsCount, Is.EqualTo(1)); } [Test] public void AtataContextBuilder_OnBuilding_WithoutDriver() { int executionsCount = 0; Assert.Throws<InvalidOperationException>(() => AtataContext.Configure(). UseDriver(() => null). OnBuilding(() => executionsCount++). Build()); Assert.That(executionsCount, Is.EqualTo(1)); } [Test] public void AtataContextBuilder_OnDriverCreated() { int executionsCount = 0; AtataContext.Configure(). UseChrome(). OnDriverCreated(driver => executionsCount++). Build(); Assert.That(executionsCount, Is.EqualTo(1)); } [Test] public void AtataContextBuilder_OnDriverCreated_RestartDriver() { int executionsCount = 0; AtataContext.Configure(). UseChrome(). OnDriverCreated(() => executionsCount++). Build(); AtataContext.Current.RestartDriver(); Assert.That(executionsCount, Is.EqualTo(2)); } } } ```
fa71e264-03ce-42c3-9a89-0cdd61a3e192
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Framework.Configuration; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Identity { /// <summary> /// Default services /// </summary> public class IdentityEntityFrameworkServices { public static IServiceCollection GetDefaultServices(Type userType, Type roleType, Type contextType, Type keyType = null, IConfiguration config = null) { Type userStoreType; Type roleStoreType; if (keyType != null) { userStoreType = typeof(UserStore<,,,>).MakeGenericType(userType, roleType, contextType, keyType); roleStoreType = typeof(RoleStore<,,>).MakeGenericType(roleType, contextType, keyType); } else { userStoreType = typeof(UserStore<,,>).MakeGenericType(userType, roleType, contextType); roleStoreType = typeof(RoleStore<,>).MakeGenericType(roleType, contextType); } var services = new ServiceCollection(); services.AddScoped( typeof(IUserStore<>).MakeGenericType(userType), userStoreType); services.AddScoped( typeof(IRoleStore<>).MakeGenericType(roleType), roleStoreType); return services; } } }``` Remove extra config param that's not used
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Framework.Configuration; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Identity { /// <summary> /// Default services /// </summary> public class IdentityEntityFrameworkServices { public static IServiceCollection GetDefaultServices(Type userType, Type roleType, Type contextType, Type keyType = null) { Type userStoreType; Type roleStoreType; if (keyType != null) { userStoreType = typeof(UserStore<,,,>).MakeGenericType(userType, roleType, contextType, keyType); roleStoreType = typeof(RoleStore<,,>).MakeGenericType(roleType, contextType, keyType); } else { userStoreType = typeof(UserStore<,,>).MakeGenericType(userType, roleType, contextType); roleStoreType = typeof(RoleStore<,>).MakeGenericType(roleType, contextType); } var services = new ServiceCollection(); services.AddScoped( typeof(IUserStore<>).MakeGenericType(userType), userStoreType); services.AddScoped( typeof(IRoleStore<>).MakeGenericType(roleType), roleStoreType); return services; } } }```
d7bfb2a5-1ab6-4b9c-91a7-e0065afe9882
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Screens.Edit.Setup { internal abstract class LabelledTextBoxWithPopover : LabelledTextBox, IHasPopover { public abstract Popover GetPopover(); protected override OsuTextBox CreateTextBox() => new PopoverTextBox { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, CornerRadius = CORNER_RADIUS, OnFocused = this.ShowPopover }; internal class PopoverTextBox : OsuTextBox { public Action OnFocused; protected override bool OnDragStart(DragStartEvent e) { // This text box is intended to be "read only" without actually specifying that. // As such we don't want to allow the user to select its content with a drag. return false; } protected override void OnFocus(FocusEvent e) { OnFocused?.Invoke(); base.OnFocus(e); GetContainingInputManager().TriggerFocusContention(this); } } } } ``` Fix interaction with popover when textbox is disabled
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Screens.Edit.Setup { internal abstract class LabelledTextBoxWithPopover : LabelledTextBox, IHasPopover { public abstract Popover GetPopover(); protected override OsuTextBox CreateTextBox() => new PopoverTextBox { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, CornerRadius = CORNER_RADIUS, OnFocused = this.ShowPopover }; internal class PopoverTextBox : OsuTextBox { public Action OnFocused; protected override bool OnDragStart(DragStartEvent e) { // This text box is intended to be "read only" without actually specifying that. // As such we don't want to allow the user to select its content with a drag. return false; } protected override void OnFocus(FocusEvent e) { if (Current.Disabled) return; OnFocused?.Invoke(); base.OnFocus(e); GetContainingInputManager().TriggerFocusContention(this); } } } } ```
da2973c3-d96e-497f-a080-6a4d3fe13f19
{ "language": "C#" }
```c# using System.IO; using System.Linq; namespace ELFinder.Connector.Drivers.FileSystem.Extensions { /// <summary> /// File system info extensions /// </summary> public static class FIleSystemInfoExtensions { #region Extension methods /// <summary> /// Get visible files in directory /// </summary> /// <param name="info">Directory info</param> /// <returns>Result directories</returns> public static FileInfo[] GetVisibleFiles(this DirectoryInfo info) { return info.GetFiles().Where(x => !x.IsHidden()).ToArray(); } /// <summary> /// Get visible directories /// </summary> /// <param name="info">Directory info</param> /// <returns>Result directories</returns> public static DirectoryInfo[] GetVisibleDirectories(this DirectoryInfo info) { return info.GetDirectories().Where(x => !x.IsHidden()).ToArray(); } /// <summary> /// Get if file is hidden /// </summary> /// <param name="info">File info</param> /// <returns>True/False based on result</returns> public static bool IsHidden(this FileSystemInfo info) { return (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; } #endregion } }``` Fix Unable to connect to backend on access denied
```c# using System.IO; using System.Linq; namespace ELFinder.Connector.Drivers.FileSystem.Extensions { /// <summary> /// File system info extensions /// </summary> public static class FIleSystemInfoExtensions { #region Extension methods /// <summary> /// Get visible files in directory /// </summary> /// <param name="info">Directory info</param> /// <returns>Result directories</returns> public static FileInfo[] GetVisibleFiles(this DirectoryInfo info) { try { return info.GetFiles().Where(x => !x.IsHidden()).ToArray(); } catch (System.Exception) { return new FileInfo[0]; } } /// <summary> /// Get visible directories /// </summary> /// <param name="info">Directory info</param> /// <returns>Result directories</returns> public static DirectoryInfo[] GetVisibleDirectories(this DirectoryInfo info) { try { return info.GetDirectories().Where(x => !x.IsHidden()).ToArray(); } catch (System.Exception) { return new DirectoryInfo[0]; } } /// <summary> /// Get if file is hidden /// </summary> /// <param name="info">File info</param> /// <returns>True/False based on result</returns> public static bool IsHidden(this FileSystemInfo info) { return (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; } #endregion } }```
70a9cb01-1891-4f58-93a2-1138e70dc7cd
{ "language": "C#" }
```c# // MvxPhoneCallTask.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using System; using Windows.System; namespace Cirrious.MvvmCross.Plugins.PhoneCall.WindowsStore { public class MvxPhoneCallTask : IMvxPhoneCallTask { public void MakePhoneCall(string name, string number) { // TODO! This is far too skype specific // TODO! name/number need looking at // this is the best I can do so far... var uri = new Uri("skype:" + number + "?call", UriKind.Absolute); Launcher.LaunchUriAsync(uri); } } }``` Use the tel uri in windows store for phone calls
```c# // MvxPhoneCallTask.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using System; using Windows.System; namespace Cirrious.MvvmCross.Plugins.PhoneCall.WindowsStore { public class MvxPhoneCallTask : IMvxPhoneCallTask { public void MakePhoneCall(string name, string number) { //The tel URI for Telephone Numbers : http://tools.ietf.org/html/rfc3966 //Handled by skype var uri = new Uri("tel:" + Uri.EscapeDataString(phoneNumber), UriKind.Absolute); Launcher.LaunchUriAsync(uri); } } } ```
b4a8af78-7dbc-46a0-a846-0ba5bf936d23
{ "language": "C#" }
```c# using System; using System.Linq; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace HealthNet.AspNetCore { public static class HealthNetMiddlewareExtensions { private static readonly Type VersionProviderType = typeof(IVersionProvider); private static readonly Type SystemCheckerType = typeof(ISystemChecker); public static IApplicationBuilder UseHealthNet(this IApplicationBuilder builder) { return builder.UseMiddleware<HealthNetMiddleware>(); } public static IServiceCollection AddHealthNet(this IServiceCollection service) { return service.AddTransient<HealthCheckService>(); } public static IServiceCollection AddHealthNet<THealthNetConfig>(this IServiceCollection service) where THealthNetConfig : class, IHealthNetConfiguration { var assembyTypes = typeof(THealthNetConfig).Assembly.GetTypes(); service.AddSingleton<IHealthNetConfiguration, THealthNetConfig>(); var versionProvider = assembyTypes .FirstOrDefault(x => x.IsClass && !x.IsAbstract && VersionProviderType.IsAssignableFrom(x)); service.AddSingleton(VersionProviderType, versionProvider ?? typeof(AssemblyFileVersionProvider)); var systemCheckers = assembyTypes .Where(x => x.IsClass && !x.IsAbstract && SystemCheckerType.IsAssignableFrom(x)); foreach (var checkerType in systemCheckers) { service.AddTransient(SystemCheckerType, checkerType); } return service.AddHealthNet(); } } }``` Allow option to prevent system checkers from being auto registered
```c# using System; using System.Linq; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace HealthNet.AspNetCore { public static class HealthNetMiddlewareExtensions { private static readonly Type VersionProviderType = typeof(IVersionProvider); private static readonly Type SystemCheckerType = typeof(ISystemChecker); public static IApplicationBuilder UseHealthNet(this IApplicationBuilder builder) { return builder.UseMiddleware<HealthNetMiddleware>(); } public static IServiceCollection AddHealthNet(this IServiceCollection service) { return service.AddTransient<HealthCheckService>(); } public static IServiceCollection AddHealthNet<THealthNetConfig>(this IServiceCollection service, bool autoRegisterCheckers = true) where THealthNetConfig : class, IHealthNetConfiguration { var assembyTypes = typeof(THealthNetConfig).Assembly.GetTypes(); service.AddSingleton<IHealthNetConfiguration, THealthNetConfig>(); var versionProvider = assembyTypes .FirstOrDefault(x => x.IsClass && !x.IsAbstract && VersionProviderType.IsAssignableFrom(x)); service.AddSingleton(VersionProviderType, versionProvider ?? typeof(AssemblyFileVersionProvider)); if (autoRegisterCheckers) { var systemCheckers = assembyTypes .Where(x => x.IsClass && !x.IsAbstract && SystemCheckerType.IsAssignableFrom(x)); foreach (var checkerType in systemCheckers) { service.AddTransient(SystemCheckerType, checkerType); } } return service.AddHealthNet(); } } }```
8bcb7f54-464a-427b-a9a9-b3d7e962f6f6
{ "language": "C#" }
```c# using Newtonsoft.Json; using Telegram.Bot.Types.ReplyMarkups; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class ReplyMarkupSerializationTests { [Theory(DisplayName = "Should serialize request poll keyboard button")] [InlineData(null)] [InlineData("regular")] [InlineData("quiz")] public void Should_Serialize_Request_Poll_Keyboard_Button(string type) { IReplyMarkup replyMarkup = new ReplyKeyboardMarkup( KeyboardButton.WithRequestPoll("Create a poll", type) ); string serializedReplyMarkup = JsonConvert.SerializeObject(replyMarkup); string expectedType = string.IsNullOrEmpty(type) ? "{}" : @$"{{""type"":""{type}""}}"; Assert.Contains(@$"""request_poll"":{expectedType}", serializedReplyMarkup); } } } ``` Change string formatting due to appveyor failing
```c# using Newtonsoft.Json; using Telegram.Bot.Types.ReplyMarkups; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class ReplyMarkupSerializationTests { [Theory(DisplayName = "Should serialize request poll keyboard button")] [InlineData(null)] [InlineData("regular")] [InlineData("quiz")] public void Should_Serialize_Request_Poll_Keyboard_Button(string type) { IReplyMarkup replyMarkup = new ReplyKeyboardMarkup( KeyboardButton.WithRequestPoll("Create a poll", type) ); string serializedReplyMarkup = JsonConvert.SerializeObject(replyMarkup); string expectedType = string.IsNullOrEmpty(type) ? "{}" : string.Format(@"{{""type"":""{0}""}}", type); Assert.Contains(@$"""request_poll"":{expectedType}", serializedReplyMarkup); } } } ```
740fc848-7506-4748-9063-3d9ca825671c
{ "language": "C#" }
```c# using Halforbit.DataStores.FileStores.Implementation; using Halforbit.DataStores.FileStores.LocalStorage.Implementation; using Halforbit.Facets.Attributes; using System; namespace HalfOrbit.DataStores.FileStores.LocalStorage.Attributes { public class RootPathAttribute : FacetParameterAttribute { public RootPathAttribute(string value = null, string configKey = null) : base(value, configKey) { } public override Type TargetType => typeof(LocalFileStore); public override string ParameterName => "rootPath"; public override Type[] ImpliedTypes => new Type[] { typeof(FileStoreDataStore<,>) }; } } ``` Fix a small, old typo
```c# using Halforbit.DataStores.FileStores.Implementation; using Halforbit.DataStores.FileStores.LocalStorage.Implementation; using Halforbit.Facets.Attributes; using System; namespace Halforbit.DataStores.FileStores.LocalStorage.Attributes { public class RootPathAttribute : FacetParameterAttribute { public RootPathAttribute(string value = null, string configKey = null) : base(value, configKey) { } public override Type TargetType => typeof(LocalFileStore); public override string ParameterName => "rootPath"; public override Type[] ImpliedTypes => new Type[] { typeof(FileStoreDataStore<,>) }; } } ```
64ee7bba-8dea-490a-a944-7d0b8059fb91
{ "language": "C#" }
```c# using System; using Platform.Data.Core.Pairs; namespace Platform.Data.Core.Sequences { public struct SequencesOptions // TODO: To use type parameter <TLink> the ILinks<TLink> must contain GetConstants function. { public ulong SequenceMarkerLink; public bool UseCascadeUpdate; public bool UseCascadeDelete; public bool UseSequenceMarker; public bool UseCompression; public bool UseGarbageCollection; public bool EnforceSingleSequenceVersionOnWrite; public bool EnforceSingleSequenceVersionOnRead; // TODO: Реализовать компактификацию при чтении public bool UseRequestMarker; public bool StoreRequestResults; public void InitOptions(ILinks<ulong> links) { if (SequenceMarkerLink == LinksConstants.Null) SequenceMarkerLink = links.Create(LinksConstants.Itself, LinksConstants.Itself); } public void ValidateOptions() { if (UseGarbageCollection && !UseSequenceMarker) throw new NotSupportedException("To use garbage collection UseSequenceMarker option must be on."); } } } ``` Create Sequence Marker only if it is used.
```c# using System; using Platform.Data.Core.Pairs; namespace Platform.Data.Core.Sequences { public struct SequencesOptions // TODO: To use type parameter <TLink> the ILinks<TLink> must contain GetConstants function. { public ulong SequenceMarkerLink; public bool UseCascadeUpdate; public bool UseCascadeDelete; public bool UseSequenceMarker; public bool UseCompression; public bool UseGarbageCollection; public bool EnforceSingleSequenceVersionOnWrite; // TODO: Реализовать компактификацию при чтении //public bool EnforceSingleSequenceVersionOnRead; //public bool UseRequestMarker; //public bool StoreRequestResults; public void InitOptions(ILinks<ulong> links) { if (UseSequenceMarker && SequenceMarkerLink == LinksConstants.Null) SequenceMarkerLink = links.Create(LinksConstants.Itself, LinksConstants.Itself); } public void ValidateOptions() { if (UseGarbageCollection && !UseSequenceMarker) throw new NotSupportedException("To use garbage collection UseSequenceMarker option must be on."); } } } ```
b4a9b7b1-2790-4257-a012-0c36a80f8bba
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mios.Payment { [Serializable] public class VerificationProviderException : Exception { public VerificationProviderException() { } public VerificationProviderException(string message) : base(message) { } public VerificationProviderException(string message, Exception inner) : base(message, inner) { } protected VerificationProviderException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } } ``` Add property for response content, mapped to Data collection.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mios.Payment { [Serializable] public class VerificationProviderException : Exception { public string ResponseContent { get { return Data["Response"] as string; } set { Data["Response"] = value; } } public VerificationProviderException() { } public VerificationProviderException(string message) : base(message) { } public VerificationProviderException(string message, Exception inner) : base(message, inner) { } protected VerificationProviderException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } } ```
15b78eba-1feb-4ad8-b740-f168b474e12e
{ "language": "C#" }
```c# using System.Collections; using System.Linq; using System.Text.RegularExpressions; public class BlockbustersComponentSolver : ComponentSolver { public BlockbustersComponentSolver(TwitchModule module) : base(module) { selectables = Module.BombComponent.GetComponent<KMSelectable>().Children; ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Press a tile using !{0} 2E. Tiles are specified by column then row."); } int CharacterToIndex(char character) => character >= 'a' ? character - 'a' : character - '1'; protected internal override IEnumerator RespondToCommandInternal(string inputCommand) { inputCommand = Regex.Replace(inputCommand, @"(\W|_|^(press|submit|click|answer))", ""); if (inputCommand.Length != 2) yield break; int column = CharacterToIndex(inputCommand[0]); int row = CharacterToIndex(inputCommand[1]); if (column.InRange(0, 4) && row.InRange(0, 4) && (row < 4 || column % 2 == 1)) { yield return null; yield return DoInteractionClick(selectables[Enumerable.Range(0, column).Select(n => (n % 2 == 0) ? 4 : 5).Sum() + row]); } } private readonly KMSelectable[] selectables; } ``` Fix Blockbusters not accepting uppercase input
```c# using System.Collections; using System.Linq; using System.Text.RegularExpressions; public class BlockbustersComponentSolver : ComponentSolver { public BlockbustersComponentSolver(TwitchModule module) : base(module) { selectables = Module.BombComponent.GetComponent<KMSelectable>().Children; ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Press a tile using !{0} 2E. Tiles are specified by column then row."); } int CharacterToIndex(char character) => character >= 'a' ? character - 'a' : character - '1'; protected internal override IEnumerator RespondToCommandInternal(string inputCommand) { inputCommand = Regex.Replace(inputCommand.ToLowerInvariant(), @"(\W|_|^(press|submit|click|answer))", ""); if (inputCommand.Length != 2) yield break; int column = CharacterToIndex(inputCommand[0]); int row = CharacterToIndex(inputCommand[1]); if (column.InRange(0, 4) && row.InRange(0, 4) && (row < 4 || column % 2 == 1)) { yield return null; yield return DoInteractionClick(selectables[Enumerable.Range(0, column).Select(n => (n % 2 == 0) ? 4 : 5).Sum() + row]); } } private readonly KMSelectable[] selectables; } ```
f61879e2-e81b-4a9a-836a-253298d42d54
{ "language": "C#" }
```c#  using Xunit; [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)] ``` Set DOTNET_HOST_PATH so Roslyn tasks will use the right host
```c#  using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Xml.Linq; using Xunit; [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)] // Register test framework for assembly fixture [assembly: TestFramework("Xunit.NetCore.Extensions.XunitTestFrameworkWithAssemblyFixture", "Xunit.NetCore.Extensions")] [assembly: AssemblyFixture(typeof(MSBuildTestAssemblyFixture))] public class MSBuildTestAssemblyFixture { public MSBuildTestAssemblyFixture() { // Find correct version of "dotnet", and set DOTNET_HOST_PATH so that the Roslyn tasks will use the right host var currentFolder = System.AppContext.BaseDirectory; while (currentFolder != null) { string potentialVersionsPropsPath = Path.Combine(currentFolder, "build", "Versions.props"); if (File.Exists(potentialVersionsPropsPath)) { var doc = XDocument.Load(potentialVersionsPropsPath); var ns = doc.Root.Name.Namespace; var cliVersionElement = doc.Root.Elements(ns + "PropertyGroup").Elements(ns + "DotNetCliVersion").FirstOrDefault(); if (cliVersionElement != null) { string cliVersion = cliVersionElement.Value; string dotnetPath = Path.Combine(currentFolder, "artifacts", ".dotnet", cliVersion, "dotnet"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { dotnetPath += ".exe"; } Environment.SetEnvironmentVariable("DOTNET_HOST_PATH", dotnetPath); } break; } currentFolder = Directory.GetParent(currentFolder)?.FullName; } } } ```
ccc5d93e-d42e-4609-b4f6-83b90eb3331b
{ "language": "C#" }
```c# namespace TraktApiSharp.Utils { using Newtonsoft.Json; using System.Threading.Tasks; internal static class Json { internal static readonly JsonSerializerSettings DEFAULT_JSON_SETTINGS = new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore }; internal static string Serialize(object value) { return JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS); } internal static TResult Deserialize<TResult>(string value) { return JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS); } internal static async Task<string> SerializeAsync(object value) { return await Task.Run(() => JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS)); } internal static async Task<TResult> DeserializeAsync<TResult>(string value) { return await Task.Run(() => JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS)); } } } ``` Remove async helper methods for json serialization.
```c# namespace TraktApiSharp.Utils { using Newtonsoft.Json; internal static class Json { internal static readonly JsonSerializerSettings DEFAULT_JSON_SETTINGS = new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore }; internal static string Serialize(object value) { return JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS); } internal static TResult Deserialize<TResult>(string value) { return JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS); } } } ```
6c65d082-840c-4134-91ef-588cc3732d49
{ "language": "C#" }
```c# using System; namespace UDIR.PAS2.OAuth.Client { internal class AuthorizationServer { public AuthorizationServer(Uri baseAddress) { BaseAddress = baseAddress; TokenEndpoint = new Uri(baseAddress, "/connect/token").ToString(); } public AuthorizationServer(string baseAddress) : this(new Uri(baseAddress)) { } public string TokenEndpoint { get; } public Uri BaseAddress { get; } } } ``` Use private accessor for property
```c# using System; namespace UDIR.PAS2.OAuth.Client { internal class AuthorizationServer { public AuthorizationServer(Uri baseAddress) { BaseAddress = baseAddress; TokenEndpoint = new Uri(baseAddress, "/connect/token").ToString(); } public AuthorizationServer(string baseAddress) : this(new Uri(baseAddress)) { } public string TokenEndpoint { get; private set; } public Uri BaseAddress { get; private set; } } } ```
1ac92fd6-0f76-4d09-bdf0-710de9a24714
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Driver; using MongoDB.Bson; using MongoDB.Bson.Serialization; using Newtonsoft.Json; namespace M101DotNet { public class Program { public static void Main(string[] args) { MainAsync(args).Wait(); Console.WriteLine(); Console.WriteLine("Press Enter"); Console.ReadLine(); } static async Task MainAsync(string[] args) { var connectionString = "mongodb://localhost:27017"; var client = new MongoClient(connectionString); var db = client.GetDatabase("test"); var person = new Person { Name = "Jones", Age = 30, Colors = new List<string> {"red", "blue"}, Pets = new List<Pet> { new Pet { Name = "Puffy", Type = "Pig" } } }; Console.WriteLine(person); // using (var writer = new JsonWriter(Console.Out)) // { // BsonSerializer.Serialize(writer, person); // }; } } }``` Use builtin MongoDB Bson serialization
```c# using System; using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Driver; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.IO; namespace M101DotNet { public class Program { public static void Main(string[] args) { MainAsync(args).Wait(); Console.WriteLine(); Console.WriteLine("Press Enter"); Console.ReadLine(); } static async Task MainAsync(string[] args) { var connectionString = "mongodb://localhost:27017"; var client = new MongoClient(connectionString); var db = client.GetDatabase("test"); var person = new Person { Name = "Jones", Age = 30, Colors = new List<string> {"red", "blue"}, Pets = new List<Pet> { new Pet { Name = "Puffy", Type = "Pig" } } }; Console.WriteLine(person); using (var writer = new JsonWriter(Console.Out)) { BsonSerializer.Serialize(writer, person); }; } } }```
7b4bd7bd-a111-4d45-bcb0-82396b577b34
{ "language": "C#" }
```c# using System.Collections.Generic; using Mono.Debugger.Cli.Debugging; using Mono.Debugger.Cli.Logging; namespace Mono.Debugger.Cli.Commands { public sealed class ThreadsCommand : ICommand { public string Name { get { return "Threads"; } } public string Description { get { return "Lists all active threads."; } } public IEnumerable<string> Arguments { get { return Argument.None(); } } public void Execute(CommandArguments args) { var session = SoftDebugger.Session; if (SoftDebugger.State == DebuggerState.Null) { Logger.WriteErrorLine("No session active."); return; } if (SoftDebugger.State == DebuggerState.Initialized) { Logger.WriteErrorLine("No process active."); return; } var threads = session.VirtualMachine.GetThreads(); foreach (var thread in threads) Logger.WriteInfoLine("[{0}] {1}: {2}", thread.Id, thread.Name, thread.ThreadState); } } } ``` Add a little more info to the thread listing.
```c# using System.Collections.Generic; using Mono.Debugger.Cli.Debugging; using Mono.Debugger.Cli.Logging; namespace Mono.Debugger.Cli.Commands { public sealed class ThreadsCommand : ICommand { public string Name { get { return "Threads"; } } public string Description { get { return "Lists all active threads."; } } public IEnumerable<string> Arguments { get { return Argument.None(); } } public void Execute(CommandArguments args) { var session = SoftDebugger.Session; if (SoftDebugger.State == DebuggerState.Null) { Logger.WriteErrorLine("No session active."); return; } if (SoftDebugger.State == DebuggerState.Initialized) { Logger.WriteErrorLine("No process active."); return; } var threads = session.VirtualMachine.GetThreads(); foreach (var thread in threads) { var id = thread.Id.ToString(); if (thread.IsThreadPoolThread) id += " (TP)"; Logger.WriteInfoLine("[{0}: {1}] {2}: {3}", thread.Domain.FriendlyName, id, thread.Name, thread.ThreadState); } } } } ```
6f93afa9-47e8-49d3-b6a0-2dbcbf7088e8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace Assent.Reporters.DiffPrograms { public class BeyondCompareDiffProgram : DiffProgramBase { static BeyondCompareDiffProgram() { var paths = new List<string>(); if (DiffReporter.IsWindows) { paths.AddRange(WindowsProgramFilePaths .SelectMany(p => new[] { $@"{p}\Beyond Compare 4\BCompare.exe", $@"{p}\Beyond Compare 3\BCompare.exe" }) .ToArray()); } else { paths.Add("/usr/bin/bcompare"); } DefaultSearchPaths = paths; } public static readonly IReadOnlyList<string> DefaultSearchPaths; public BeyondCompareDiffProgram() : base(DefaultSearchPaths) { } public BeyondCompareDiffProgram(IReadOnlyList<string> searchPaths) : base(searchPaths) { } protected override string CreateProcessStartArgs(string receivedFile, string approvedFile) { var defaultArgs = base.CreateProcessStartArgs(receivedFile, approvedFile); var argChar = DiffReporter.IsWindows ? "/" : "-"; return $"{defaultArgs} {argChar}solo" ; } } } ``` Add OSX default install location for BeyondCompare.
```c# using System; using System.Collections.Generic; using System.Linq; namespace Assent.Reporters.DiffPrograms { public class BeyondCompareDiffProgram : DiffProgramBase { static BeyondCompareDiffProgram() { var paths = new List<string>(); if (DiffReporter.IsWindows) { paths.AddRange(WindowsProgramFilePaths .SelectMany(p => new[] { $@"{p}\Beyond Compare 4\BCompare.exe", $@"{p}\Beyond Compare 3\BCompare.exe" }) .ToArray()); } else { paths.Add("/usr/bin/bcompare"); paths.Add("/usr/local/bin/bcompare"); } DefaultSearchPaths = paths; } public static readonly IReadOnlyList<string> DefaultSearchPaths; public BeyondCompareDiffProgram() : base(DefaultSearchPaths) { } public BeyondCompareDiffProgram(IReadOnlyList<string> searchPaths) : base(searchPaths) { } protected override string CreateProcessStartArgs(string receivedFile, string approvedFile) { var defaultArgs = base.CreateProcessStartArgs(receivedFile, approvedFile); var argChar = DiffReporter.IsWindows ? "/" : "-"; return $"{defaultArgs} {argChar}solo" ; } } } ```
286075dd-d839-4621-a22e-e5a87a719107
{ "language": "C#" }
```c# using System; using elbsms_core; namespace elbsms_console { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: elbsms_console <path to rom>"); return; } string romPath = args[0]; Cartridge cartridge = Cartridge.LoadFromFile(romPath); MasterSystem masterSystem = new MasterSystem(cartridge); try { while (true) { masterSystem.SingleStep(); } } catch (NotImplementedException ex) { Console.WriteLine(ex.Message); } } } } ``` Add some simple runtime stats while implementing the Z80 core
```c# using System; using System.Diagnostics; using elbsms_core; namespace elbsms_console { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: elbsms_console <path to rom>"); return; } string romPath = args[0]; Cartridge cartridge = Cartridge.LoadFromFile(romPath); MasterSystem masterSystem = new MasterSystem(cartridge); Console.WriteLine($"Starting: {DateTime.Now}"); Console.WriteLine(); ulong instructionCount = 0; var sw = Stopwatch.StartNew(); try { while (true) { instructionCount++; masterSystem.SingleStep(); } } catch (NotImplementedException ex) { Console.WriteLine(ex.Message); } sw.Stop(); Console.WriteLine(); Console.WriteLine($"Finished: {DateTime.Now}"); Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}ms Instructions: {instructionCount}, Instructions/ms: {instructionCount/(double)sw.ElapsedMilliseconds}"); } } } ```
390a27a3-01de-473f-a85a-69957e05befb
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyProduct("SqlStreamStore")] [assembly: AssemblyCopyright("Copyright Damian Hickey & Contributors 2015 - 2016")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")] ``` Make the next release version 0.1.1 (bug fixes)
```c# using System.Reflection; [assembly: AssemblyProduct("SqlStreamStore")] [assembly: AssemblyCopyright("Copyright Damian Hickey & Contributors 2015 - 2016")] [assembly: AssemblyVersion("0.1.1.0")] [assembly: AssemblyFileVersion("0.1.1.0")] ```
737f86d3-c316-473c-a623-bb1a971650c5
{ "language": "C#" }
```c# namespace Cash_Flow_Projection { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; using Serilog.Core; public class Program { public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information); public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureLogging((context, builder) => { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName) .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName) .Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}") .WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), compact: true, controlLevelSwitch: LogLevel) .MinimumLevel.ControlledBy(LogLevel) .CreateLogger(); builder.AddSerilog(); }); } } ``` Move Seq 'Compact' flag, default
```c# namespace Cash_Flow_Projection { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; using Serilog.Core; public class Program { public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information); public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureLogging((context, builder) => { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName) .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName) .Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}") .WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), controlLevelSwitch: LogLevel) .MinimumLevel.ControlledBy(LogLevel) .CreateLogger(); builder.AddSerilog(); }); } } ```
454adced-b78d-480e-bcae-f996eb7c1685
{ "language": "C#" }
```c# using ARSoft.Tools.Net.Dns; using System; using System.Net; using System.Net.Sockets; namespace DNSRootServerResolver { public class Program { public static void Main(string[] args) { using (var server = new DnsServer(IPAddress.Any, 25, 25, DnsServerHandler)) { server.Start(); string command; while ((command = Console.ReadLine()) != "exit") { if (command == "clear") { DNS.GlobalCache.Clear(); } } } } public static DnsMessageBase DnsServerHandler(DnsMessageBase dnsMessageBase, IPAddress clientAddress, ProtocolType protocolType) { DnsMessage query = dnsMessageBase as DnsMessage; foreach (var question in query.Questions) { switch (question.RecordType) { case RecordType.A: query.AnswerRecords.AddRange(DNS.Resolve(question.Name)); break; case RecordType.Ptr: { if (question.Name == "1.0.0.127.in-addr.arpa") { query.AnswerRecords.Add(new PtrRecord("127.0.0.1", 172800 /*2 days*/, "localhost")); } }; break; } } return query; } } } ``` Add mx handling and not implemented if non supported type request
```c# using ARSoft.Tools.Net.Dns; using System; using System.Net; using System.Net.Sockets; namespace DNSRootServerResolver { public class Program { public static void Main(string[] args) { using (var server = new DnsServer(IPAddress.Any, 25, 25, DnsServerHandler)) { server.Start(); string command; while ((command = Console.ReadLine()) != "exit") { if (command == "clear") { DNS.GlobalCache.Clear(); } } } } public static DnsMessageBase DnsServerHandler(DnsMessageBase dnsMessageBase, IPAddress clientAddress, ProtocolType protocolType) { DnsMessage query = dnsMessageBase as DnsMessage; foreach (var question in query.Questions) { Console.WriteLine(question); switch (question.RecordType) { case RecordType.A: case RecordType.Mx: query.AnswerRecords.AddRange(DNS.Resolve(question.Name, question.RecordType, question.RecordClass)); break; case RecordType.Ptr: { if (question.Name == "1.0.0.127.in-addr.arpa") { query.AnswerRecords.Add(new PtrRecord("127.0.0.1", 172800 /*2 days*/, "localhost")); } }; break; default: { query.ReturnCode = ReturnCode.NotImplemented; Console.WriteLine("Unknown record type: " + question.RecordType + " (class: " + question.RecordClass + ", " + question.Name + ")"); } break; } } return query; } } } ```
22c543ba-c944-473d-8d81-bbc88a07052f
{ "language": "C#" }
```c# using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.UI; using System.Collections; using System.Collections.Generic; using UnityEngine; public class TouchHandler : MonoBehaviour, IMixedRealityTouchHandler { #region Event handlers public TouchEvent OnTouchStarted = new TouchEvent(); public TouchEvent OnTouchCompleted = new TouchEvent(); public TouchEvent OnTouchUpdated = new TouchEvent(); #endregion void IMixedRealityTouchHandler.OnTouchCompleted(HandTrackingInputEventData eventData) { OnTouchCompleted.Invoke(eventData); } void IMixedRealityTouchHandler.OnTouchStarted(HandTrackingInputEventData eventData) { OnTouchStarted.Invoke(eventData); } void IMixedRealityTouchHandler.OnTouchUpdated(HandTrackingInputEventData eventData) { OnTouchUpdated.Invoke(eventData); } } ``` Add missing namespace to resolve asset retargeting failures
```c# using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.UI; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { public class TouchHandler : MonoBehaviour, IMixedRealityTouchHandler { #region Event handlers public TouchEvent OnTouchStarted = new TouchEvent(); public TouchEvent OnTouchCompleted = new TouchEvent(); public TouchEvent OnTouchUpdated = new TouchEvent(); #endregion void IMixedRealityTouchHandler.OnTouchCompleted(HandTrackingInputEventData eventData) { OnTouchCompleted.Invoke(eventData); } void IMixedRealityTouchHandler.OnTouchStarted(HandTrackingInputEventData eventData) { OnTouchStarted.Invoke(eventData); } void IMixedRealityTouchHandler.OnTouchUpdated(HandTrackingInputEventData eventData) { OnTouchUpdated.Invoke(eventData); } } } ```
b5c03d74-4b00-4eb5-9213-c443a1f65f9e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Test.Converters { class ESDATDataConverterTest { } } ``` Implement ESDATModel test for OSM2.Actions
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Moq; using Hatfield.EnviroData.Core; using Hatfield.EnviroData.DataAcquisition.ESDAT; using Hatfield.EnviroData.DataAcquisition.ESDAT.Converters; namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Test.Converters { [TestFixture] public class ESDATConverterTest { // See https://github.com/HatfieldConsultants/Hatfield.EnviroData.Core/wiki/Loading-ESDAT-data-into-ODM2#actions for expected values [Test] public void ESDATConverterConvertToODMActionActionTest() { var mockDbContext = new Mock<IDbContext>().Object; var esdatConverter = new ESDATConverter(mockDbContext); ESDATModel esdatModel = new ESDATModel(); DateTime sampledDateTime = DateTime.Now; esdatModel.SampleFileData.SampledDateTime = sampledDateTime; var action = esdatConverter.ConvertToODMAction(esdatModel); Assert.AreEqual(action.ActionID, 0); Assert.AreEqual(action.ActionTypeCV, "specimenCollection"); Assert.AreEqual(action.BeginDateTime, sampledDateTime); Assert.AreEqual(action.EndDateTime, null); Assert.AreEqual(action.EndDateTimeUTCOffset, null); Assert.AreEqual(action.ActionDescription, null); Assert.AreEqual(action.ActionFileLink, null); } } } ```
3a2f19db-b730-4215-bd00-f1cd16011e7e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using Bonobo.Git.Server.Data; using Bonobo.Git.Server.Models; using Microsoft.Practices.Unity; namespace Bonobo.Git.Server.Security { public class ADRepositoryPermissionService : IRepositoryPermissionService { [Dependency] public IRepositoryRepository Repository { get; set; } [Dependency] public IRoleProvider RoleProvider { get; set; } [Dependency] public ITeamRepository TeamRepository { get; set; } public bool AllowsAnonymous(string repositoryName) { return Repository.GetRepository(repositoryName).AnonymousAccess; } public bool HasPermission(string username, string repositoryName) { bool result = true; RepositoryModel repositoryModel = Repository.GetRepository(repositoryName); result &= repositoryModel.Users.Contains(username, StringComparer.OrdinalIgnoreCase); result &= repositoryModel.Administrators.Contains(username, StringComparer.OrdinalIgnoreCase); result &= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator); result &= TeamRepository.GetTeams(username).Any(x => repositoryModel.Teams.Contains(x.Name, StringComparer.OrdinalIgnoreCase)); return result; } public bool IsRepositoryAdministrator(string username, string repositoryName) { bool result = true; result &= Repository.GetRepository(repositoryName).Administrators.Contains(username, StringComparer.OrdinalIgnoreCase); result &= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator); return result; } } }``` Fix repository permission checks. Yes, that was stupid.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using Bonobo.Git.Server.Data; using Bonobo.Git.Server.Models; using Microsoft.Practices.Unity; namespace Bonobo.Git.Server.Security { public class ADRepositoryPermissionService : IRepositoryPermissionService { [Dependency] public IRepositoryRepository Repository { get; set; } [Dependency] public IRoleProvider RoleProvider { get; set; } [Dependency] public ITeamRepository TeamRepository { get; set; } public bool AllowsAnonymous(string repositoryName) { return Repository.GetRepository(repositoryName).AnonymousAccess; } public bool HasPermission(string username, string repositoryName) { bool result = false; RepositoryModel repositoryModel = Repository.GetRepository(repositoryName); result |= repositoryModel.Users.Contains(username, StringComparer.OrdinalIgnoreCase); result |= repositoryModel.Administrators.Contains(username, StringComparer.OrdinalIgnoreCase); result |= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator); result |= TeamRepository.GetTeams(username).Any(x => repositoryModel.Teams.Contains(x.Name, StringComparer.OrdinalIgnoreCase)); return result; } public bool IsRepositoryAdministrator(string username, string repositoryName) { bool result = false; result |= Repository.GetRepository(repositoryName).Administrators.Contains(username, StringComparer.OrdinalIgnoreCase); result |= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator); return result; } } }```
6c3553c2-f354-42d8-99c6-10fdd96aed07
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExpressionToCodeLib; using Xunit; namespace ExpressionToCodeTest { public class AnonymousObjectFormattingTest { [Fact] public void AnonymousObjectsRenderAsCode() { Assert.Equal("new {\n A = 1,\n Foo = \"Bar\",\n}", ObjectToCode.ComplexObjectToPseudoCode(new { A = 1, Foo = "Bar", })); } [Fact] public void AnonymousObjectsInArray() { Assert.Equal("new[] {\n new {\n Val = 3,\n },\n new {\n Val = 42,\n },\n}", ObjectToCode.ComplexObjectToPseudoCode(new[] { new { Val = 3, }, new { Val = 42 } })); } [Fact] public void EnumerableInAnonymousObject() { Assert.Equal("new {\n Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...},\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Nums = Enumerable.Range(1, 13) })); } [Fact] public void EnumInAnonymousObject() { Assert.Equal("new {\n Enum = ConsoleKey.A,\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Enum = ConsoleKey.A })); } } }``` Fix test to use the appropriate config
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExpressionToCodeLib; using Xunit; namespace ExpressionToCodeTest { public class AnonymousObjectFormattingTest { [Fact] public void AnonymousObjectsRenderAsCode() { Assert.Equal("new {\n A = 1,\n Foo = \"Bar\",\n}", ObjectToCode.ComplexObjectToPseudoCode(new { A = 1, Foo = "Bar", })); } [Fact] public void AnonymousObjectsInArray() { Assert.Equal("new[] {\n new {\n Val = 3,\n },\n new {\n Val = 42,\n },\n}", ObjectToCode.ComplexObjectToPseudoCode(new[] { new { Val = 3, }, new { Val = 42 } })); } [Fact] public void EnumerableInAnonymousObject() { Assert.Equal("new {\n Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...},\n}", ExpressionToCodeConfiguration.DefaultAssertionConfiguration.ComplexObjectToPseudoCode(new { Nums = Enumerable.Range(1, 13) })); } [Fact] public void EnumInAnonymousObject() { Assert.Equal("new {\n Enum = ConsoleKey.A,\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Enum = ConsoleKey.A })); } } }```
5668ce4f-4258-4fda-9ff1-715e2842dd0f
{ "language": "C#" }
```c# using System; using System.ComponentModel; using System.Diagnostics; using TweetDuck.Configuration; using TweetLib.Core; using TweetLib.Utils.Static; namespace TweetDuck.Updates { sealed class UpdateInstaller { private string Path { get; } public UpdateInstaller(string path) { this.Path = path; } public bool Launch() { // ProgramPath has a trailing backslash string arguments = "/SP- /SILENT /FORCECLOSEAPPLICATIONS /UPDATEPATH=\"" + App.ProgramPath + "\" /RUNARGS=\"" + Arguments.GetCurrentForInstallerCmd() + "\"" + (App.IsPortable ? " /PORTABLE=1" : ""); bool runElevated = !App.IsPortable || !FileUtils.CheckFolderWritePermission(App.ProgramPath); try { using (Process.Start(new ProcessStartInfo { FileName = Path, Arguments = arguments, Verb = runElevated ? "runas" : string.Empty, ErrorDialog = true })) { return true; } } catch (Win32Exception e) when (e.NativeErrorCode == 0x000004C7) { // operation canceled by the user return false; } catch (Exception e) { App.ErrorHandler.HandleException("Update Installer Error", "Could not launch update installer.", true, e); return false; } } } } ``` Fix update installer not running as administrator due to breaking change in .NET
```c# using System; using System.ComponentModel; using System.Diagnostics; using TweetDuck.Configuration; using TweetLib.Core; using TweetLib.Utils.Static; namespace TweetDuck.Updates { sealed class UpdateInstaller { private string Path { get; } public UpdateInstaller(string path) { this.Path = path; } public bool Launch() { // ProgramPath has a trailing backslash string arguments = "/SP- /SILENT /FORCECLOSEAPPLICATIONS /UPDATEPATH=\"" + App.ProgramPath + "\" /RUNARGS=\"" + Arguments.GetCurrentForInstallerCmd() + "\"" + (App.IsPortable ? " /PORTABLE=1" : ""); bool runElevated = !App.IsPortable || !FileUtils.CheckFolderWritePermission(App.ProgramPath); try { using (Process.Start(new ProcessStartInfo { FileName = Path, Arguments = arguments, Verb = runElevated ? "runas" : string.Empty, UseShellExecute = true, ErrorDialog = true })) { return true; } } catch (Win32Exception e) when (e.NativeErrorCode == 0x000004C7) { // operation canceled by the user return false; } catch (Exception e) { App.ErrorHandler.HandleException("Update Installer Error", "Could not launch update installer.", true, e); return false; } } } } ```
31962831-3ab3-4440-9898-f9c0555b630a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hqub.Lastfm { public static class Configure { /// <summary> /// Set value delay between requests. /// </summary> public static int Delay { get; set; } } } ``` Set default delay value = 1000
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hqub.Lastfm { public static class Configure { static Configure() { Delay = 1000; } /// <summary> /// Set value delay between requests. /// </summary> public static int Delay { get; set; } } } ```
d7b18073-d639-4045-8789-fb198602b499
{ "language": "C#" }
```c# namespace Stripe { using System.Collections.Generic; using Newtonsoft.Json; public class SubscriptionItemPriceDataRecurringOptions : INestedOptions { /// <summary> /// Specifies a usage aggregation strategy for prices where <see cref="UsageType"/> is /// <c>metered</c>. Allowed values are <c>sum</c> for summing up all usage during a period, /// <c>last_during_period</c> for picking the last usage record reported within a period, /// <c>last_ever</c> for picking the last usage record ever (across period bounds) or /// <c>max</c> which picks the usage record with the maximum reported usage during a /// period. Defaults to <c>sum</c>. /// </summary> [JsonProperty("aggregate_usage")] public string AggregateUsage { get; set; } /// <summary> /// he frequency at which a subscription is billed. One of <c>day</c>, <c>week</c>, /// <c>month</c> or <c>year</c>. /// </summary> [JsonProperty("interval")] public string Interval { get; set; } /// <summary> /// The number of intervals (specified in the <see cref="Interval"/> property) between /// subscription billings. /// </summary> [JsonProperty("interval_count")] public long? IntervalCount { get; set; } /// <summary> /// Default number of trial days when subscribing a customer to this price using /// <c>trial_from_price=true</c>. /// </summary> [JsonProperty("trial_period_days")] public long? TrialPeriodDays { get; set; } /// <summary> /// Configures how the quantity per period should be determined, can be either /// <c>metered</c> or <c>licensed</c>. <c>licensed</c> will automatically bill the quantity /// set for a price when adding it to a subscription, <c>metered</c> will aggregate the /// total usage based on usage records. Defaults to <c>licensed</c>. /// </summary> [JsonProperty("usage_type")] public string UsageType { get; set; } } } ``` Fix parameters supported in `Recurring` for `PriceData` across the API
```c# namespace Stripe { using System.Collections.Generic; using Newtonsoft.Json; public class SubscriptionItemPriceDataRecurringOptions : INestedOptions { /// <summary> /// he frequency at which a subscription is billed. One of <c>day</c>, <c>week</c>, /// <c>month</c> or <c>year</c>. /// </summary> [JsonProperty("interval")] public string Interval { get; set; } /// <summary> /// The number of intervals (specified in the <see cref="Interval"/> property) between /// subscription billings. /// </summary> [JsonProperty("interval_count")] public long? IntervalCount { get; set; } } } ```
0bf8bd9f-9ab6-4ea7-98ce-5d4cdda34cdd
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api { interface IVsTypeScriptRemoteLanguageServiceWorkspace { } } ``` Add usage comment to interface
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api { /// <summary> /// Used to acquire the RemoteLanguageServiceWorkspace. Its members should be accessed by casting to <see cref="Workspace"/>. /// </summary> interface IVsTypeScriptRemoteLanguageServiceWorkspace { } } ```
1c21232e-5965-4ab3-befa-bfdf983dc4c8
{ "language": "C#" }
```c# using JetBrains.Application; using JetBrains.Application.Components; using JetBrains.Collections.Viewable; using JetBrains.ProjectModel; using JetBrains.ReSharper.Host.Features; using JetBrains.ReSharper.Host.Features.UnitTesting; using JetBrains.ReSharper.Plugins.Unity.ProjectModel; using JetBrains.ReSharper.UnitTestFramework; using JetBrains.Rider.Model; namespace JetBrains.ReSharper.Plugins.Unity.Rider { [ShellComponent] public class UnityRiderUnitTestCoverageAvailabilityChecker : IRiderUnitTestCoverageAvailabilityChecker, IHideImplementation<DefaultRiderUnitTestCoverageAvailabilityChecker> { // this method should be very fast as it gets called a lot public HostProviderAvailability GetAvailability(IUnitTestElement element) { var solution = element.Id.Project.GetSolution(); var tracker = solution.GetComponent<UnitySolutionTracker>(); if (tracker.IsUnityProject.HasValue() && !tracker.IsUnityProject.Value) return HostProviderAvailability.Available; var rdUnityModel = solution.GetProtocolSolution().GetRdUnityModel(); if (rdUnityModel.UnitTestPreference.Value != UnitTestLaunchPreference.PlayMode) return HostProviderAvailability.Available; return HostProviderAvailability.Nonexistent; } } }``` Disable tests coverage for unsupported Unity versions
```c# using System; using JetBrains.Application; using JetBrains.Application.Components; using JetBrains.Collections.Viewable; using JetBrains.ProjectModel; using JetBrains.ReSharper.Host.Features; using JetBrains.ReSharper.Host.Features.UnitTesting; using JetBrains.ReSharper.Plugins.Unity.ProjectModel; using JetBrains.ReSharper.UnitTestFramework; using JetBrains.Rider.Model; namespace JetBrains.ReSharper.Plugins.Unity.Rider { [ShellComponent] public class UnityRiderUnitTestCoverageAvailabilityChecker : IRiderUnitTestCoverageAvailabilityChecker, IHideImplementation<DefaultRiderUnitTestCoverageAvailabilityChecker> { private static readonly Version ourMinSupportedUnityVersion = new Version(2018, 3); // this method should be very fast as it gets called a lot public HostProviderAvailability GetAvailability(IUnitTestElement element) { var solution = element.Id.Project.GetSolution(); var tracker = solution.GetComponent<UnitySolutionTracker>(); if (tracker.IsUnityProject.HasValue() && !tracker.IsUnityProject.Value) return HostProviderAvailability.Available; var rdUnityModel = solution.GetProtocolSolution().GetRdUnityModel(); switch (rdUnityModel.UnitTestPreference.Value) { case UnitTestLaunchPreference.NUnit: return HostProviderAvailability.Available; case UnitTestLaunchPreference.PlayMode: return HostProviderAvailability.Nonexistent; case UnitTestLaunchPreference.EditMode: { var unityVersion = UnityVersion.Parse(rdUnityModel.ApplicationVersion.Maybe.ValueOrDefault ?? string.Empty); return unityVersion == null || unityVersion < ourMinSupportedUnityVersion ? HostProviderAvailability.Nonexistent : HostProviderAvailability.Available; } default: return HostProviderAvailability.Nonexistent; } } } }```
b1bea006-061b-4c28-8c24-0006acbcbec1
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Appleseed.UrlRewriting")] [assembly: AssemblyDescription("Appleseed Portal and Content Management System : URL Rewriting ")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("Appleseed Portal")] [assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01d79d33-2176-4a6d-a8aa-7cc02f308240")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers [assembly: AssemblyVersion("1.6.160.540")] [assembly: AssemblyFileVersion("1.6.160.540")]``` Update Version : 1.7.171.0 URL Changes + Fix User Manager Delete
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Appleseed.UrlRewriting")] [assembly: AssemblyDescription("Appleseed Portal and Content Management System : URL Rewriting ")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("Appleseed Portal")] [assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01d79d33-2176-4a6d-a8aa-7cc02f308240")] // Version information for an assembly consists of the following four values: // Major Version // Minor Version // Build Number // Revision // You can specify all the values or you can default the Revision and Build Numbers [assembly: AssemblyVersion("1.7.171.0")] [assembly: AssemblyFileVersion("1.7.171.0")]```
7256b2c5-f015-4f8c-8e99-f314d7bee4e2
{ "language": "C#" }
```c# namespace TraktApiSharp.Objects.Get.People { using Basic; using Newtonsoft.Json; public class TraktPersonImages { [JsonProperty(PropertyName = "headshot")] public TraktImageSet Headshot { get; set; } [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } } } ``` Add documentation for person images.
```c# namespace TraktApiSharp.Objects.Get.People { using Basic; using Newtonsoft.Json; /// <summary>A collection of images and image sets for a Trakt person.</summary> public class TraktPersonImages { /// <summary>Gets or sets the headshot image set.</summary> [JsonProperty(PropertyName = "headshot")] public TraktImageSet Headshot { get; set; } /// <summary>Gets or sets the fan art image set.</summary> [JsonProperty(PropertyName = "fanart")] public TraktImageSet FanArt { get; set; } } } ```
d763c3dc-94dc-451d-8062-71c7ec1c5f16
{ "language": "C#" }
```c# // Copyright (C) by Housemarque, Inc. namespace Hopac.Core { using System.Threading; /// <summary>Provides a low overhead, single shot waitable event.</summary> internal static class Condition { internal static bool warned; internal static void Pulse(object o, ref int v) { var w = v; if (w < 0 || 0 != Interlocked.Exchange(ref v, ~w)) { Monitor.Enter(o); Monitor.Pulse(o); Monitor.Exit(o); } } internal static void Wait(object o, ref int v) { if (0 <= v) { Monitor.Enter(o); var w = v; if (0 <= w) { if (0 == Interlocked.Exchange(ref v, ~w)) { if (!warned && Worker.IsWorkerThread) { warned = true; StaticData.writeLine( "WARNNG: You are making a blocking call from within a Hopac " + "worker thread, which means that your program may deadlock."); } Monitor.Wait(o); } } } } } } ``` Add stack to deadlock warning (and fix typo)
```c# // Copyright (C) by Housemarque, Inc. namespace Hopac.Core { using System.Threading; /// <summary>Provides a low overhead, single shot waitable event.</summary> internal static class Condition { internal static bool warned; internal static void Pulse(object o, ref int v) { var w = v; if (w < 0 || 0 != Interlocked.Exchange(ref v, ~w)) { Monitor.Enter(o); Monitor.Pulse(o); Monitor.Exit(o); } } internal static void Wait(object o, ref int v) { if (0 <= v) { Monitor.Enter(o); var w = v; if (0 <= w) { if (0 == Interlocked.Exchange(ref v, ~w)) { if (!warned && Worker.IsWorkerThread) { warned = true; StaticData.writeLine( "WARNING: You are making a blocking call from within a Hopac " + "worker thread, which means that your program may deadlock."); StaticData.writeLine("First occurrence (there may be others):"); StaticData.writeLine(System.Environment.StackTrace); } Monitor.Wait(o); } } } } } } ```
5a1efcf6-6fe4-4c35-a75b-9d357a36133c
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdownLite { public class MarkdownParagraphBlockToken : IMarkdownToken, IMarkdownRewritable<MarkdownParagraphBlockToken> { public MarkdownParagraphBlockToken(IMarkdownRule rule, IMarkdownContext context, InlineContent inlineTokens, string rawMarkdown) { Rule = rule; Context = context; InlineTokens = inlineTokens; RawMarkdown = rawMarkdown; } public IMarkdownRule Rule { get; } public IMarkdownContext Context { get; } public InlineContent InlineTokens { get; } public string RawMarkdown { get; set; } public static MarkdownParagraphBlockToken Create(IMarkdownRule rule, MarkdownParser engine, string content, string rawMarkdown) { return new MarkdownParagraphBlockToken(rule, engine.Context, engine.TokenizeInline(content), rawMarkdown); } public MarkdownParagraphBlockToken Rewrite(IMarkdownRewriteEngine rewriterEngine) { var c = InlineTokens.Rewrite(rewriterEngine); if (c == InlineTokens) { return this; } return new MarkdownParagraphBlockToken(Rule, Context, InlineTokens, RawMarkdown); } } } ``` Fix bug in Paragraph rewriter
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdownLite { public class MarkdownParagraphBlockToken : IMarkdownToken, IMarkdownRewritable<MarkdownParagraphBlockToken> { public MarkdownParagraphBlockToken(IMarkdownRule rule, IMarkdownContext context, InlineContent inlineTokens, string rawMarkdown) { Rule = rule; Context = context; InlineTokens = inlineTokens; RawMarkdown = rawMarkdown; } public IMarkdownRule Rule { get; } public IMarkdownContext Context { get; } public InlineContent InlineTokens { get; } public string RawMarkdown { get; set; } public static MarkdownParagraphBlockToken Create(IMarkdownRule rule, MarkdownParser engine, string content, string rawMarkdown) { return new MarkdownParagraphBlockToken(rule, engine.Context, engine.TokenizeInline(content), rawMarkdown); } public MarkdownParagraphBlockToken Rewrite(IMarkdownRewriteEngine rewriterEngine) { var c = InlineTokens.Rewrite(rewriterEngine); if (c == InlineTokens) { return this; } return new MarkdownParagraphBlockToken(Rule, Context, c, RawMarkdown); } } } ```
3107912d-ba03-4812-ac79-647afee51654
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Mitternacht; using System.Threading.Tasks; namespace MitternachtWeb { public class Program { public static MitternachtBot MitternachtBot; public static async Task Main(string[] args) { MitternachtBot = new MitternachtBot(0, 0); await MitternachtBot.RunAsync(args); await CreateHostBuilder(args).Build().RunAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, config) => { config.AddJsonFile("mitternachtweb.config"); }).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()); } } ``` Make content root path independent of working directory.
```c# using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Mitternacht; using System; using System.IO; using System.Threading.Tasks; namespace MitternachtWeb { public class Program { public static MitternachtBot MitternachtBot; public static async Task Main(string[] args) { MitternachtBot = new MitternachtBot(0, 0); await MitternachtBot.RunAsync(args); await CreateHostBuilder(args).Build().RunAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, config) => { config.SetBasePath(Environment.CurrentDirectory); config.AddJsonFile("mitternachtweb.config"); }).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); webBuilder.UseContentRoot(Path.GetDirectoryName(typeof(Program).Assembly.Location)); }); } } ```
38286b9d-dbc6-43f0-a1b5-08506901d7dd
{ "language": "C#" }
```c# using System; using System.Windows; using System.Windows.Media.Imaging; using Hardcodet.Wpf.TaskbarNotification; using SteamAccountSwitcher.Properties; namespace SteamAccountSwitcher { internal class TrayIconHelper { public static void ShowRunningInTrayBalloon() { ShowTrayBalloon( $"{Resources.AppName} is running in system tray.\nDouble click icon to show window.", BalloonIcon.Info); } public static void ShowTrayBalloon(string text, BalloonIcon icon) { if (!Settings.Default.ShowTrayNotifications) return; App.NotifyIcon.ShowBalloonTip(Resources.AppName, text, icon); } public static void RefreshTrayIcon() { if (Settings.Default.AlwaysOn) App.NotifyIcon.ContextMenu = MenuHelper.NotifyMenu(); } public static void CreateTrayIcon() { if (App.NotifyIcon != null) return; App.NotifyIcon = new TaskbarIcon {ToolTipText = Resources.AppName}; var logo = new BitmapImage(); logo.BeginInit(); logo.UriSource = new Uri($"pack://application:,,,/SteamAccountSwitcher;component/steam.ico"); logo.EndInit(); App.NotifyIcon.IconSource = logo; App.NotifyIcon.Visibility = Settings.Default.AlwaysOn ? Visibility.Visible : Visibility.Hidden; App.NotifyIcon.TrayMouseDoubleClick += (sender, args) => SwitchWindowHelper.ShowSwitcherWindow(); App.Accounts.CollectionChanged += (sender, args) => RefreshTrayIcon(); RefreshTrayIcon(); } } }``` Fix tray icon double click not activating switcher window
```c# using System; using System.Windows; using System.Windows.Media.Imaging; using Hardcodet.Wpf.TaskbarNotification; using SteamAccountSwitcher.Properties; namespace SteamAccountSwitcher { internal class TrayIconHelper { public static void ShowRunningInTrayBalloon() { ShowTrayBalloon( $"{Resources.AppName} is running in system tray.\nDouble click icon to show window.", BalloonIcon.Info); } public static void ShowTrayBalloon(string text, BalloonIcon icon) { if (!Settings.Default.ShowTrayNotifications) return; App.NotifyIcon.ShowBalloonTip(Resources.AppName, text, icon); } public static void RefreshTrayIcon() { if (Settings.Default.AlwaysOn) App.NotifyIcon.ContextMenu = MenuHelper.NotifyMenu(); } public static void CreateTrayIcon() { if (App.NotifyIcon != null) return; App.NotifyIcon = new TaskbarIcon {ToolTipText = Resources.AppName}; var logo = new BitmapImage(); logo.BeginInit(); logo.UriSource = new Uri($"pack://application:,,,/SteamAccountSwitcher;component/steam.ico"); logo.EndInit(); App.NotifyIcon.IconSource = logo; App.NotifyIcon.Visibility = Settings.Default.AlwaysOn ? Visibility.Visible : Visibility.Hidden; App.NotifyIcon.TrayMouseDoubleClick += (sender, args) => SwitchWindowHelper.ActivateSwitchWindow(); App.Accounts.CollectionChanged += (sender, args) => RefreshTrayIcon(); RefreshTrayIcon(); } } }```
ae512339-7f09-4a24-85e3-063a2591901b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; namespace ExcelMediaConsole { class Program { static void Main(string[] args) { var excelFilePath = "Book1.xlsx"; var outputDirPath = "Media"; Directory.CreateDirectory(outputDirPath); using (var archive = ZipFile.OpenRead(excelFilePath)) { var query = archive.Entries .Where(e => e.FullName.StartsWith("xl/media/", StringComparison.InvariantCultureIgnoreCase)); foreach (var entry in query) { var filePath = Path.Combine(outputDirPath, entry.Name); entry.ExtractToFile(filePath, true); } } } } } ``` Add method to extract and zip
```c# using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; namespace ExcelMediaConsole { class Program { static void Main(string[] args) { var excelFilePath = "Book1.xlsx"; var outputDirPath = "Media"; Directory.CreateDirectory(outputDirPath); using (var archive = ZipFile.OpenRead(excelFilePath)) { // In case of Excel, the path separator is "/" not "\". var query = archive.Entries .Where(e => e.FullName.StartsWith("xl/media/", StringComparison.InvariantCultureIgnoreCase)); foreach (var entry in query) { var filePath = Path.Combine(outputDirPath, entry.Name); entry.ExtractToFile(filePath, true); } } } static void ExtractAndZip() { var targetFilePath = "Book1.xlsx"; var extractDirPath = "Book1"; var zipFilePath = "Book1.zip"; ZipFile.ExtractToDirectory(targetFilePath, extractDirPath); ZipFile.CreateFromDirectory(extractDirPath, zipFilePath); } } } ```
18b7730b-64b7-4685-8bee-ef24a570d388
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Integration.Web")] [assembly: AssemblyDescription("Autofac ASP.NET Integration")] [assembly: InternalsVisibleTo("Autofac.Tests.Integration.Web, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")] [assembly: ComVisible(false)] ``` Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Integration.Web")] [assembly: InternalsVisibleTo("Autofac.Tests.Integration.Web, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")] [assembly: ComVisible(false)] ```
091e06d9-40be-46ed-8b1c-389f2a1d0f59
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Commons; [assembly: AssemblyTitle("TickTack")] [assembly: AssemblyDescription("Delayed reminder!")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rafael Teixeira")] [assembly: AssemblyProduct("TickTack")] [assembly: AssemblyCopyright("Copyright © 2008-2015 Rafael Teixeira")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("ac8af955-f068-4e26-af5e-f07c8f1c1e6e")] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-Alpha")] [assembly: License(LicenseType.MIT)] ``` Drop alpha status, it is a 1.0.0 release as is
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Commons; [assembly: AssemblyTitle("TickTack")] [assembly: AssemblyDescription("Delayed reminder!")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rafael Teixeira")] [assembly: AssemblyProduct("TickTack")] [assembly: AssemblyCopyright("Copyright © 2008-2015 Rafael Teixeira")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("ac8af955-f068-4e26-af5e-f07c8f1c1e6e")] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: License(LicenseType.MIT)] ```
74f9c8f3-de1b-4705-8587-d3641a377a07
{ "language": "C#" }
```c# namespace Pagination.ReleaseActions { class Tag : ReleaseAction { public override void Work() { var tag = Context.Version.StagedVersion; Process("git", "commit", "-a", "-m", $"\"(Auto-)Commit version '{tag}'.\""); Process("git", "tag", "-a", tag, "-m", $"\"(Auto-)Tag version '{tag}'.\""); Process("git", "push", "origin", tag); } } } ``` Add git commands to tool.
```c# namespace Pagination.ReleaseActions { class Tag : ReleaseAction { public override void Work() { var tag = Context.Version.StagedVersion; Process("git", "status"); Process("git", "commit", "-a", "-m", $"\"(Auto-)Commit version '{tag}'.\""); Process("git", "push"); Process("git", "tag", "-a", tag, "-m", $"\"(Auto-)Tag version '{tag}'.\""); Process("git", "push", "origin", tag); } } } ```
a4463922-4792-4fa1-b0ab-dc5abb249b11
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Bindables; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.Objects.Drawables; namespace osu.Game.Rulesets.Mania.Tests.Skinning { public class TestSceneHoldNote : ManiaHitObjectTestScene { [Test] public void TestHoldNote() { AddToggleStep("toggle hitting", v => { foreach (var holdNote in CreatedDrawables.SelectMany(d => d.ChildrenOfType<DrawableHoldNote>())) { ((Bindable<bool>)holdNote.IsHitting).Value = v; } }); } protected override DrawableManiaHitObject CreateHitObject() { var note = new HoldNote { Duration = 1000 }; note.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); return new DrawableHoldNote(note); } } } ``` Add test case for fading hold note
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Bindables; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.Objects.Drawables; namespace osu.Game.Rulesets.Mania.Tests.Skinning { public class TestSceneHoldNote : ManiaHitObjectTestScene { [Test] public void TestHoldNote() { AddToggleStep("toggle hitting", v => { foreach (var holdNote in CreatedDrawables.SelectMany(d => d.ChildrenOfType<DrawableHoldNote>())) { ((Bindable<bool>)holdNote.IsHitting).Value = v; } }); } [Test] public void TestFadeOnMiss() { AddStep("miss tick", () => { foreach (var holdNote in holdNotes) holdNote.ChildrenOfType<DrawableHoldNoteHead>().First().MissForcefully(); }); } private IEnumerable<DrawableHoldNote> holdNotes => CreatedDrawables.SelectMany(d => d.ChildrenOfType<DrawableHoldNote>()); protected override DrawableManiaHitObject CreateHitObject() { var note = new HoldNote { Duration = 1000 }; note.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); return new DrawableHoldNote(note); } } } ```
b9f8fc21-4c51-49b9-a8de-347c55e61615
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Judgements { public class HoldNoteTickJudgement : ManiaJudgement { public override bool AffectsCombo => false; protected override int NumericResultFor(HitResult result) => 20; protected override double HealthIncreaseFor(HitResult result) { switch (result) { default: return 0; case HitResult.Perfect: return 0.01; } } } } ``` Make hold note ticks affect combo score rather than bonus
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Judgements { public class HoldNoteTickJudgement : ManiaJudgement { protected override int NumericResultFor(HitResult result) => 20; protected override double HealthIncreaseFor(HitResult result) { switch (result) { default: return 0; case HitResult.Perfect: return 0.01; } } } } ```
81630ef2-3955-4227-b5c6-8113ece67f5a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snowflake.Events { public partial class SnowflakeEventSource { public static SnowflakeEventSource SnowflakeEventSource; SnowflakeEventSource() { } public static void InitEventSource() { if (SnowflakeEventSource.SnowflakeEventSource == null) { SnowflakeEventSource.SnowflakeEventSource = new SnowflakeEventSource(); } } } } ``` Fix a syntax error causing typo
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snowflake.Events { public partial class SnowflakeEventSource { public static SnowflakeEventSource EventSource; SnowflakeEventSource() { } public static void InitEventSource() { if (SnowflakeEventSource.EventSource == null) { SnowflakeEventSource.EventSource = new SnowflakeEventSource(); } } } } ```
6258bccc-5fbf-4721-8c6a-34746ab09ed1
{ "language": "C#" }
```c# using System; namespace Glimpse.Agent { public class RemoteStreamMessagePublisher : BaseMessagePublisher { public override void PublishMessage(IMessage message) { var newMessage = ConvertMessage(message); // TODO: Use SignalR to publish message } } }``` Switch stream publisher over to use new proxy
```c# using Glimpse.Agent.Connection.Stream.Connection; using System; namespace Glimpse.Agent { public class RemoteStreamMessagePublisher : BaseMessagePublisher { private readonly IStreamProxy _messagePublisherHub; public RemoteStreamMessagePublisher(IStreamProxy messagePublisherHub) { _messagePublisherHub = messagePublisherHub; } public override void PublishMessage(IMessage message) { var newMessage = ConvertMessage(message); _messagePublisherHub.UseSender(x => x.Invoke("HandleMessage", newMessage)); } } }```
837e6e50-c11c-4772-98f4-5318a3276f94
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Runtime.InteropServices.Tests { #pragma warning disable 0618 // DispatchWrapper is marked as Obsolete. public class DispatchWrapperTests { [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Throws PlatformNotSupportedException in UapAot")] public void Ctor_NullWindows_Success() { var wrapper = new DispatchWrapper(null); Assert.Null(wrapper.WrappedObject); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.UapAot, "Throws PlatformNotSupportedException in UapAot")] public void Ctor_NullUapAot_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(null)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void Ctor_NullUnix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(null)); } [Theory] [InlineData("")] [InlineData(0)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Marshal.GetIDispatchForObject is not supported in .NET Core.")] public void Ctor_NonNull_ThrowsPlatformNotSupportedException(object value) { Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(value)); } } #pragma warning restore 0618 } ``` Unify DispatchWrapper behavior for null
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Runtime.InteropServices.Tests { #pragma warning disable 0618 // DispatchWrapper is marked as Obsolete. public class DispatchWrapperTests { [Fact] public void Ctor_Null_Success() { var wrapper = new DispatchWrapper(null); Assert.Null(wrapper.WrappedObject); } [Theory] [InlineData("")] [InlineData(0)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Marshal.GetIDispatchForObject is not supported in .NET Core.")] public void Ctor_NonNull_ThrowsPlatformNotSupportedException(object value) { Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(value)); } } #pragma warning restore 0618 } ```
5537c93c-5c28-44f4-a030-654fa21b9b68
{ "language": "C#" }
```c# using System; using static System.Math; namespace MyDriving.Utils { public static class DistanceUtils { /// <summary> /// Calculates the distance in miles /// </summary> /// <returns>The distance.</returns> /// <param name="latitudeStart">Latitude start.</param> /// <param name="longitudeStart">Longitude start.</param> /// <param name="latitudeEnd">Latitude end.</param> /// <param name="longitudeEnd">Longitude end.</param> public static double CalculateDistance(double latitudeStart, double longitudeStart, double latitudeEnd, double longitudeEnd) { var rlat1 = PI * latitudeStart / 180.0; var rlat2 = PI * latitudeEnd / 180.0; var theta = longitudeStart - longitudeEnd; var rtheta = PI * theta / 180.0; var dist = Sin(rlat1) * Sin(rlat2) + Cos(rlat1) * Cos(rlat2) * Cos(rtheta); dist = Acos(dist); dist = dist * 180.0 / PI; return dist * 60.0 * 1.1515; } public static double MilesToKilometers(double miles) => miles * 1.609344; } } ``` Fix for NAN on Distance Calculations
```c# using System; using static System.Math; namespace MyDriving.Utils { public static class DistanceUtils { /// <summary> /// Calculates the distance in miles /// </summary> /// <returns>The distance.</returns> /// <param name="latitudeStart">Latitude start.</param> /// <param name="longitudeStart">Longitude start.</param> /// <param name="latitudeEnd">Latitude end.</param> /// <param name="longitudeEnd">Longitude end.</param> public static double CalculateDistance(double latitudeStart, double longitudeStart, double latitudeEnd, double longitudeEnd) { if (latitudeEnd == latitudeStart && longitudeEnd == longitudeStart) return 0; var rlat1 = PI * latitudeStart / 180.0; var rlat2 = PI * latitudeEnd / 180.0; var theta = longitudeStart - longitudeEnd; var rtheta = PI * theta / 180.0; var dist = Sin(rlat1) * Sin(rlat2) + Cos(rlat1) * Cos(rlat2) * Cos(rtheta); dist = Acos(dist); dist = dist * 180.0 / PI; var final = dist * 60.0 * 1.1515; if (double.IsNaN(final) || double.IsInfinity(final) || double.IsNegativeInfinity(final) || double.IsPositiveInfinity(final) || final < 0) return 0; return final; } public static double MilesToKilometers(double miles) => miles * 1.609344; } } ```
06735506-3e27-4b17-8bb4-2fe59291449e
{ "language": "C#" }
```c# using System.Windows.Forms; namespace Bloom.WebLibraryIntegration { public partial class OverwriteWarningDialog : Form { public OverwriteWarningDialog() { InitializeComponent(); } } } ``` Fix a dialog display glitch on Linux (20190725)
```c# using System.Windows.Forms; namespace Bloom.WebLibraryIntegration { public partial class OverwriteWarningDialog : Form { public OverwriteWarningDialog() { InitializeComponent(); } protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); // Fix a display glitch on Linux with the Mono SWF implementation. The button were half off // the bottom of the dialog on Linux, but fine on Windows. if (SIL.PlatformUtilities.Platform.IsLinux) { if (ClientSize.Height < _replaceExistingButton.Location.Y + _replaceExistingButton.Height) { var delta = ClientSize.Height - (_replaceExistingButton.Location.Y + _replaceExistingButton.Height) - 4; _replaceExistingButton.Location = new System.Drawing.Point(_replaceExistingButton.Location.X, _replaceExistingButton.Location.Y + delta); } if (ClientSize.Height < _cancelButton.Location.Y + _cancelButton.Height) { var delta = ClientSize.Height - (_cancelButton.Location.Y + _cancelButton.Height) - 4; _cancelButton.Location = new System.Drawing.Point(_cancelButton.Location.X, _cancelButton.Location.Y + delta); } } } } } ```
ad49c6cc-fc3e-4704-bd77-47664904eb34
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Web.Mvc; using AutoMapper; using StudentFollowingSystem.Data.Repositories; using StudentFollowingSystem.Filters; using StudentFollowingSystem.Models; using StudentFollowingSystem.ViewModels; using Validatr.Filters; namespace StudentFollowingSystem.Controllers { [AuthorizeCounseler] public class StudentsController : Controller { private readonly StudentRepository _studentRepository = new StudentRepository(); public ActionResult Dashboard() { var model = new StudentDashboardModel(); return View(model); } public ActionResult List() { var students = Mapper.Map<List<StudentModel>>(_studentRepository.GetAll()); return View(students); } public ActionResult Add() { return View(new StudentModel()); } [HttpPost] public ActionResult Add(StudentModel model) { if (ModelState.IsValid) { var student = Mapper.Map<Student>(model); _studentRepository.Add(student); return RedirectToAction("List"); } return View(model); } } } ``` Test password for new students.
```c# using System.Collections.Generic; using System.Web.Helpers; using System.Web.Mvc; using AutoMapper; using StudentFollowingSystem.Data.Repositories; using StudentFollowingSystem.Filters; using StudentFollowingSystem.Models; using StudentFollowingSystem.ViewModels; namespace StudentFollowingSystem.Controllers { [AuthorizeCounseler] public class StudentsController : Controller { private readonly StudentRepository _studentRepository = new StudentRepository(); public ActionResult Dashboard() { var model = new StudentDashboardModel(); return View(model); } public ActionResult List() { var students = Mapper.Map<List<StudentModel>>(_studentRepository.GetAll()); return View(students); } public ActionResult Add() { return View(new StudentModel()); } [HttpPost] public ActionResult Add(StudentModel model) { if (ModelState.IsValid) { var student = Mapper.Map<Student>(model); student.Password = Crypto.HashPassword("test"); _studentRepository.Add(student); return RedirectToAction("List"); } return View(model); } } } ```
c10d06a4-dd71-43f5-acc5-e8626a08b3eb
{ "language": "C#" }
```c# // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api; using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Cloud.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class MetricServiceClientSnippets { private readonly MonitoringFixture _fixture; public MetricServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } [Fact] public void ListMetricDescriptors() { string projectId = _fixture.ProjectId; // Sample: ListMetricDescriptors // Additional: ListMetricDescriptors(*,*,*,*) MetricServiceClient client = MetricServiceClient.Create(); string projectName = new ProjectName(projectId).ToString(); PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName); foreach (MetricDescriptor metric in metrics.Take(10)) { Console.WriteLine($"{metric.Name}: {metric.DisplayName}"); } // End sample } } } ``` Fix hand-written Monitoring snippet to use resource names
```c# // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api; using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Cloud.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class MetricServiceClientSnippets { private readonly MonitoringFixture _fixture; public MetricServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } [Fact] public void ListMetricDescriptors() { string projectId = _fixture.ProjectId; // Sample: ListMetricDescriptors // Additional: ListMetricDescriptors(*,*,*,*) MetricServiceClient client = MetricServiceClient.Create(); ProjectName projectName = new ProjectName(projectId); PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName); foreach (MetricDescriptor metric in metrics.Take(10)) { Console.WriteLine($"{metric.Name}: {metric.DisplayName}"); } // End sample } } } ```
3c025a78-9469-482e-bdf7-5497e9c04dc0
{ "language": "C#" }
```c# using System.Collections.Generic; namespace UniProgramGen.Data { public class Teacher { public Requirements requirements { get; internal set; } public string name { get; internal set; } public Teacher(Requirements requirements, string name) { this.requirements = requirements; this.name = name; } } } ``` Add get method for teacher name
```c# using System.Collections.Generic; namespace UniProgramGen.Data { public class Teacher { public Requirements requirements { get; internal set; } public string name { get; internal set; } public string Name { get { return name; } } public Teacher(Requirements requirements, string name) { this.requirements = requirements; this.name = name; } } } ```
3074c7df-a8d0-4b2a-8285-e136b6a686b9
{ "language": "C#" }
```c# // Note.cs // <copyright file="Note.cs"> This code is protected under the MIT License. </copyright> using System.Collections.Generic; namespace Todo_List { /// <summary> /// A data representation of a note. /// </summary> public class Note { /// <summary> /// Initializes a new instance of the <see cref="Note" /> class. /// </summary> public Note() { this.Title = string.Empty; this.Categories = new string[0]; } /// <summary> /// Initializes a new instance of the <see cref="Note" /> class. /// </summary> /// <param name="title"> The title of the note. </param> /// <param name="categories"> The categories the note is in. </param> public Note(string title, string[] categories) { this.Title = title; this.Categories = categories; } /// <summary> /// Gets or sets the title of the note. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets the categories the note is in. /// </summary> public string[] Categories { get; set; } } } ``` Make styling consistent between files
```c# // Note.cs // <copyright file="Note.cs"> This code is protected under the MIT License. </copyright> using System.Collections.Generic; namespace Todo_List { /// <summary> /// A data representation of a note. /// </summary> public class Note { /// <summary> /// Initializes a new instance of the <see cref="Note" /> class. /// </summary> public Note() { Title = string.Empty; Categories = new string[0]; } /// <summary> /// Initializes a new instance of the <see cref="Note" /> class. /// </summary> /// <param name="title"> The title of the note. </param> /// <param name="categories"> The categories the note is in. </param> public Note(string title, string[] categories) { Title = title; Categories = categories; } /// <summary> /// Gets or sets the title of the note. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets the categories the note is in. /// </summary> public string[] Categories { get; set; } } } ```
f3f6876b-9521-4b68-91ad-8fa00fffdd52
{ "language": "C#" }
```c# #if __MonoCS__ using System; using System.Diagnostics; using System.Runtime.InteropServices; using IBusDotNet; using NDesk.DBus; namespace Palaso.UI.WindowsForms.Keyboarding.Linux { /// <summary> /// a global cache used only to reduce traffic with ibus via dbus. /// </summary> internal static class GlobalCachedInputContext { /// <summary> /// Caches the current InputContext. /// </summary> public static InputContext InputContext { get; set; } /// <summary> /// Cache the keyboard of the InputContext. /// </summary> public static IBusKeyboardDescription Keyboard { get; set; } /// <summary> /// Clear the cached InputContext details. /// </summary> public static void Clear() { Keyboard = null; InputContext = null; } } } #endif``` Fix bug when deactivating ibus keyboards Setting the Keyboard to null in GlobalInputContext.Clear prevented the IbusKeyboardAdaptor.SetIMEKeyboard method from disabling the keyboard.
```c# #if __MonoCS__ using System; using System.Diagnostics; using System.Runtime.InteropServices; using IBusDotNet; using NDesk.DBus; namespace Palaso.UI.WindowsForms.Keyboarding.Linux { /// <summary> /// a global cache used only to reduce traffic with ibus via dbus. /// </summary> internal static class GlobalCachedInputContext { /// <summary> /// Caches the current InputContext. /// </summary> public static InputContext InputContext { get; set; } /// <summary> /// Cache the keyboard of the InputContext. /// </summary> public static IBusKeyboardDescription Keyboard { get; set; } /// <summary> /// Clear the cached InputContext details. /// </summary> public static void Clear() { InputContext = null; } } } #endif```
766124ba-d611-457f-af1d-146de9588d88
{ "language": "C#" }
```c# using System; using System.IO; using System.Runtime.Serialization; using ProtoBuf; using ProtoBuf.Meta; namespace Dx.Runtime { public class DefaultObjectWithTypeSerializer : IObjectWithTypeSerializer { private readonly ILocalNode m_LocalNode; public DefaultObjectWithTypeSerializer(ILocalNode localNode) { this.m_LocalNode = localNode; } public ObjectWithType Serialize(object obj) { if (obj == null) { return new ObjectWithType { AssemblyQualifiedTypeName = null, SerializedObject = null }; } byte[] serializedObject; using (var memory = new MemoryStream()) { Serializer.Serialize(memory, obj); var length = (int)memory.Position; memory.Seek(0, SeekOrigin.Begin); serializedObject = new byte[length]; memory.Read(serializedObject, 0, length); } return new ObjectWithType { AssemblyQualifiedTypeName = obj.GetType().AssemblyQualifiedName, SerializedObject = serializedObject }; } public object Deserialize(ObjectWithType owt) { if (owt.AssemblyQualifiedTypeName == null) { return null; } var type = Type.GetType(owt.AssemblyQualifiedTypeName); if (type == null) { throw new TypeLoadException(); } using (var memory = new MemoryStream(owt.SerializedObject)) { object instance; if (type == typeof(string)) { instance = string.Empty; } else { instance = FormatterServices.GetUninitializedObject(type); } var value = RuntimeTypeModel.Default.Deserialize(memory, instance, type); GraphWalker.Apply(value, this.m_LocalNode); return value; } } } } ``` Remove old serialization check that is no longer required
```c# using System; using System.IO; using System.Runtime.Serialization; using ProtoBuf; using ProtoBuf.Meta; namespace Dx.Runtime { public class DefaultObjectWithTypeSerializer : IObjectWithTypeSerializer { private readonly ILocalNode m_LocalNode; public DefaultObjectWithTypeSerializer(ILocalNode localNode) { this.m_LocalNode = localNode; } public ObjectWithType Serialize(object obj) { if (obj == null) { return new ObjectWithType { AssemblyQualifiedTypeName = null, SerializedObject = null }; } byte[] serializedObject; using (var memory = new MemoryStream()) { Serializer.Serialize(memory, obj); var length = (int)memory.Position; memory.Seek(0, SeekOrigin.Begin); serializedObject = new byte[length]; memory.Read(serializedObject, 0, length); } return new ObjectWithType { AssemblyQualifiedTypeName = obj.GetType().AssemblyQualifiedName, SerializedObject = serializedObject }; } public object Deserialize(ObjectWithType owt) { if (owt.AssemblyQualifiedTypeName == null) { return null; } var type = Type.GetType(owt.AssemblyQualifiedTypeName); if (type == null) { throw new TypeLoadException(); } using (var memory = new MemoryStream(owt.SerializedObject)) { var value = RuntimeTypeModel.Default.Deserialize(memory, null, type); GraphWalker.Apply(value, this.m_LocalNode); return value; } } } } ```
360829df-ef4d-46e2-9178-c22d1d7671fb
{ "language": "C#" }
```c# namespace TheCollection.Domain.Contracts.Repository { using System.Collections.Generic; using System.Threading.Tasks; public interface ILinqSearchRepository<T> where T : class { Task<IEnumerable<T>> SearchItemsAsync(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate = null, int pageSize = 0, int page = 0); } } ``` Clean code with using instead of fixed namespaces
```c# namespace TheCollection.Domain.Contracts.Repository { using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; public interface ILinqSearchRepository<T> where T : class { Task<IEnumerable<T>> SearchItemsAsync(Expression<Func<T, bool>> predicate = null, int pageSize = 0, int page = 0); } } ```
80e5f971-b868-449a-a21d-d2930e6e2bcc
{ "language": "C#" }
```c# using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace AllReady.Models { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { [Display(Name = "Associated skills")] public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>(); public string Name { get; set; } [Display(Name = "Time Zone")] [Required] public string TimeZoneId { get; set; } public string PendingNewEmail { get; set; } public IEnumerable<ValidationResult> ValidateProfileCompleteness() { List<ValidationResult> validationResults = new List<ValidationResult>(); if (!EmailConfirmed) { validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) })); } if (string.IsNullOrWhiteSpace(Name)) { validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) })); } if (string.IsNullOrWhiteSpace(PhoneNumber)) { validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) })); } if (!string.IsNullOrWhiteSpace(PhoneNumber) && !PhoneNumberConfirmed) { validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) })); } return validationResults; } public bool IsProfileComplete() { return !ValidateProfileCompleteness().Any(); } } }``` Simplify logic in user profile validation
```c# using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace AllReady.Models { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { [Display(Name = "Associated skills")] public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>(); public string Name { get; set; } [Display(Name = "Time Zone")] [Required] public string TimeZoneId { get; set; } public string PendingNewEmail { get; set; } public IEnumerable<ValidationResult> ValidateProfileCompleteness() { List<ValidationResult> validationResults = new List<ValidationResult>(); if (!EmailConfirmed) { validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) })); } if (string.IsNullOrWhiteSpace(Name)) { validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) })); } if (string.IsNullOrWhiteSpace(PhoneNumber)) { validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) })); } else if (!PhoneNumberConfirmed) { validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) })); } return validationResults; } public bool IsProfileComplete() { return !ValidateProfileCompleteness().Any(); } } }```