doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
a5b8bbd9-ad10-4e8a-8707-6240b81c0a38
{ "language": "C#" }
```c# using System; using Xamarin.Forms; using AI.XamarinSDK.Abstractions; namespace XamarinTest { public class App : Application { public App () { var mainNav = new NavigationPage (new XamarinTestMasterView ()); MainPage = mainNav; } protected override void OnStart () { ApplicationInsights.Setup (""); //ApplicationInsights.Setup ("ijhch"); ApplicationInsights.Start (); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } } ``` Add ikey placeholder to setup() call
```c# using System; using Xamarin.Forms; using AI.XamarinSDK.Abstractions; namespace XamarinTest { public class App : Application { public App () { var mainNav = new NavigationPage (new XamarinTestMasterView ()); MainPage = mainNav; } protected override void OnStart () { ApplicationInsights.Setup ("<YOUR-INSTRUMENTATION-KEY>"); ApplicationInsights.Start (); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } } ```
30713712-1abb-43ad-a971-e6d8c1d25768
{ "language": "C#" }
```c# using System.Linq; using BitChangeSetManager.DataAccess; using BitChangeSetManager.Dto; using BitChangeSetManager.Model; using Foundation.Api.ApiControllers; using AutoMapper; using AutoMapper.QueryableExtensions; namespace BitChangeSetManager.Api { public class ChangeSetsController : DefaultDtoSetController<ChangeSet, ChangeSetDto> { private readonly IBitChangeSetManagerRepository<ChangeSet> _changeSetsRepository; public ChangeSetsController(IBitChangeSetManagerRepository<ChangeSet> changeSetsRepository) : base(changeSetsRepository) { _changeSetsRepository = changeSetsRepository; } public IMapper Mapper { get; set; } public IBitChangeSetManagerRepository<Customer> CustomersRepository { get; set; } public override IQueryable<ChangeSetDto> GetAll() { IQueryable<Customer> customersQuery = CustomersRepository.GetAll(); return _changeSetsRepository .GetAll() .ProjectTo<ChangeSetDto>(configuration: Mapper.ConfigurationProvider, parameters: new { customersQuery = customersQuery }); } } }``` Use IDtoModelMapper instead of IMapper in change sets controller
```c# using System.Linq; using BitChangeSetManager.DataAccess; using BitChangeSetManager.Dto; using BitChangeSetManager.Model; using Foundation.Api.ApiControllers; namespace BitChangeSetManager.Api { public class ChangeSetsController : DefaultDtoSetController<ChangeSet, ChangeSetDto> { private readonly IBitChangeSetManagerRepository<ChangeSet> _changeSetsRepository; public ChangeSetsController(IBitChangeSetManagerRepository<ChangeSet> changeSetsRepository) : base(changeSetsRepository) { _changeSetsRepository = changeSetsRepository; } public IBitChangeSetManagerRepository<Customer> CustomersRepository { get; set; } public override IQueryable<ChangeSetDto> GetAll() { IQueryable<Customer> customersQuery = CustomersRepository.GetAll(); return DtoModelMapper.FromModelQueryToDtoQuery(_changeSetsRepository.GetAll(), parameters: new { customersQuery = customersQuery }); } } }```
53063b93-785e-4b72-948d-db061369141a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Net.Http; using System.Text; namespace Skarp.HubSpotClient { [Serializable] public class HubSpotException : Exception { private HttpResponseMessage response; public string RawJsonResponse { get; set; } public HubSpotException() { } public HubSpotException(string message) : base(message) { } public HubSpotException(string message, string jsonResponse) : base(message) { RawJsonResponse = jsonResponse; } public HubSpotException(string message, Exception innerException) : base(message, innerException) { } public HubSpotException(string message, string jsonResponse, HttpResponseMessage response) : this(message, jsonResponse) { this.response = response; } public override String Message { get { return base.Message + $", JSONResponse={RawJsonResponse??"Empty"}"; } } } } ``` Change properties to getters only
```c# using System; using System.Collections.Generic; using System.Net.Http; using System.Text; namespace Skarp.HubSpotClient { [Serializable] public class HubSpotException : Exception { public HttpResponseMessage Response { get; } public string RawJsonResponse { get; } public HubSpotException() { } public HubSpotException(string message) : base(message) { } public HubSpotException(string message, string jsonResponse) : base(message) { RawJsonResponse = jsonResponse; } public HubSpotException(string message, Exception innerException) : base(message, innerException) { } public HubSpotException(string message, string jsonResponse, HttpResponseMessage response) : this(message, jsonResponse) { this.Response = response; } public override String Message { get { return base.Message + $", JSONResponse={RawJsonResponse??"Empty"}"; } } } } ```
70d3dad9-d1e0-484e-b60c-82ff1d60c0d4
{ "language": "C#" }
```c# using System; namespace BmpListener.Bgp { internal class PathAttributeLargeCommunities : PathAttribute { public PathAttributeLargeCommunities(ArraySegment<byte> data) : base(ref data) { } } }``` Add large BGP communities support
```c# using System; namespace BmpListener.Bgp { internal class PathAttributeLargeCommunities : PathAttribute { private int asn; private int data1; private int data2; public PathAttributeLargeCommunities(ArraySegment<byte> data) : base(ref data) { DecodeFromByes(data); } public void DecodeFromByes(ArraySegment<byte> data) { asn = data.ToInt32(0); data1 = data.ToInt32(4); data2 = data.ToInt32(8); } public override string ToString() { return ($"{asn}:{data1}:{data2}"); } } }```
5f895932-69ba-4eb6-99ec-ac749887ff70
{ "language": "C#" }
```c# using CSharpTo2600.Framework; using static CSharpTo2600.Framework.TIARegisters; namespace CSharpTo2600.FunctionalitySamples { [Atari2600Game] static class SingleChangeBkColor { [SpecialMethod(MethodType.Initialize)] [System.Obsolete(CSharpTo2600.Framework.Assembly.Symbols.AUDC0, true)] static void Initialize() { BackgroundColor = 0x5E; } } } ``` Remove pointless line from functionality test
```c# using CSharpTo2600.Framework; using static CSharpTo2600.Framework.TIARegisters; namespace CSharpTo2600.FunctionalitySamples { [Atari2600Game] static class SingleChangeBkColor { [SpecialMethod(MethodType.Initialize)] static void Initialize() { BackgroundColor = 0x5E; } } } ```
0dd64f54-fc7b-455a-ae08-bc1f97145f4b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using BlogTemplate._1.Models; namespace BlogTemplate._1.Services { public class SlugGenerator { private BlogDataStore _dataStore; private static Regex AllowList = new Regex("([^A-Za-z0-9-])", RegexOptions.None, TimeSpan.FromSeconds(1)); public SlugGenerator(BlogDataStore dataStore) { _dataStore = dataStore; } public string CreateSlug(string title) { string tempTitle = title; tempTitle = tempTitle.Replace(" ", "-"); string slug = AllowList.Replace(tempTitle, ""); return slug; } } } ``` Revert "Created the Regex outside of the method, with a MatchTimeout property."
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using BlogTemplate._1.Models; namespace BlogTemplate._1.Services { public class SlugGenerator { private BlogDataStore _dataStore; public SlugGenerator(BlogDataStore dataStore) { _dataStore = dataStore; } public string CreateSlug(string title) { string tempTitle = title; tempTitle = tempTitle.Replace(" ", "-"); Regex allowList = new Regex("([^A-Za-z0-9-])"); string slug = allowList.Replace(tempTitle, ""); return slug; } } } ```
bfe7e0c4-623e-4761-afd8-0f3393bf9a61
{ "language": "C#" }
```c# using System.Windows.Forms; using CefSharp; using TweetDuck.Utils; namespace TweetDuck.Browser.Handling { class KeyboardHandlerBase : IKeyboardHandler { protected virtual bool HandleRawKey(IWebBrowser browserControl, Keys key, CefEventFlags modifiers) { if (modifiers == (CefEventFlags.ControlDown | CefEventFlags.ShiftDown) && key == Keys.I) { browserControl.OpenDevToolsCustom(); return true; } return false; } bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut) { if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("devtools://")) { return HandleRawKey(browserControl, (Keys) windowsKeyCode, modifiers); } return false; } bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey) { return false; } } } ``` Fix not disposing frame object when handling key events
```c# using System.Windows.Forms; using CefSharp; using TweetDuck.Utils; namespace TweetDuck.Browser.Handling { class KeyboardHandlerBase : IKeyboardHandler { protected virtual bool HandleRawKey(IWebBrowser browserControl, Keys key, CefEventFlags modifiers) { if (modifiers == (CefEventFlags.ControlDown | CefEventFlags.ShiftDown) && key == Keys.I) { browserControl.OpenDevToolsCustom(); return true; } return false; } bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut) { if (type == KeyType.RawKeyDown) { using var frame = browser.FocusedFrame; if (!frame.Url.StartsWith("devtools://")) { return HandleRawKey(browserControl, (Keys) windowsKeyCode, modifiers); } } return false; } bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey) { return false; } } } ```
dacf1b29-228f-4096-9912-f2649f9f042c
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Data.Entity; using System.Linq; using Moq; namespace Mox { public static class DbSetMockingExtensions { public static DbSet<T> MockWithList<T>(this DbSet<T> dbSet, IList<T> data) where T : class { var queryable = data.AsQueryable(); Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider); Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression); Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType); Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator()); return dbSet; } } } ``` Update GetEnumerator binding for more one run support.
```c# using System.Collections.Generic; using System.Data.Entity; using System.Linq; using Moq; namespace Mox { public static class DbSetMockingExtensions { public static DbSet<T> MockWithList<T>(this DbSet<T> dbSet, IList<T> data) where T : class { var queryable = data.AsQueryable(); Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider); Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression); Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType); Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator()); return dbSet; } } } ```
e7dc6311-5067-4cef-b6e3-2855ae72e1de
{ "language": "C#" }
```c# using Content.Server.GameObjects.Components.GUI; using Content.Shared.GameObjects.Components; using Content.Shared.Interfaces.GameObjects.Components; using Robust.Shared.GameObjects; using Robust.Shared.Serialization; namespace Content.Server.GameObjects.Components { [RegisterComponent] public class PlaceableSurfaceComponent : SharedPlaceableSurfaceComponent, IInteractUsing { private bool _isPlaceable; public bool IsPlaceable { get => _isPlaceable; set => _isPlaceable = value; } public override void ExposeData(ObjectSerializer serializer) { base.ExposeData(serializer); serializer.DataField(ref _isPlaceable, "IsPlaceable", true); } public bool InteractUsing(InteractUsingEventArgs eventArgs) { if (!IsPlaceable) return false; if(!eventArgs.User.TryGetComponent<HandsComponent>(out var handComponent)) { return false; } handComponent.Drop(eventArgs.Using); eventArgs.Using.Transform.WorldPosition = eventArgs.ClickLocation.Position; return true; } } } ``` Set interaction priority of PlacableSurfaceComponent to 1
```c# using Content.Server.GameObjects.Components.GUI; using Content.Shared.GameObjects.Components; using Content.Shared.Interfaces.GameObjects.Components; using Robust.Shared.GameObjects; using Robust.Shared.Serialization; namespace Content.Server.GameObjects.Components { [RegisterComponent] public class PlaceableSurfaceComponent : SharedPlaceableSurfaceComponent, IInteractUsing { private bool _isPlaceable; public bool IsPlaceable { get => _isPlaceable; set => _isPlaceable = value; } int IInteractUsing.Priority { get => 1; } public override void ExposeData(ObjectSerializer serializer) { base.ExposeData(serializer); serializer.DataField(ref _isPlaceable, "IsPlaceable", true); } public bool InteractUsing(InteractUsingEventArgs eventArgs) { if (!IsPlaceable) return false; if(!eventArgs.User.TryGetComponent<HandsComponent>(out var handComponent)) { return false; } handComponent.Drop(eventArgs.Using); eventArgs.Using.Transform.WorldPosition = eventArgs.ClickLocation.Position; return true; } } } ```
b1025e0b-b30b-4d4e-983e-7055aab45731
{ "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.Game.Database; using osu.Game.Users; using osu.Game.Utils; using Realms; namespace osu.Game.Models { public class RealmUser : EmbeddedObject, IUser, IEquatable<RealmUser>, IDeepCloneable<RealmUser> { public int OnlineID { get; set; } = 1; public string Username { get; set; } = string.Empty; [Ignored] public CountryCode CountryCode { get => Enum.TryParse(CountryString, out CountryCode country) ? country : default; set => CountryString = value.ToString(); } [MapTo(nameof(CountryCode))] public string CountryString { get; set; } = default(CountryCode).ToString(); public bool IsBot => false; public bool Equals(RealmUser other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return OnlineID == other.OnlineID && Username == other.Username; } public RealmUser DeepClone() => (RealmUser)this.Detach().MemberwiseClone(); } } ``` Use `Unknown` instead of `default`
```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.Game.Database; using osu.Game.Users; using osu.Game.Utils; using Realms; namespace osu.Game.Models { public class RealmUser : EmbeddedObject, IUser, IEquatable<RealmUser>, IDeepCloneable<RealmUser> { public int OnlineID { get; set; } = 1; public string Username { get; set; } = string.Empty; [Ignored] public CountryCode CountryCode { get => Enum.TryParse(CountryString, out CountryCode country) ? country : CountryCode.Unknown; set => CountryString = value.ToString(); } [MapTo(nameof(CountryCode))] public string CountryString { get; set; } = default(CountryCode).ToString(); public bool IsBot => false; public bool Equals(RealmUser other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return OnlineID == other.OnlineID && Username == other.Username; } public RealmUser DeepClone() => (RealmUser)this.Detach().MemberwiseClone(); } } ```
acd98b38-5b0a-44bf-95a5-ed643e00713e
{ "language": "C#" }
```c# using System; #if __UNIFIED__ using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; #endif namespace Plugin.Messaging { internal class PhoneCallTask : IPhoneCallTask { public PhoneCallTask() { } #region IPhoneCallTask Members public bool CanMakePhoneCall { get { return true; } } public void MakePhoneCall(string number, string name = null) { if (string.IsNullOrWhiteSpace(number)) throw new ArgumentNullException("number"); if (CanMakePhoneCall) { var nsurl = new NSUrl("tel://" + number); UIApplication.SharedApplication.OpenUrl(nsurl); } } #endregion } }``` Allow formatted telephone numbers on iOS (e.g. 1800 111 222 333 instead of 1800111222333)
```c# using System; #if __UNIFIED__ using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; #endif namespace Plugin.Messaging { internal class PhoneCallTask : IPhoneCallTask { public PhoneCallTask() { } #region IPhoneCallTask Members public bool CanMakePhoneCall { get { return true; } } public void MakePhoneCall(string number, string name = null) { if (string.IsNullOrWhiteSpace(number)) throw new ArgumentNullException("number"); if (CanMakePhoneCall) { var nsurl = CreateNSUrl(number); UIApplication.SharedApplication.OpenUrl(nsurl); } } private NSUrl CreateNSUrl(string number) { return new NSUrl(new Uri($"tel:{number}").AbsoluteUri); } #endregion } }```
a40a88f3-7728-419b-aa56-fdfd3142b7ee
{ "language": "C#" }
```c# using System.Runtime.Serialization; namespace Orationi.CommunicationCore.Model { /// <summary> /// Provide information about slave configuration. /// </summary> [DataContract] public class SlaveConfiguration { /// <summary> /// Versions of slave-assigned modules. /// </summary> [DataMember] public ModuleVersionItem[] Modules { get; set; } } } ``` Add id of slave to slave configuration.
```c# using System; using System.Runtime.Serialization; namespace Orationi.CommunicationCore.Model { /// <summary> /// Provide information about slave configuration. /// </summary> [DataContract] public class SlaveConfiguration { /// <summary> /// Global slave Id. /// </summary> [DataMember] public Guid Id { get; set; } /// <summary> /// Versions of slave-assigned modules. /// </summary> [DataMember] public ModuleVersionItem[] Modules { get; set; } } } ```
3f52cda8-7dba-4328-8c76-f8cc55da729b
{ "language": "C#" }
```c# using AutoMapper.Configuration; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace AutoMapper.Internal { public class FeatureCollectionBase<TValue> : IEnumerable<KeyValuePair<Type, TValue>> { private IDictionary<Type, TValue> _features = new Dictionary<Type, TValue>(); public TValue this[Type key] { get => _features.GetOrDefault(key); set { if (value == null) { _features.Remove(key); } else { _features[key] = value; } } } /// <summary> /// Gets the feature of type <typeparamref name="TFeature"/>. /// </summary> /// <typeparam name="TFeature">The type of the feature.</typeparam> /// <returns>The feature or null if feature not exists.</returns> public TFeature Get<TFeature>() where TFeature : TValue => (TFeature)this[typeof(TFeature)]; /// <summary> /// Add the feature for type <typeparamref name="TFeature"/>. Existing feature of the same type will be replaces. /// </summary> /// <typeparam name="TFeature">The type of the feature.</typeparam> /// <param name="feature">The feature.</param> public void Add<TFeature>(TFeature feature) where TFeature : TValue => this[typeof(TFeature)] = feature; public IEnumerator<KeyValuePair<Type, TValue>> GetEnumerator() => _features.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); protected void MakeReadOnly() => _features = new ReadOnlyDictionary<Type, TValue>(_features); } } ``` Change to AddOrUpdate for the feature to make it visible what the method is doing
```c# using AutoMapper.Configuration; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace AutoMapper.Internal { public class FeatureCollectionBase<TValue> : IEnumerable<KeyValuePair<Type, TValue>> { private IDictionary<Type, TValue> _features = new Dictionary<Type, TValue>(); public TValue this[Type key] { get => _features.GetOrDefault(key); set { if (value == null) { _features.Remove(key); } else { _features[key] = value; } } } /// <summary> /// Gets the feature of type <typeparamref name="TFeature"/>. /// </summary> /// <typeparam name="TFeature">The type of the feature.</typeparam> /// <returns>The feature or null if feature not exists.</returns> public TFeature Get<TFeature>() where TFeature : TValue => (TFeature)this[typeof(TFeature)]; /// <summary> /// Add or update the feature for type <typeparamref name="TFeature"/>. Existing feature of the same type will be replaces. /// </summary> /// <typeparam name="TFeature">The type of the feature.</typeparam> /// <param name="feature">The feature.</param> public void AddOrUpdate<TFeature>(TFeature feature) where TFeature : TValue => this[typeof(TFeature)] = feature; public IEnumerator<KeyValuePair<Type, TValue>> GetEnumerator() => _features.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); protected void MakeReadOnly() => _features = new ReadOnlyDictionary<Type, TValue>(_features); } } ```
1184bad8-767f-4590-8417-44e64cd38d96
{ "language": "C#" }
```c# using System; using System.Linq; using System.Security.Cryptography; using System.Text; namespace JabbR.Infrastructure { public static class StringExtensions { public static string ToMD5(this string value) { if (String.IsNullOrEmpty(value)) { return null; } return String.Join("", MD5.Create() .ComputeHash(Encoding.Default.GetBytes(value)) .Select(b => b.ToString("x2"))); } public static string ToSha256(this string value, string salt) { string saltedValue = ((salt ?? "") + value); return String.Join("", SHA256.Create() .ComputeHash(Encoding.Default.GetBytes(saltedValue)) .Select(b => b.ToString("x2"))); } } }``` Add ToSlug and ToFileNameSlug string extensions
```c# using System; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace JabbR.Infrastructure { public static class StringExtensions { public static string ToMD5(this string value) { if (String.IsNullOrEmpty(value)) { return null; } return String.Join("", MD5.Create() .ComputeHash(Encoding.Default.GetBytes(value)) .Select(b => b.ToString("x2"))); } public static string ToSha256(this string value, string salt) { string saltedValue = ((salt ?? "") + value); return String.Join("", SHA256.Create() .ComputeHash(Encoding.Default.GetBytes(saltedValue)) .Select(b => b.ToString("x2"))); } public static string ToSlug(this string value) { string result = value; // Remove non-ASCII characters result = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(result)); result = result.Trim(); // Remove Invalid Characters result = Regex.Replace(result, @"[^A-z0-9\s-]", string.Empty); // Reduce spaces and convert to underscore result = Regex.Replace(result, @"\s+", "_"); return result; } public static string ToFileNameSlug(this string value) { string result = value; // Trim Slashes result = result.TrimEnd('/', '\\', '.'); // Remove Path (included by IE in Intranet Mode) result = result.Contains(@"/") ? result.Substring(result.LastIndexOf(@"/") + 1) : result; result = result.Contains(@"\") ? result.Substring(result.LastIndexOf(@"\") + 1) : result; if (result.Contains('.')) { // ToSlug Filename Component string fileNameSlug = result.Substring(0, result.LastIndexOf('.')).ToSlug(); // ToSlug Extension Component string fileExtensionSlug = result.Substring(result.LastIndexOf('.') + 1).ToSlug(); // Combine Filename Slug result = string.Concat(fileNameSlug, ".", fileExtensionSlug); } else { // No Extension result = result.ToSlug(); } return result; } } }```
ea9b18fd-96a7-440a-a7e9-765281d358d0
{ "language": "C#" }
```c# using System.Web.Mvc; using NUnit.Framework.Constraints; namespace MvcRouteTester.Test.Areas.SomeArea { public class SomeAreaAreaRegistration : AreaRegistration { public override string AreaName { get { return "SomeArea"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "SomeArea_TestController", "SomeArea/{action}/{id}", defaults: new { action = "Index", controller = "Test", id = UrlParameter.Optional }, constraints: new { action = "Index|About" } ); context.MapRoute( "SomeArea_default", "SomeArea/{controller}/{action}/{id}", new { action = "Index", controller = "Test", id = UrlParameter.Optional } ); } } } ``` Remove NUnit.Framework.Constraint (unused - accident)
```c# using System.Web.Mvc; namespace MvcRouteTester.Test.Areas.SomeArea { public class SomeAreaAreaRegistration : AreaRegistration { public override string AreaName { get { return "SomeArea"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "SomeArea_TestController", "SomeArea/{action}/{id}", defaults: new { action = "Index", controller = "Test", id = UrlParameter.Optional }, constraints: new { action = "Index|About" } ); context.MapRoute( "SomeArea_default", "SomeArea/{controller}/{action}/{id}", new { action = "Index", controller = "Test", id = UrlParameter.Optional } ); } } } ```
3b91f924-e622-4e6b-90b9-d4be3e26864a
{ "language": "C#" }
```c# <h1>Legal Notice &amp; Privacy</h1> <p>Dangl.<strong>Docu</strong> hosts all documentation and help pages for products and services offered by Dangl<strong>IT</strong> as well as for multiple open source projects.</p> <p> This website is operated and hosted by <a href="https://www.dangl-it.com/legal-notice/">Dangl<strong>IT</strong> GmbH</a>. Please <a href="mailto:info@dangl-it.com">contact us</a> for any further questions. </p> <p> <strong> The source code for this website is completely open and available at <a href="https://github.com/GeorgDangl/WebDocu">GitHub</a>. </strong> </p> <h2>Privacy Information</h2> <p>If you have no user account, no information about you is stored.</p> <p> For user accounts, the only personal identifiable information stored about you is your email address. You will not receive automated newsletters, we will not give your information to anyone and we will not use your information for anything else than providing this documentation website. </p> <p> You only need your own user account if you are a customer of Dangl<strong>IT</strong> and want to get access to internal, non-public information. </p> ``` Include app info in legal notice and privacy page
```c# <h1>Legal Notice &amp; Privacy</h1> <p>Dangl.<strong>Docu</strong> hosts all documentation and help pages for products and services offered by Dangl<strong>IT</strong> as well as for multiple open source projects.</p> <p> This website is operated and hosted by <a href="https://www.dangl-it.com/legal-notice/">Dangl<strong>IT</strong> GmbH</a>. Please <a href="mailto:info@dangl-it.com">contact us</a> for any further questions. </p> <p> <strong> The source code for this website is completely open and available at <a href="https://github.com/GeorgDangl/WebDocu">GitHub</a>. </strong> </p> <h2>Privacy Information</h2> <p>If you have no user account, no information about you is stored.</p> <p> For user accounts, the only personal identifiable information stored about you is your email address. You will not receive automated newsletters, we will not give your information to anyone and we will not use your information for anything else than providing this documentation website. </p> <p> You only need your own user account if you are a customer of Dangl<strong>IT</strong> and want to get access to internal, non-public information. </p> <hr /> <p>Dangl<strong>Docu</strong> @Dangl.WebDocumentation.Services.VersionsService.Version, built @Dangl.WebDocumentation.Services.VersionsService.BuildDateUtc.ToString("dd.MM.yyyy HH:mm") (UTC)</p> ```
f1bd3cd6-6af9-404f-bbfd-43bcb2505334
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using System.Net; using UnityEngine; using UnityEngine.Networking; public class Autopilot : NetworkBehaviour { public string serverUrl; public float smoothing; private SerializableTransform targetTransform; private void Start () { if (isLocalPlayer) StartCoroutine(SendTransformToServer ()); else StartCoroutine(UpdateTransformFromServer ()); } private void Update () { if (isLocalPlayer) return; if (targetTransform != null) { transform.position = Vector3.Lerp (transform.position, targetTransform.position, smoothing); transform.rotation = Quaternion.Lerp (transform.rotation, targetTransform.rotation, smoothing); } } private IEnumerator SendTransformToServer() { while (true) { WWWForm form = new WWWForm (); form.AddField("transform", SerializableTransform.ToJson (transform)); WWW postRequest = new WWW(serverUrl + netId, form); yield return postRequest; } } private IEnumerator UpdateTransformFromServer() { while (true) { WWW getRequest = new WWW(serverUrl + netId); yield return getRequest; targetTransform = SerializableTransform.FromJson (getRequest.text); } } } ``` Check before trying to deserialize transform
```c# using System.Collections; using System.Collections.Generic; using System.Net; using UnityEngine; using UnityEngine.Networking; public class Autopilot : NetworkBehaviour { public string serverUrl; public float smoothing; private SerializableTransform targetTransform; private void Start () { if (isLocalPlayer) StartCoroutine(SendTransformToServer ()); else StartCoroutine(UpdateTransformFromServer ()); } private void Update () { if (isLocalPlayer) return; if (targetTransform != null) { transform.position = Vector3.Lerp (transform.position, targetTransform.position, smoothing); transform.rotation = Quaternion.Lerp (transform.rotation, targetTransform.rotation, smoothing); } } private IEnumerator SendTransformToServer() { while (true) { WWWForm form = new WWWForm (); form.AddField("transform", SerializableTransform.ToJson (transform)); WWW postRequest = new WWW(serverUrl + netId, form); yield return postRequest; } } private IEnumerator UpdateTransformFromServer() { while (true) { WWW getRequest = new WWW(serverUrl + netId); yield return getRequest; if (string.IsNullOrEmpty (getRequest.error)) { targetTransform = SerializableTransform.FromJson (getRequest.text); } } } } ```
5ba437ca-c639-46da-b688-7071e9a41009
{ "language": "C#" }
```c# // Copyright (c) 2016 The btcsuite developers // Copyright (c) 2016 The Decred developers // Licensed under the ISC license. See LICENSE file in the project root for full license information. using Paymetheus.Framework; using System; using System.Windows; using System.Windows.Input; namespace Paymetheus.ViewModels { public sealed class CreateAccountDialogViewModel : DialogViewModelBase { public CreateAccountDialogViewModel(ShellViewModel shell) : base(shell) { Execute = new DelegateCommand(ExecuteAction); } public string AccountName { get; set; } = ""; public string Passphrase { private get; set; } = ""; public ICommand Execute { get; } private async void ExecuteAction() { try { await App.Current.Synchronizer.WalletRpcClient.NextAccountAsync(Passphrase, AccountName); HideDialog(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } ``` Make "add account" button nonexecutable when running.
```c# // Copyright (c) 2016 The btcsuite developers // Copyright (c) 2016 The Decred developers // Licensed under the ISC license. See LICENSE file in the project root for full license information. using Grpc.Core; using Paymetheus.Framework; using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace Paymetheus.ViewModels { public sealed class CreateAccountDialogViewModel : DialogViewModelBase { public CreateAccountDialogViewModel(ShellViewModel shell) : base(shell) { Execute = new DelegateCommandAsync(ExecuteAction); } public string AccountName { get; set; } = ""; public string Passphrase { private get; set; } = ""; public ICommand Execute { get; } private async Task ExecuteAction() { try { await App.Current.Synchronizer.WalletRpcClient.NextAccountAsync(Passphrase, AccountName); HideDialog(); } catch (RpcException ex) when (ex.Status.StatusCode == StatusCode.AlreadyExists) { MessageBox.Show("Account name already exists"); } catch (RpcException ex) when (ex.Status.StatusCode == StatusCode.InvalidArgument) { // Since there is no client-side validation of account name user input, this might be an // invalid account name or the wrong passphrase. Just show the detail for now. MessageBox.Show(ex.Status.Detail); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } } } ```
7e81184d-e4a7-469c-a43d-c891e0092cf1
{ "language": "C#" }
```c# using System.Web.Mvc; using RestfulRouting.Sample.Infrastructure; using RestfulRouting.Sample.Models; namespace RestfulRouting.Sample.Controllers { public class BlogsController : Controller { public ActionResult Index() { return View(SampleData.Blogs()); } public ActionResult New() { return View(new Blog()); } public ActionResult Test(int id, string t) { var c = ControllerContext.RouteData.Values.Count; return Content("t: " + t); } public ActionResult Create() { TempData["notice"] = "Created"; return RedirectToAction("Index"); } public ActionResult Edit(int id) { return View(SampleData.Blog(id)); } public ActionResult Update(int id, Blog blog) { TempData["notice"] = "Updated " + id; return RedirectToAction("Index"); } public ActionResult Delete(int id) { return View(SampleData.Blog(id)); } public ActionResult Destroy(int id) { TempData["notice"] = "Deleted " + id; return RedirectToAction("Index"); } public ActionResult Show(int id) { return View(SampleData.Blog(id)); } } }``` Add sample to blogs index
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using RestfulRouting.Sample.Infrastructure; using RestfulRouting.Sample.Models; namespace RestfulRouting.Sample.Controllers { public class BlogsController : Controller { protected ActionResult RespondTo(Action<FormatCollection> format) { return new FormatResult(format); } public ActionResult Index() { // return View(SampleData.Blogs()); return RespondTo(format => { format.Html = View(SampleData.Blogs()); format.Xml = Content("Not exactly"); }); } public ActionResult New() { return View(new Blog()); } public ActionResult Test(int id, string t) { var c = ControllerContext.RouteData.Values.Count; return Content("t: " + t); } public ActionResult Create() { TempData["notice"] = "Created"; return RedirectToAction("Index"); } public ActionResult Edit(int id) { return View(SampleData.Blog(id)); } public ActionResult Update(int id, Blog blog) { TempData["notice"] = "Updated " + id; return RedirectToAction("Index"); } public ActionResult Delete(int id) { return View(SampleData.Blog(id)); } public ActionResult Destroy(int id) { TempData["notice"] = "Deleted " + id; return RedirectToAction("Index"); } public ActionResult Show(int id) { return View(SampleData.Blog(id)); } } }```
8be2780b-2980-48c4-8823-592ee9e4a813
{ "language": "C#" }
```c# using System.Configuration; using System.Linq; using System.Web.Mvc; namespace MAB.PCAPredictCapturePlus.TestHarness.Controllers { public class HomeController : Controller { private CapturePlusClient _client = new CapturePlusClient( apiVersion: "2.10", key: ConfigurationManager.AppSettings["PCAPredictCapturePlusKey"], defaultFindCountry: "GBR", defaultLanguage: "EN" ); public ActionResult Index() { return View(); } [HttpPost] public ActionResult Find(string term) { var result = _client.Find(term); if(result.Error != null) return Json(result.Error); return Json(result.Items); } [HttpPost] public ActionResult Retrieve(string id) { var result = _client.Retrieve(id); if(result.Error != null) return Json(result.Error); var model = result.Items.Select(a => new { Company = a.Company, BuildingName = a.BuildingName, Street = a.Street, Line1 = a.Line1, Line2 = a.Line2, Line3 = a.Line3, Line4 = a.Line4, Line5 = a.Line5, City = a.City, County = a.Province, Postcode = a.PostalCode }).First(); return Json(model); } } }``` Change default find country code
```c# using System.Configuration; using System.Linq; using System.Web.Mvc; namespace MAB.PCAPredictCapturePlus.TestHarness.Controllers { public class HomeController : Controller { private CapturePlusClient _client = new CapturePlusClient( apiVersion: "2.10", key: ConfigurationManager.AppSettings["PCAPredictCapturePlusKey"], defaultFindCountry: "GB", defaultLanguage: "EN" ); public ActionResult Index() { return View(); } [HttpPost] public ActionResult Find(string term) { var result = _client.Find(term); if(result.Error != null) return Json(result.Error); return Json(result.Items); } [HttpPost] public ActionResult Retrieve(string id) { var result = _client.Retrieve(id); if(result.Error != null) return Json(result.Error); var model = result.Items.Select(a => new { Company = a.Company, BuildingName = a.BuildingName, Street = a.Street, Line1 = a.Line1, Line2 = a.Line2, Line3 = a.Line3, Line4 = a.Line4, Line5 = a.Line5, City = a.City, County = a.Province, Postcode = a.PostalCode }).First(); return Json(model); } } }```
8ee786df-11a2-42cf-b7f5-a6c0a73cc122
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Game_Algo { class Tile { /// <summary> /// 0 - Floor /// 1 - Wall /// </summary> public int TypeId { get; set; } public Tile(int MapCellId) { this.TypeId = MapCellId; } public bool Walkable { get { return (TypeId == GameSetting.TileType.Wall) ? false : true; } } } } ``` Allow player to walk through unlocked doors
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Game_Algo { class Tile { /// <summary> /// 0 - Floor /// 1 - Wall /// </summary> public int TypeId { get; set; } public Tile(int MapCellId) { this.TypeId = MapCellId; } public bool Walkable { get { return (TypeId == GameSetting.TileType.Floor || TypeId == GameSetting.TileType.DoorUnlocked); } } } } ```
49cbfd20-8809-4653-8459-9fb3830b4a1c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuantConnect.ToolBox { /// <summary> /// Provides time stamped writing to the console /// </summary> public static class Log { /// <summary> /// Writes the message in normal text /// </summary> public static void Trace(string format, params object[] args) { Console.WriteLine("{0}: {1}", DateTime.UtcNow.ToString("o"), string.Format(format, args)); } /// <summary> /// Writes the message in red /// </summary> public static void Error(string format, params object[] args) { var foregroundColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("{0}: ERROR:: {1}", DateTime.UtcNow.ToString("o"), string.Format(format, args)); Console.ForegroundColor = foregroundColor; } } } ``` Make logging configurable by external consumers
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuantConnect.ToolBox { /// <summary> /// Provides time stamped writing to the console /// </summary> public static class Log { /// <summary> /// Defines the delegate used to perform trace logging, this allows other application /// users of the toolbox projects to intercept their logging /// </summary> public static Action<string> TraceHandler = TraceHandlerImpl; /// <summary> /// Defines the delegate used to perform error logging, this allows other application /// users of the toolbox projects to intercept their logging /// </summary> public static Action<string> ErrorHandler = ErrorHandlerImpl; /// <summary> /// Writes the message in normal text /// </summary> public static void Trace(string format, params object[] args) { TraceHandler(string.Format(format, args)); } /// <summary> /// Writes the message in red /// </summary> public static void Error(string format, params object[] args) { ErrorHandler(string.Format(format, args)); } private static void TraceHandlerImpl(string msg) { Console.WriteLine("{0}: {1}", DateTime.UtcNow.ToString("o"), msg); } private static void ErrorHandlerImpl(string msg) { var foregroundColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("{0}: ERROR:: {1}", DateTime.UtcNow.ToString("o"), msg); Console.ForegroundColor = foregroundColor; } } } ```
994df0ed-3a0f-49f9-9044-03d08637eb7b
{ "language": "C#" }
```c# // The MIT License (MIT) // // Copyright (c) 2015 Rasmus Mikkelsen // https://github.com/rasmus/EventFlow // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. namespace EventFlow.EventStores { public interface ICommittedDomainEvent { string AggregateId { get; set; } string Data { get; set; } string Metadata { get; set; } int AggregateSequenceNumber { get; set; } } } ``` Remove properties from interface as they are no longer needed
```c# // The MIT License (MIT) // // Copyright (c) 2015 Rasmus Mikkelsen // https://github.com/rasmus/EventFlow // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. namespace EventFlow.EventStores { public interface ICommittedDomainEvent { string Data { get; set; } string Metadata { get; set; } } } ```
2321884c-8a1c-4734-b4ba-f287cf5bd155
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace ExcelFormsTest.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } } ``` Update the appdelegate to make sure FreshEssentials is deployed
```c# using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace ExcelFormsTest.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); new FreshEssentials.iOS.AdvancedFrameRendereriOS(); return base.FinishedLaunching(app, options); } } } ```
80bae0b5-91ee-47e5-afdb-f6eea9af371c
{ "language": "C#" }
```c# using System; using System.ComponentModel.DataAnnotations; using System.Configuration; using System.Linq; using System.Text; namespace HermaFx.SimpleConfig { internal class CompositeConfigurationValidator : ConfigurationValidatorBase { private readonly ValidationAttribute[] _validationAttributes; private readonly string _propertyName; public CompositeConfigurationValidator(ValidationAttribute[] validationAttributes, string propertyName) { _validationAttributes = validationAttributes; _propertyName = propertyName; } public override bool CanValidate(Type type) { return true; } public override void Validate(object value) { var validationErrors = (from validation in _validationAttributes where validation.IsValid(value) == false select validation.FormatErrorMessage(_propertyName)).ToList(); if(validationErrors.Any()) { var errorMsgs = new StringBuilder("Validation Errors:"); var fullMsg = validationErrors.Aggregate(errorMsgs, (sb, cur) => sb.AppendLine(cur)).ToString(); throw new ArgumentException(fullMsg); } } } } ``` Use net4+ validation API on SimpleConfig, so we have detailed error messages.
```c# using System; using System.ComponentModel.DataAnnotations; using System.Configuration; using System.Linq; using System.Text; namespace HermaFx.SimpleConfig { internal class CompositeConfigurationValidator : ConfigurationValidatorBase { private readonly ValidationAttribute[] _validationAttributes; private readonly string _propertyName; public CompositeConfigurationValidator(ValidationAttribute[] validationAttributes, string propertyName) { _validationAttributes = validationAttributes; _propertyName = propertyName; } public override bool CanValidate(Type type) { return true; } public override void Validate(object value) { var context = new ValidationContext(value) { MemberName = _propertyName }; var errors = _validationAttributes .Select(x => x.GetValidationResult(value, context)) .Where(x => x != ValidationResult.Success) .ToArray(); if(errors.Any()) { var errorMsgs = new StringBuilder("Validation Errors:"); var fullMsg = errors.Select(x => x.ErrorMessage).Aggregate(errorMsgs, (sb, cur) => sb.AppendLine(cur)).ToString(); throw new ArgumentException(fullMsg); } } } } ```
49e4ba50-55f8-41b3-aa0c-b38b5df934e9
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Schedutalk.Logic.KTHPlaces { [DataContract] public class RoomDataContract { [DataMember(Name = "floorUid")] public string FloorUId { get; set; } [DataMember(Name = "buildingName")] public string BuildingName { get; set; } [DataMember(Name = "campus")] public string Campus { get; set; } [DataMember(Name = "typeName")] public string TypeName { get; set; } [DataMember(Name = "placeName")] public string PlaceName { get; set; } [DataMember(Name = "uid")] public string UId { get; set; } } }``` Add fields related to 5b3c493
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Schedutalk.Logic.KTHPlaces { [DataContract] public class RoomDataContract { [DataMember(Name = "floorUid")] public string FloorUId { get; set; } [DataMember(Name = "buildingName")] public string BuildingName { get; set; } [DataMember(Name = "campus")] public string Campus { get; set; } [DataMember(Name = "typeName")] public string TypeName { get; set; } [DataMember(Name = "placeName")] public string PlaceName { get; set; } [DataMember(Name = "uid")] public string UId { get; set; } [DataMember(Name = "equipment")] public Equipment[] Equipment { get; set; } } [DataContract] public class Equipment { [DataMember(Name = "name")] public Name Name { get; set; } } [DataContract] public class Name { [DataMember(Name = "en")] public string En { get; set; } } }```
844f632a-8b72-4169-9001-d9ca2a200d6c
{ "language": "C#" }
```c# using ChromeCast.Desktop.AudioStreamer.Application; namespace ChromeCast.Desktop.AudioStreamer.Discover { public class DiscoveredDevice { private const string GroupIdentifier = "\"md=Google Cast Group\""; public string Name { get; set; } public string IPAddress { get; set; } public int Port { get; set; } public string Protocol { get; set; } public string Usn { get; set; } public string Headers { get; set; } public bool AddedByDeviceInfo { get; internal set; } public DeviceEureka Eureka { get; internal set; } public Group Group { get; internal set; } public bool IsGroup { get { if (Headers != null && Headers.IndexOf(GroupIdentifier) >= 0) return true; return false; } set { if (value) Headers = GroupIdentifier; } } } } ``` Fix for persisting the known devices.
```c# using ChromeCast.Desktop.AudioStreamer.Application; using System.Xml.Serialization; namespace ChromeCast.Desktop.AudioStreamer.Discover { public class DiscoveredDevice { private const string GroupIdentifier = "\"md=Google Cast Group\""; public string Name { get; set; } public string IPAddress { get; set; } public int Port { get; set; } public string Protocol { get; set; } public string Usn { get; set; } public string Headers { get; set; } public bool AddedByDeviceInfo { get; set; } [XmlIgnore] public DeviceEureka Eureka { get; set; } [XmlIgnore] public Group Group { get; set; } public bool IsGroup { get { if (Headers != null && Headers.IndexOf(GroupIdentifier) >= 0) return true; return false; } set { if (value) Headers = GroupIdentifier; } } } } ```
ac253546-48ec-4dfc-83a6-4784dc27d842
{ "language": "C#" }
```c# using StructuredXmlEditor.View; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace StructuredXmlEditor { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public App() { if (!Debugger.IsAttached) this.Dispatcher.UnhandledException += OnDispatcherUnhandledException; VersionInfo.DeleteUpdater(); } void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { string errorMessage = "An unhandled exception occurred!\n" + e.Exception.Message + "\n\nThe app has attempted to recover and carry on, but you may experience some weirdness. Report error?."; File.WriteAllText("error.log", e.Exception.ToString()); var choice = Message.Show(errorMessage, "Error", "Report", "Ignore"); if (choice == "Report") { Email.SendEmail("Crash Report", "Editor crashed on " + DateTime.Now + ".\nEditor Version: " + VersionInfo.Version, e.Exception.ToString()); Message.Show("Error Reported, I shall fix as soon as possible.", "Error reported", "Ok"); } e.Handled = true; } } } ``` Change the padding on the exception message
```c# using StructuredXmlEditor.View; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace StructuredXmlEditor { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public App() { if (!Debugger.IsAttached) this.Dispatcher.UnhandledException += OnDispatcherUnhandledException; VersionInfo.DeleteUpdater(); } void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { string errorMessage = "An unhandled exception occurred!\n\n" + e.Exception.Message + "\n\nThe app has attempted to recover and carry on, but you may experience some weirdness. Report error?"; File.WriteAllText("error.log", e.Exception.ToString()); var choice = Message.Show(errorMessage, "Error", "Report", "Ignore"); if (choice == "Report") { Email.SendEmail("Crash Report", "Editor crashed on " + DateTime.Now + ".\nEditor Version: " + VersionInfo.Version, e.Exception.ToString()); Message.Show("Error Reported, I shall fix as soon as possible.", "Error reported", "Ok"); } e.Handled = true; } } } ```
0a67b263-9b1c-4781-bd9a-f012aea6d2bb
{ "language": "C#" }
```c# <script type="text/javascript">searchHighlight()</script> <?cs if:len(links.alternate) ?> <div id="altlinks"> <h3>Download in other formats:</h3> <ul><?cs each:link = links.alternate ?> <li<?cs if:name(link) == len(links.alternate) - #1 ?> class="last"<?cs /if ?>> <a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a> </li><?cs /each ?> </ul> </div> <?cs /if ?> </div> <div id="footer"> <hr /> <a id="tracpowered" href="http://trac.edgewall.com/"><img src="<?cs var:$htdocs_location ?>trac_logo_mini.png" height="30" width="107" alt="Trac Powered"/></a> <p class="left"> Powered by <strong>Trac <?cs var:trac.version ?></strong><br /> By <a href="http://www.edgewall.com/">Edgewall Software</a>. </p> <p class="right"> <?cs var $project.footer ?> </p> </div> <?cs include "site_footer.cs" ?> </body> </html> ``` Add a link to "about trac" on the trac version number at the end
```c# <script type="text/javascript">searchHighlight()</script> <?cs if:len(links.alternate) ?> <div id="altlinks"> <h3>Download in other formats:</h3> <ul><?cs each:link = links.alternate ?> <li<?cs if:name(link) == len(links.alternate) - #1 ?> class="last"<?cs /if ?>> <a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a> </li><?cs /each ?> </ul> </div> <?cs /if ?> </div> <div id="footer"> <hr /> <a id="tracpowered" href="http://trac.edgewall.com/"><img src="<?cs var:$htdocs_location ?>trac_logo_mini.png" height="30" width="107" alt="Trac Powered"/></a> <p class="left"> Powered by <a href="<?cs var:trac.href.about ?>"><strong>Trac <?cs var:trac.version ?></strong></a><br /> By <a href="http://www.edgewall.com/">Edgewall Software</a>. </p> <p class="right"> <?cs var $project.footer ?> </p> </div> <?cs include "site_footer.cs" ?> </body> </html> ```
eb64428d-dde2-49b4-bd54-f36a0c0737d2
{ "language": "C#" }
```c# using System; using System.Collections.Specialized; using System.IO; using System.Web; using Newtonsoft.Json; namespace WebServer { public class RequestInformation { public NameValueCollection Headers { get; private set; } public string BodyContent { get; private set; } public int BodyLength { get; private set; } public bool SecureConnection { get; private set; } public bool ClientCertificatePresent { get; private set; } public HttpClientCertificate ClientCertificate { get; private set; } public static RequestInformation Create(HttpRequest request) { var info = new RequestInformation(); info.Headers = request.Headers; Stream stream = request.GetBufferedInputStream(); using (var reader = new StreamReader(stream)) { string body = reader.ReadToEnd(); info.BodyContent = body; info.BodyLength = body.Length; } info.SecureConnection = request.IsSecureConnection; var cs = request.ClientCertificate; info.ClientCertificatePresent = cs.IsPresent; if (cs.IsPresent) { info.ClientCertificate = request.ClientCertificate; } return info; } public static RequestInformation DeSerializeFromJson(string json) { return (RequestInformation)JsonConvert.DeserializeObject( json, typeof(RequestInformation), new NameValueCollectionConverter()); } public string SerializeToJson() { return JsonConvert.SerializeObject(this, new NameValueCollectionConverter()); } private RequestInformation() { } } } ``` Add HTTP request verb and url to echo response
```c# using System; using System.Collections.Specialized; using System.IO; using System.Web; using Newtonsoft.Json; namespace WebServer { public class RequestInformation { public string Verb { get; private set; } public string Url { get; private set; } public NameValueCollection Headers { get; private set; } public string BodyContent { get; private set; } public int BodyLength { get; private set; } public bool SecureConnection { get; private set; } public bool ClientCertificatePresent { get; private set; } public HttpClientCertificate ClientCertificate { get; private set; } public static RequestInformation Create(HttpRequest request) { var info = new RequestInformation(); info.Verb = request.HttpMethod; info.Url = request.RawUrl; info.Headers = request.Headers; Stream stream = request.GetBufferedInputStream(); using (var reader = new StreamReader(stream)) { string body = reader.ReadToEnd(); info.BodyContent = body; info.BodyLength = body.Length; } info.SecureConnection = request.IsSecureConnection; var cs = request.ClientCertificate; info.ClientCertificatePresent = cs.IsPresent; if (cs.IsPresent) { info.ClientCertificate = request.ClientCertificate; } return info; } public static RequestInformation DeSerializeFromJson(string json) { return (RequestInformation)JsonConvert.DeserializeObject( json, typeof(RequestInformation), new NameValueCollectionConverter()); } public string SerializeToJson() { return JsonConvert.SerializeObject(this, new NameValueCollectionConverter()); } private RequestInformation() { } } } ```
fc9fc469-a26c-459c-b77a-d990d3efefd6
{ "language": "C#" }
```c# using System.Collections.Generic; namespace DotVVM.Framework.Diagnostics.Models { public class HttpHeaderItem { public string Key { get; set; } public string Value { get; set; } public static HttpHeaderItem FromKeyValuePair(KeyValuePair<string, string[]> pair) { return new HttpHeaderItem { Key = pair.Key, Value = pair.Value[0] }; } } }``` Add sending of all http header values
```c# using System.Collections.Generic; namespace DotVVM.Framework.Diagnostics.Models { public class HttpHeaderItem { public string Key { get; set; } public string Value { get; set; } public static HttpHeaderItem FromKeyValuePair(KeyValuePair<string, string[]> pair) { return new HttpHeaderItem { Key = pair.Key, Value = string.Join("; ", pair.Value) }; } } }```
8f95450b-2807-4ebe-b1dd-c28591e858b4
{ "language": "C#" }
```c#  @if (Request.IsAuthenticated) { <div class="btn-group"> <a class="btn btn-inverse" href="#"><i class="icon-user icon-white"></i> @User.Identity.Name</a> <a class="btn btn-inverse dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a> <ul class="dropdown-menu"> <li>@Html.ActionLink("Details", "User", "Account")</li> <li><a href="javascript:document.getElementById('logoutMenuForm').submit()">Logout</a></li> </ul> </div> using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutMenuForm", @class="hidden" })) { @Html.AntiForgeryToken() } } else { <a class="btn btn-info" href="@Url.Action("Login", "Account")" > <i class="icon-user icon-white"></i> Login</a> }``` Fix up menu for IE
```c#  @if (Request.IsAuthenticated) { <li> <div class="btn-group"> <a class="btn btn-inverse" href="#"><i class="icon-user icon-white"></i> @User.Identity.Name</a> <a class="btn btn-inverse dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a> <ul class="dropdown-menu"> <li>@Html.ActionLink("Details", "User", "Account")</li> <li><a href="javascript:document.getElementById('logoutMenuForm').submit()">Logout</a></li> </ul> </div> </li> using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutMenuForm", @class="hidden" })) { @Html.AntiForgeryToken() } } else { <li><a class="btn btn-info" href="@Url.Action("Login", "Account")" > <i class="icon-user icon-white"></i> Login</a></li> }```
3556a7bd-e0a3-42a1-a129-61cf1e46208d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace Glimpse.Agent.AspNet.Mvc { internal class ActionSelectedMessage : IMessage { public Guid Id { get; } = Guid.NewGuid(); public DateTime Time { get; } = DateTime.Now; public string ActionId { get; set; } public string DisplayName { get; set; } public RouteData RouteData { get; set; } } internal class RouteData { public string Name { get; set; } public string Pattern { get; set; } public IList<RouteResolutionData> Data { get; set; } } internal class RouteResolutionData { public string Tag { get; set; } public string Match { get; set; } } }``` Fix some spacing in class
```c# using System; using System.Collections.Generic; namespace Glimpse.Agent.AspNet.Mvc { internal class ActionSelectedMessage : IMessage { public Guid Id { get; } = Guid.NewGuid(); public DateTime Time { get; } = DateTime.Now; public string ActionId { get; set; } public string DisplayName { get; set; } public RouteData RouteData { get; set; } } internal class RouteData { public string Name { get; set; } public string Pattern { get; set; } public IList<RouteResolutionData> Data { get; set; } } internal class RouteResolutionData { public string Tag { get; set; } public string Match { get; set; } } }```
c756af22-f954-48cb-80b3-1a0409e7977f
{ "language": "C#" }
```c# using Moq; using NUnit.Framework; using PhotoLife.Data.Contracts; using PhotoLife.Models; namespace PhotoLife.Services.Tests.UserServiceTests { [TestFixture] public class GetById_Should { [TestCase("some id")] [TestCase("other id")] public void _CallRepository_GetByIdMethod(string id) { //Arrange var mockedRepository = new Mock<IRepository<User>>(); var mockedUnitOfWork = new Mock<IUnitOfWork>(); var userService = new UserService(mockedRepository.Object, mockedUnitOfWork.Object); //Act userService.GetUserById(id); //Assert mockedRepository.Verify(r => r.GetById(id), Times.Once); } } } ``` Add more tests for get by id
```c# using Moq; using NUnit.Framework; using PhotoLife.Data.Contracts; using PhotoLife.Models; namespace PhotoLife.Services.Tests.UserServiceTests { [TestFixture] public class GetById_Should { [TestCase("some id")] [TestCase("other id")] public void _CallRepository_GetByIdMethod(string id) { //Arrange var mockedRepository = new Mock<IRepository<User>>(); var mockedUnitOfWork = new Mock<IUnitOfWork>(); var userService = new UserService(mockedRepository.Object, mockedUnitOfWork.Object); //Act userService.GetUserById(id); //Assert mockedRepository.Verify(r => r.GetById(id), Times.Once); } [TestCase("some id")] [TestCase("other id")] public void _Return_Correctly(string id) { //Arrange var mockedUser = new Mock<User>(); var mockedRepository = new Mock<IRepository<User>>(); mockedRepository.Setup(r=>r.GetById(It.IsAny<string>())).Returns(mockedUser.Object); var mockedUnitOfWork = new Mock<IUnitOfWork>(); var userService = new UserService(mockedRepository.Object, mockedUnitOfWork.Object); //Act var res = userService.GetUserById(id); //Assert Assert.AreSame(mockedUser.Object, res); } } } ```
2737fcc0-faf3-48b4-8311-ade1cab17e31
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Threading; using osu.Game.Graphics.Backgrounds; namespace osu.Game.Screens.Backgrounds { public class BackgroundScreenDefault : BackgroundScreen { private int currentDisplay; private const int background_count = 5; private string backgroundName => $@"Menu/menu-background-{currentDisplay % background_count + 1}"; private Background current; [BackgroundDependencyLoader] private void load() { display(new Background(backgroundName)); } private void display(Background newBackground) { current?.FadeOut(800, Easing.InOutSine); current?.Expire(); Add(current = newBackground); currentDisplay++; } private ScheduledDelegate nextTask; public void Next() { nextTask?.Cancel(); nextTask = Scheduler.AddDelayed(() => { LoadComponentAsync(new Background(backgroundName) { Depth = currentDisplay }, display); }, 100); } } } ``` Use random default background on starting the game
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.MathUtils; using osu.Framework.Threading; using osu.Game.Graphics.Backgrounds; namespace osu.Game.Screens.Backgrounds { public class BackgroundScreenDefault : BackgroundScreen { private int currentDisplay; private const int background_count = 5; private string backgroundName => $@"Menu/menu-background-{currentDisplay % background_count + 1}"; private Background current; [BackgroundDependencyLoader] private void load() { currentDisplay = RNG.Next(0, background_count); display(new Background(backgroundName)); } private void display(Background newBackground) { current?.FadeOut(800, Easing.InOutSine); current?.Expire(); Add(current = newBackground); currentDisplay++; } private ScheduledDelegate nextTask; public void Next() { nextTask?.Cancel(); nextTask = Scheduler.AddDelayed(() => { LoadComponentAsync(new Background(backgroundName) { Depth = currentDisplay }, display); }, 100); } } } ```
bc732eea-85e0-43b9-a492-374e0165582e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Windows; using System.Windows.Data; using System.Windows.Media.Imaging; using SylphyHorn.Services; namespace SylphyHorn.UI.Controls { public class UnlockImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) return null; using (var stream = new FileStream((string)value, FileMode.Open)) { var decoder = BitmapDecoder.Create( stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); var bitmap = new WriteableBitmap(decoder.Frames[0]); bitmap.Freeze(); return bitmap; } } catch (Exception ex) { LoggingService.Instance.Register(ex); return null; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } ``` Fix issue to throw exception when wallpaper isn't set.
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Windows; using System.Windows.Data; using System.Windows.Media.Imaging; using SylphyHorn.Services; namespace SylphyHorn.UI.Controls { public class UnlockImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) return null; var filename = (string)value; if (string.IsNullOrEmpty(filename)) return null; using (var stream = new FileStream(filename, FileMode.Open)) { var decoder = BitmapDecoder.Create( stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); var bitmap = new WriteableBitmap(decoder.Frames[0]); bitmap.Freeze(); return bitmap; } } catch (Exception ex) { LoggingService.Instance.Register(ex); return null; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } ```
d3fe9fdb-9df0-4563-89c4-2229fe87d1ca
{ "language": "C#" }
```c# using System.Text.RegularExpressions; namespace Sep.Git.Tfs { public static class GitTfsConstants { public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase); public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase); public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$"); public const string DefaultRepositoryId = "default"; public const string GitTfsPrefix = "git-tfs"; // e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123 public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}"; public static readonly Regex TfsCommitInfoRegex = new Regex("^\\s*" + GitTfsPrefix + "-id:\\s+" + "\\[(?<url>.+)\\]" + "(?<repository>.+);" + "C(?<changeset>\\d+)" + "\\s*$"); } } ``` Add regex for associating work items
```c# using System.Text.RegularExpressions; namespace Sep.Git.Tfs { public static class GitTfsConstants { public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase); public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase); public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$"); public const string DefaultRepositoryId = "default"; public const string GitTfsPrefix = "git-tfs"; // e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123 public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}"; public static readonly Regex TfsCommitInfoRegex = new Regex("^\\s*" + GitTfsPrefix + "-id:\\s+" + "\\[(?<url>.+)\\]" + "(?<repository>.+);" + "C(?<changeset>\\d+)" + "\\s*$"); // e.g. git-tfs-work-item: 24 associate public static readonly Regex TfsWorkItemRegex = new Regex(@"^\s*"+ GitTfsPrefix + @"-work-item:\s+(?<item_id>\d+)\s(?<action>.+)"); } } ```
a696ac0f-3c3d-4d15-820b-0630b43083cd
{ "language": "C#" }
```c# using PKISharp.WACS.Services; namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns { class Manual : DnsValidation<ManualOptions, Manual> { private IInputService _input; public Manual(ILogService log, IInputService input, ManualOptions options, string identifier) : base(log, options, identifier) { // Usually it's a big no-no to rely on user input in validation plugin // because this should be able to run unattended. This plugin is for testing // only and therefor we will allow it. Future versions might be more advanced, // e.g. shoot an email to an admin and complete the order later. _input = input; } public override void CreateRecord(string recordName, string token) { _log.Warning("Create record {recordName} for domain {identifier} with content {token}", recordName, _identifier, token); _input.Wait(); } public override void DeleteRecord(string recordName, string token) { _log.Warning("Delete record {recordName} for domain {identifier}", recordName, _identifier); _input.Wait(); } } } ``` Use proper input instead of log message to request manual DNS change
```c# using PKISharp.WACS.Services; namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns { class Manual : DnsValidation<ManualOptions, Manual> { private IInputService _input; public Manual(ILogService log, IInputService input, ManualOptions options, string identifier) : base(log, options, identifier) { // Usually it's a big no-no to rely on user input in validation plugin // because this should be able to run unattended. This plugin is for testing // only and therefor we will allow it. Future versions might be more advanced, // e.g. shoot an email to an admin and complete the order later. _input = input; } public override void CreateRecord(string recordName, string token) { _input.Wait($"Create record {recordName} for domain {_identifier} with content {token} and press enter to continue..."); } public override void DeleteRecord(string recordName, string token) { _input.Wait($"Delete record {recordName} for domain {_identifier}"); } } } ```
3be18c9c-14c8-4977-995a-26cd9f210458
{ "language": "C#" }
```c# using System; using NUnit.Framework; namespace MongoDB.Driver.Connections { [TestFixture] public class TestConnectionFactory { [TearDown] public void TearDown (){ ConnectionFactory.Shutdown (); } [Test] public void TestGetConnection (){ var connection1 = ConnectionFactory.GetConnection (string.Empty); var connection2 = ConnectionFactory.GetConnection (string.Empty); Assert.IsNotNull (connection1); Assert.IsNotNull (connection2); Assert.AreEqual (1, ConnectionFactory.PoolCount); } [Test] public void TestCreatePoolForEachUniqeConnectionString (){ ConnectionFactory.GetConnection (string.Empty); ConnectionFactory.GetConnection (string.Empty); ConnectionFactory.GetConnection ("Username=test"); ConnectionFactory.GetConnection ("Username=test"); ConnectionFactory.GetConnection ("Server=localhost"); Assert.AreEqual (3, ConnectionFactory.PoolCount); } [Test] public void TestGetInvalidConnection (){ bool thrown = false; try{ ConnectionFactory.GetConnection("MinimumPoolSize=50; MaximumPoolSize=10"); }catch(ArgumentException){ thrown = true; }catch(Exception){ Assert.Fail("Wrong exception thrown"); } } } } ``` Fix compiler warning and rename test to be more clear.
```c# using System; using NUnit.Framework; namespace MongoDB.Driver.Connections { [TestFixture] public class TestConnectionFactory { [TearDown] public void TearDown (){ ConnectionFactory.Shutdown (); } [Test] public void TestGetConnection (){ var connection1 = ConnectionFactory.GetConnection (string.Empty); var connection2 = ConnectionFactory.GetConnection (string.Empty); Assert.IsNotNull (connection1); Assert.IsNotNull (connection2); Assert.AreEqual (1, ConnectionFactory.PoolCount); } [Test] public void TestCreatePoolForEachUniqeConnectionString (){ ConnectionFactory.GetConnection (string.Empty); ConnectionFactory.GetConnection (string.Empty); ConnectionFactory.GetConnection ("Username=test"); ConnectionFactory.GetConnection ("Username=test"); ConnectionFactory.GetConnection ("Server=localhost"); Assert.AreEqual (3, ConnectionFactory.PoolCount); } [Test] public void TestExceptionWhenMinimumPoolSizeIsGreaterThenMaximumPoolSize (){ try{ ConnectionFactory.GetConnection("MinimumPoolSize=50; MaximumPoolSize=10"); }catch(ArgumentException){ }catch(Exception){ Assert.Fail("Wrong exception thrown"); } } } } ```
0353d56e-e001-41d5-af23-1a555e7a5f7c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; using OneWayMirror.Core; namespace OneWayMirror { internal sealed class ReportingConsoleHost : ConsoleHost { private readonly string _reportEmailAddress; internal ReportingConsoleHost(bool verbose, string reportEmailAddress) : base(verbose) { _reportEmailAddress = reportEmailAddress; } private void SendMail(string body) { using (var msg = new MailMessage()) { msg.To.Add(new MailAddress(_reportEmailAddress)); msg.From = new MailAddress(Environment.UserDomainName + @"@microsoft.com"); msg.IsBodyHtml = false; msg.Subject = "Git to TFS Mirror Error"; msg.Body = body; var client = new SmtpClient("smtphost"); client.UseDefaultCredentials = true; client.Send(msg); } } public override void Error(string format, params object[] args) { base.Error(format, args); SendMail(string.Format(format, args)); } } } ``` Use UserName instead of UserDomainName
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; using OneWayMirror.Core; namespace OneWayMirror { internal sealed class ReportingConsoleHost : ConsoleHost { private readonly string _reportEmailAddress; internal ReportingConsoleHost(bool verbose, string reportEmailAddress) : base(verbose) { _reportEmailAddress = reportEmailAddress; } private void SendMail(string body) { using (var msg = new MailMessage()) { msg.To.Add(new MailAddress(_reportEmailAddress)); msg.From = new MailAddress(Environment.UserName + @"@microsoft.com"); msg.IsBodyHtml = false; msg.Subject = "Git to TFS Mirror Error"; msg.Body = body; var client = new SmtpClient("smtphost"); client.UseDefaultCredentials = true; client.Send(msg); } } public override void Error(string format, params object[] args) { base.Error(format, args); SendMail(string.Format(format, args)); } } } ```
a8c4d170-4d9c-421b-81f7-bd781089b2c8
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.Threading.Tasks; using System.Windows.Input; namespace Fotografix { public sealed class DelegateCommand : ICommand { private readonly Func<bool> canExecute; private readonly Func<Task> execute; private bool executing; public DelegateCommand(Action execute) : this(() => true, () => { execute(); return Task.CompletedTask; }) { } public DelegateCommand(Func<Task> execute) : this(() => true, execute) { } public DelegateCommand(Func<bool> canExecute, Func<Task> execute) { this.canExecute = canExecute; this.execute = execute; } public event EventHandler CanExecuteChanged { add { } remove { } } public bool CanExecute(object parameter) { return canExecute(); } public async void Execute(object parameter) { if (executing) { /* * This scenario can occur in two situations: * 1. The user invokes the command again before the previous async execution has completed. * 2. A bug in the XAML framework that sometimes triggers a command twice when using a keyboard accelerator. */ Debug.WriteLine("Skipping command execution since previous execution has not completed yet"); return; } try { this.executing = true; await execute(); } finally { this.executing = false; } } } } ``` Disable commands while they are executing
```c# using System; using System.Diagnostics; using System.Threading.Tasks; using System.Windows.Input; namespace Fotografix { public sealed class DelegateCommand : ICommand { private readonly Func<bool> canExecute; private readonly Func<Task> execute; private bool executing; public DelegateCommand(Action execute) : this(() => true, () => { execute(); return Task.CompletedTask; }) { } public DelegateCommand(Func<Task> execute) : this(() => true, execute) { } public DelegateCommand(Func<bool> canExecute, Func<Task> execute) { this.canExecute = canExecute; this.execute = execute; } public bool IsExecuting { get => executing; private set { this.executing = value; RaiseCanExecuteChanged(); } } public event EventHandler CanExecuteChanged; public void RaiseCanExecuteChanged() { CanExecuteChanged?.Invoke(this, EventArgs.Empty); } public bool CanExecute(object parameter) { return !executing && canExecute(); } public async void Execute(object parameter) { if (IsExecuting) { /* * This scenario can occur in two situations: * 1. The user invokes the command again before the previous async execution has completed. * 2. A bug in the XAML framework that sometimes triggers a command twice when using a keyboard accelerator. */ Debug.WriteLine("Skipping command execution since previous execution has not completed yet"); return; } try { this.IsExecuting = true; await execute(); } finally { this.IsExecuting = false; } } } } ```
20ec26fc-2312-45de-bb49-178163e435f1
{ "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.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Online; namespace osu.Game.Overlays { public abstract class OnlineOverlay<T> : FullscreenOverlay<T> where T : OverlayHeader { protected override Container<Drawable> Content => content; protected readonly OverlayScrollContainer ScrollFlow; protected readonly LoadingLayer Loading; private readonly Container content; protected OnlineOverlay(OverlayColourScheme colourScheme, bool requiresSignIn = true) : base(colourScheme) { var mainContent = requiresSignIn ? new OnlineViewContainer($"Sign in to view the {Header.Title.Title}") : new Container(); mainContent.RelativeSizeAxes = Axes.Both; mainContent.AddRange(new Drawable[] { ScrollFlow = new OverlayScrollContainer { RelativeSizeAxes = Axes.Both, ScrollbarVisible = false, Child = new FillFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Direction = FillDirection.Vertical, Children = new Drawable[] { Header.With(h => h.Depth = float.MinValue), content = new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y } } } }, Loading = new LoadingLayer() }); base.Content.Add(mainContent); } } } ``` Revert change to loading layer's default state
```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.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Online; namespace osu.Game.Overlays { public abstract class OnlineOverlay<T> : FullscreenOverlay<T> where T : OverlayHeader { protected override Container<Drawable> Content => content; protected readonly OverlayScrollContainer ScrollFlow; protected readonly LoadingLayer Loading; private readonly Container content; protected OnlineOverlay(OverlayColourScheme colourScheme, bool requiresSignIn = true) : base(colourScheme) { var mainContent = requiresSignIn ? new OnlineViewContainer($"Sign in to view the {Header.Title.Title}") : new Container(); mainContent.RelativeSizeAxes = Axes.Both; mainContent.AddRange(new Drawable[] { ScrollFlow = new OverlayScrollContainer { RelativeSizeAxes = Axes.Both, ScrollbarVisible = false, Child = new FillFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Direction = FillDirection.Vertical, Children = new Drawable[] { Header.With(h => h.Depth = float.MinValue), content = new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y } } } }, Loading = new LoadingLayer(true) }); base.Content.Add(mainContent); } } } ```
0f8aa504-ba18-4b3a-a342-ed429a229759
{ "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.TypeExtensions; namespace osu.Framework.Localisation { /// <summary> /// Indicates that the members of an enum can be localised. /// </summary> [AttributeUsage(AttributeTargets.Enum)] public sealed class LocalisableEnumAttribute : Attribute { /// <summary> /// The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s. /// </summary> public readonly Type MapperType; /// <summary> /// Creates a new <see cref="LocalisableEnumAttribute"/>. /// </summary> /// <param name="mapperType">The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.</param> public LocalisableEnumAttribute(Type mapperType) { MapperType = mapperType; if (!typeof(IEnumLocalisationMapper).IsAssignableFrom(mapperType)) throw new ArgumentException($"Type \"{mapperType.ReadableName()}\" must inherit from {nameof(EnumLocalisationMapper<Enum>)}.", nameof(mapperType)); } } } ``` Add description indicating retrieval method
```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.Extensions.TypeExtensions; namespace osu.Framework.Localisation { /// <summary> /// Indicates that the values of an enum have <see cref="LocalisableString"/> descriptions. /// The descriptions can be returned through <see cref="ExtensionMethods.GetLocalisableDescription{T}"/>. /// </summary> [AttributeUsage(AttributeTargets.Enum)] public sealed class LocalisableEnumAttribute : Attribute { /// <summary> /// The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s. /// </summary> public readonly Type MapperType; /// <summary> /// Creates a new <see cref="LocalisableEnumAttribute"/>. /// </summary> /// <param name="mapperType">The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.</param> public LocalisableEnumAttribute(Type mapperType) { MapperType = mapperType; if (!typeof(IEnumLocalisationMapper).IsAssignableFrom(mapperType)) throw new ArgumentException($"Type \"{mapperType.ReadableName()}\" must inherit from {nameof(EnumLocalisationMapper<Enum>)}.", nameof(mapperType)); } } } ```
aa8b36e6-bd05-434c-a26c-6a302f7e5b16
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using Hadouken.Common; using Hadouken.Hosting; namespace Hadouken.Hosts.WindowsService { public class HdknService : ServiceBase { private IHadoukenHost _host; public HdknService() { InitializeComponent(); } private void InitializeComponent() { this.AutoLog = true; this.ServiceName = "Hadouken"; } protected override void OnStart(string[] args) { Task.Factory.StartNew(() => { _host = Kernel.Get<IHadoukenHost>(); _host.Load(); }); } protected override void OnStop() { if (_host != null) _host.Unload(); } } } ``` Load the service in the main thread, once more.
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using Hadouken.Common; using Hadouken.Hosting; using System.Threading; namespace Hadouken.Hosts.WindowsService { public class HdknService : ServiceBase { private IHadoukenHost _host; public HdknService() { InitializeComponent(); } private void InitializeComponent() { this.AutoLog = true; this.ServiceName = "Hadouken"; } protected override void OnStart(string[] args) { Load(); } private void Load() { _host = Kernel.Get<IHadoukenHost>(); _host.Load(); } protected override void OnStop() { if (_host != null) _host.Unload(); } } } ```
5a7053b3-1f65-4993-bf1e-f72aa7e2a074
{ "language": "C#" }
```c# using JetBrains.Annotations; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.Core.Common.Fields; namespace Orchard.Core.Common.Drivers { [UsedImplicitly] public class TextFieldDriver : ContentFieldDriver<TextField> { public IOrchardServices Services { get; set; } private const string TemplateName = "Fields/Common.TextField"; public TextFieldDriver(IOrchardServices services) { Services = services; } private static string GetPrefix(TextField field, ContentPart part) { return part.PartDefinition.Name + "." + field.Name; } protected override DriverResult Display(ContentPart part, TextField field, string displayType) { return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part)); } protected override DriverResult Editor(ContentPart part, TextField field) { return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part)).Location("primary", "5"); } protected override DriverResult Editor(ContentPart part, TextField field, IUpdateModel updater) { updater.TryUpdateModel(field, GetPrefix(field, part), null, null); return Editor(part, field); } } } ``` Create Display/Editor location settings for Parts and Fields
```c# using JetBrains.Annotations; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.Core.Common.Fields; using Orchard.Core.Common.Settings; namespace Orchard.Core.Common.Drivers { [UsedImplicitly] public class TextFieldDriver : ContentFieldDriver<TextField> { public IOrchardServices Services { get; set; } private const string TemplateName = "Fields/Common.TextField"; public TextFieldDriver(IOrchardServices services) { Services = services; } private static string GetPrefix(TextField field, ContentPart part) { return part.PartDefinition.Name + "." + field.Name; } protected override DriverResult Display(ContentPart part, TextField field, string displayType) { var locationSettings = field.PartFieldDefinition.Settings.GetModel<LocationSettings>("DisplayLocation") ?? new LocationSettings { Zone = "primary", Position = "5" }; return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part)) .Location(locationSettings.Zone, locationSettings.Position); } protected override DriverResult Editor(ContentPart part, TextField field) { var locationSettings = field.PartFieldDefinition.Settings.GetModel<LocationSettings>("EditorLocation") ?? new LocationSettings { Zone = "primary", Position = "5" }; return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part)) .Location(locationSettings.Zone, locationSettings.Position); } protected override DriverResult Editor(ContentPart part, TextField field, IUpdateModel updater) { updater.TryUpdateModel(field, GetPrefix(field, part), null, null); return Editor(part, field); } } } ```
1f9424ab-26de-4c21-8fec-1e174128c29d
{ "language": "C#" }
```c# // Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Reflection; [assembly: AssemblyTitle("Perspex.Styling.UnitTests")] ``` Fix intermittent Style unit test failures.
```c# // Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Reflection; using Xunit; [assembly: AssemblyTitle("Perspex.Styling.UnitTests")] // Don't run tests in parallel. [assembly: CollectionBehavior(DisableTestParallelization = true)]```
569bdf4e-306a-442c-9e2b-efc7773dbfde
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Sandbox.ModAPI; using VRage.Game.Components; namespace Torch.Mod { [MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)] public class TorchModCore : MySessionComponentBase { public const ulong MOD_ID = 1406994352; private static bool _init; public static bool Debug; public override void UpdateAfterSimulation() { if (_init) return; _init = true; ModCommunication.Register(); MyAPIGateway.Utilities.MessageEntered += Utilities_MessageEntered; } private void Utilities_MessageEntered(string messageText, ref bool sendToOthers) { if (messageText == "@!debug") { Debug = !Debug; MyAPIGateway.Utilities.ShowMessage("Torch", $"Debug: {Debug}"); sendToOthers = false; } } protected override void UnloadData() { try { ModCommunication.Unregister(); } catch { //session unloading, don't care } } } } ``` Fix dumb in torch mod
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Sandbox.ModAPI; using VRage.Game.Components; namespace Torch.Mod { [MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)] public class TorchModCore : MySessionComponentBase { public const ulong MOD_ID = 1406994352; private static bool _init; public static bool Debug; public override void UpdateAfterSimulation() { if (_init) return; _init = true; ModCommunication.Register(); MyAPIGateway.Utilities.MessageEntered += Utilities_MessageEntered; } private void Utilities_MessageEntered(string messageText, ref bool sendToOthers) { if (messageText == "@!debug") { Debug = !Debug; MyAPIGateway.Utilities.ShowMessage("Torch", $"Debug: {Debug}"); sendToOthers = false; } } protected override void UnloadData() { try { MyAPIGateway.Utilities.MessageEntered -= Utilities_MessageEntered; ModCommunication.Unregister(); } catch { //session unloading, don't care } } } } ```
39dd5df2-b2f2-4594-8575-3ee66623d5da
{ "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 NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Utils; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneStarCounter : OsuTestScene { private readonly StarCounter starCounter; private readonly OsuSpriteText starsLabel; public TestSceneStarCounter() { starCounter = new StarCounter { Origin = Anchor.Centre, Anchor = Anchor.Centre, }; Add(starCounter); starsLabel = new OsuSpriteText { Origin = Anchor.Centre, Anchor = Anchor.Centre, Scale = new Vector2(2), Y = 50, }; Add(starsLabel); setStars(5); AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10); AddStep("stop animation", () => starCounter.StopAnimation()); AddStep("reset", () => setStars(0)); } private void setStars(float stars) { starCounter.Current = stars; starsLabel.Text = starCounter.Current.ToString("0.00"); } } } ``` Add slider test step for visual inspection purposes
```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 NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Utils; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneStarCounter : OsuTestScene { private readonly StarCounter starCounter; private readonly OsuSpriteText starsLabel; public TestSceneStarCounter() { starCounter = new StarCounter { Origin = Anchor.Centre, Anchor = Anchor.Centre, }; Add(starCounter); starsLabel = new OsuSpriteText { Origin = Anchor.Centre, Anchor = Anchor.Centre, Scale = new Vector2(2), Y = 50, }; Add(starsLabel); setStars(5); AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10); AddSliderStep("exact value", 0f, 10f, 5f, setStars); AddStep("stop animation", () => starCounter.StopAnimation()); AddStep("reset", () => setStars(0)); } private void setStars(float stars) { starCounter.Current = stars; starsLabel.Text = starCounter.Current.ToString("0.00"); } } } ```
8e7a81ac-ab7c-4d42-9107-ed176d4b555d
{ "language": "C#" }
```c# using System; using System.Runtime.InteropServices; using System.Resources; using System.IO; namespace Win32 { public static class Winmm { public static void PlayMessageNotify() { if (_soundData == null) { using (UnmanagedMemoryStream sound = Toxy.Properties.Resources.Blop) { _soundData = new byte[sound.Length]; sound.Read(_soundData, 0, (int)sound.Length); } } PlaySound(_soundData, IntPtr.Zero, SND_ASYNC | SND_MEMORY); } private static byte[] _soundData; private const UInt32 SND_ASYNC = 1; private const UInt32 SND_MEMORY = 4; [DllImport("Winmm.dll")] private static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags); } } ``` Check if _soundData is null before attempting to play the sound
```c# using System; using System.Runtime.InteropServices; using System.Resources; using System.IO; namespace Win32 { public static class Winmm { public static void PlayMessageNotify() { if (_soundData == null) { using (UnmanagedMemoryStream sound = Toxy.Properties.Resources.Blop) { _soundData = new byte[sound.Length]; sound.Read(_soundData, 0, (int)sound.Length); } } if (_soundData != null) { PlaySound(_soundData, IntPtr.Zero, SND_ASYNC | SND_MEMORY); } } private static byte[] _soundData; private const UInt32 SND_ASYNC = 1; private const UInt32 SND_MEMORY = 4; [DllImport("Winmm.dll")] private static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags); } } ```
1fe12fea-3081-486c-977b-9ab5acc3b737
{ "language": "C#" }
```c# using System; namespace Arkivverket.Arkade.Metadata { public static class MetsTranslationHelper { public static bool IsValidSystemType(string systemType) { // TODO: Use Enum ExternalModels.Mets.type (not ExternalModels.Info.type) when/if supported in built in mets schema return Enum.IsDefined(typeof(ExternalModels.Info.type), systemType); } public static bool IsSystemTypeNoark5(string systemType) { // TODO: Use Enum ExternalModels.Mets.type (not ExternalModels.Info.type) when/if supported in built in mets schema ExternalModels.Info.type enumSystemType; bool isParsableSystemType = Enum.TryParse(systemType, out enumSystemType); return isParsableSystemType && enumSystemType == ExternalModels.Info.type.Noark5; } } } ``` Use local definition of ArchiveTypes to validate metadata systemtypes
```c# using System; using Arkivverket.Arkade.Core; namespace Arkivverket.Arkade.Metadata { public static class MetsTranslationHelper { public static bool IsValidSystemType(string systemType) { return Enum.IsDefined(typeof(ArchiveType), systemType); } public static bool IsSystemTypeNoark5(string systemType) { ArchiveType archiveType; bool isParsableSystemType = Enum.TryParse(systemType, out archiveType); return isParsableSystemType && archiveType == ArchiveType.Noark5; } } } ```
2a08091f-7de7-4237-9f9d-a4f96adfef5a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ServiceModel; using PS.Mothership.Core.Common.Dto; namespace PS.Mothership.Core.Common.Contracts { [ServiceContract(Name = "DiallerService")] public interface IDiallerService { [OperationContract] ValidUserInfoDto ValidateUser(Guid userGuid, Guid mothershipSessionGuid); [OperationContract] Guid LogDiallerSessionSubscribe(DiallerSessionSubscribeDto diallerSessionSubscribe); [OperationContract] Guid LogDiallerSessionUnsubscribe(DiallerSessionUnsubscribeDto diallerSessionUnsubscribe); [OperationContract] SipAccountDetailsDto GetSipAccountDetails(Guid userGuid); [OperationContract(IsOneWay = true)] List<InboundQueueDetailsDto> GetInboundQueueDetails(); [OperationContract(IsOneWay = true)] List<MissingCallRecordingsDto> GetMissingCallRecordings(DateTime dateStart, DateTime dateEnd); [OperationContract] void UpdateRecorderCallIdForCallGuid(Guid callGuid, int recorderCallId, Guid userGuid); } } ``` Remove userGuid on ValidateUser method
```c# using System; using System.Collections.Generic; using System.ServiceModel; using PS.Mothership.Core.Common.Dto; namespace PS.Mothership.Core.Common.Contracts { [ServiceContract(Name = "DiallerService")] public interface IDiallerService { [OperationContract] ValidUserInfoDto ValidateUser(Guid mothershipSessionGuid); [OperationContract] Guid LogDiallerSessionSubscribe(DiallerSessionSubscribeDto diallerSessionSubscribe); [OperationContract] Guid LogDiallerSessionUnsubscribe(DiallerSessionUnsubscribeDto diallerSessionUnsubscribe); [OperationContract] SipAccountDetailsDto GetSipAccountDetails(Guid userGuid); [OperationContract(IsOneWay = true)] List<InboundQueueDetailsDto> GetInboundQueueDetails(); [OperationContract(IsOneWay = true)] List<MissingCallRecordingsDto> GetMissingCallRecordings(DateTime dateStart, DateTime dateEnd); [OperationContract] void UpdateRecorderCallIdForCallGuid(Guid callGuid, int recorderCallId, Guid userGuid); } } ```
d4380ca9-8768-4c34-8797-dd4a9cb4c9dd
{ "language": "C#" }
```c# using Elders.Cronus.Workflow; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.IO; using System.Threading.Tasks; namespace Elders.Cronus.MessageProcessing { /// <summary> /// Work-flow which gets an object from the passed context and calls a method 'Handle' passing execution.Context.Message' /// <see cref="HandlerContext"/> should have 'HandlerInstance' and 'Message' already set /// </summary> public class DynamicMessageHandle : Workflow<HandlerContext> { protected override Task RunAsync(Execution<HandlerContext> execution) { dynamic handler = execution.Context.HandlerInstance; return handler.HandleAsync((dynamic)execution.Context.Message); } } public class LogExceptionOnHandleError : Workflow<ErrorContext> { private static readonly ILogger logger = CronusLogger.CreateLogger(typeof(LogExceptionOnHandleError)); protected override async Task RunAsync(Execution<ErrorContext> execution) { var serializer = execution.Context.ServiceProvider.GetRequiredService<ISerializer>(); string messageContent = await MessageAsStringAsync(serializer, execution.Context.Message).ConfigureAwait(false); logger.ErrorException(execution.Context.Error, () => $"There was an error in {execution.Context.HandlerType.Name} while handling message {messageContent}"); } private Task<string> MessageAsStringAsync(ISerializer serializer, CronusMessage message) { using (var stream = new MemoryStream()) using (StreamReader reader = new StreamReader(stream)) { serializer.Serialize(stream, message); stream.Position = 0; return reader.ReadToEndAsync(); } } } } ``` Revert "fix: Uses async to log an error message"
```c# using Elders.Cronus.Workflow; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.IO; using System.Threading.Tasks; namespace Elders.Cronus.MessageProcessing { /// <summary> /// Work-flow which gets an object from the passed context and calls a method 'Handle' passing execution.Context.Message' /// <see cref="HandlerContext"/> should have 'HandlerInstance' and 'Message' already set /// </summary> public class DynamicMessageHandle : Workflow<HandlerContext> { protected override async Task RunAsync(Execution<HandlerContext> execution) { dynamic handler = execution.Context.HandlerInstance; await handler.HandleAsync((dynamic)execution.Context.Message); } } public class LogExceptionOnHandleError : Workflow<ErrorContext> { private static readonly ILogger logger = CronusLogger.CreateLogger(typeof(LogExceptionOnHandleError)); protected override Task RunAsync(Execution<ErrorContext> execution) { var serializer = execution.Context.ServiceProvider.GetRequiredService<ISerializer>(); logger.ErrorException(execution.Context.Error, () => $"There was an error in {execution.Context.HandlerType.Name} while handling message {MessageAsString(serializer, execution.Context.Message)}"); return Task.CompletedTask; } private string MessageAsString(ISerializer serializer, CronusMessage message) { using (var stream = new MemoryStream()) using (StreamReader reader = new StreamReader(stream)) { serializer.Serialize(stream, message); stream.Position = 0; return reader.ReadToEnd(); } } } } ```
594388e7-ca9d-4c5f-a805-94d59ad28d00
{ "language": "C#" }
```c# @model IEnumerable<GiveCRM.Models.Donation> @{ Layout = null; } <table> <tr> <th>Date</th><th>Amount</th> </tr> @foreach (var donation in Model) { <tr> <td>@donation.Date.ToLongDateString()</td> <td>@donation.Amount</td> </tr> } </table>``` Fix a niggle from the wiki: display donation amounts to two decimal places. Also format them as a currency, and respect the current culture.
```c# @using System.Globalization @model IEnumerable<GiveCRM.Models.Donation> @{ Layout = null; } <table> <tr> <th>Date</th><th>Amount</th> </tr> @foreach (var donation in Model) { <tr> <td>@donation.Date.ToLongDateString()</td> <td>@donation.Amount.ToString("C2", NumberFormatInfo.CurrentInfo)</td> </tr> } </table>```
71b62d44-1c0c-4e45-a6c5-621b79f85aed
{ "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 System.Collections.Generic; using System.Runtime.Serialization.Formatters.Tests; using Xunit; namespace System.Collections.ObjectModel.Tests { public partial class KeyedCollection_Serialization { public static IEnumerable<object[]> SerializeDeserialize_Roundtrips_MemberData() { yield return new object[] { new TestCollection() }; yield return new object[] { new TestCollection() { "hello" } }; yield return new object[] { new TestCollection() { "hello", "world" } }; } [ActiveIssue("https://github.com/dotnet/coreclr/pull/7966")] [Theory] [MemberData(nameof(SerializeDeserialize_Roundtrips_MemberData))] public void SerializeDeserialize_Roundtrips(TestCollection c) { TestCollection clone = BinaryFormatterHelpers.Clone(c); Assert.NotSame(c, clone); Assert.Equal(c, clone); } [Serializable] public sealed class TestCollection : KeyedCollection<string, string> { protected override string GetKeyForItem(string item) => item; } } } ``` Remove CoreCLR pull 6423, run msbuild System.ObjectModel.Tests.csproj /t:BuildAndTest, succeeded.
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Tests; using Xunit; namespace System.Collections.ObjectModel.Tests { public partial class KeyedCollection_Serialization { public static IEnumerable<object[]> SerializeDeserialize_Roundtrips_MemberData() { yield return new object[] { new TestCollection() }; yield return new object[] { new TestCollection() { "hello" } }; yield return new object[] { new TestCollection() { "hello", "world" } }; } [Theory] [MemberData(nameof(SerializeDeserialize_Roundtrips_MemberData))] public void SerializeDeserialize_Roundtrips(TestCollection c) { TestCollection clone = BinaryFormatterHelpers.Clone(c); Assert.NotSame(c, clone); Assert.Equal(c, clone); } [Serializable] public sealed class TestCollection : KeyedCollection<string, string> { protected override string GetKeyForItem(string item) => item; } } } ```
942f2aad-03c5-4098-afe5-5bc47e6e5981
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; namespace Contentful.Core.Models { /// <summary> /// Represents a single asset of a <see cref="Space"/>. /// </summary> public class Asset : IContentfulResource { /// <summary> /// Common system managed metadata properties. /// </summary> [JsonProperty("sys")] public SystemProperties SystemProperties { get; set; } /// <summary> /// The description of the asset. /// </summary> public string Description { get; set; } /// <summary> /// The title of the asset. /// </summary> public string Title { get; set; } /// <summary> /// Encapsulates information about the binary file of the asset. /// </summary> public File File { get; set; } /// <summary> /// The titles of the asset per locale. /// </summary> public Dictionary<string, string> TitleLocalized { get; set; } /// <summary> /// The descriptions of the asset per locale. /// </summary> public Dictionary<string, string> DescriptionLocalized { get; set; } /// <summary> /// Information about the file in respective language. /// </summary> [JsonProperty("file")] public Dictionary<string, File> FilesLocalized { get; set; } } } ``` Remove JsonProperty Mapping for "file"
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; namespace Contentful.Core.Models { /// <summary> /// Represents a single asset of a <see cref="Space"/>. /// </summary> public class Asset : IContentfulResource { /// <summary> /// Common system managed metadata properties. /// </summary> [JsonProperty("sys")] public SystemProperties SystemProperties { get; set; } /// <summary> /// The description of the asset. /// </summary> public string Description { get; set; } /// <summary> /// The title of the asset. /// </summary> public string Title { get; set; } /// <summary> /// Encapsulates information about the binary file of the asset. /// </summary> public File File { get; set; } /// <summary> /// The titles of the asset per locale. /// </summary> public Dictionary<string, string> TitleLocalized { get; set; } /// <summary> /// The descriptions of the asset per locale. /// </summary> public Dictionary<string, string> DescriptionLocalized { get; set; } /// <summary> /// Information about the file in respective language. /// </summary> public Dictionary<string, File> FilesLocalized { get; set; } } } ```
c84f2f4f-7565-4b57-9cec-c54fb303f2d4
{ "language": "C#" }
```c# namespace CypherTwo.Core { using System; using System.Linq; using System.Threading.Tasks; public class NeoClient : INeoClient { private readonly ISendRestCommandsToNeo neoApi; public NeoClient(string baseUrl) : this(new ApiClientFactory(baseUrl, new JsonHttpClientWrapper())) { } internal NeoClient(ISendRestCommandsToNeo neoApi) { this.neoApi = neoApi; } public async Task InitialiseAsync() { try { await this.neoApi.LoadServiceRootAsync(); } catch (Exception ex) { throw new InvalidOperationException(ex.Message); } } public async Task<ICypherDataReader> QueryAsync(string cypher) { var neoResponse = await this.neoApi.SendCommandAsync(cypher); if (neoResponse.errors != null && neoResponse.errors.Any()) { throw new Exception(string.Join(Environment.NewLine, neoResponse.errors.Select(error => error.ToObject<string>()))); } return new CypherDataReader(neoResponse); } public async Task ExecuteAsync(string cypher) { await this.neoApi.SendCommandAsync(cypher); } } }``` Add throw error on Neo exception in ExecuteCore
```c# namespace CypherTwo.Core { using System; using System.Linq; using System.Threading.Tasks; public class NeoClient : INeoClient { private readonly ISendRestCommandsToNeo neoApi; public NeoClient(string baseUrl) : this(new ApiClientFactory(baseUrl, new JsonHttpClientWrapper())) { } internal NeoClient(ISendRestCommandsToNeo neoApi) { this.neoApi = neoApi; } public async Task InitialiseAsync() { try { await this.neoApi.LoadServiceRootAsync(); } catch (Exception ex) { throw new InvalidOperationException(ex.Message); } } public async Task<ICypherDataReader> QueryAsync(string cypher) { var neoResponse = await this.ExecuteCore(cypher); return new CypherDataReader(neoResponse); } public async Task ExecuteAsync(string cypher) { await this.ExecuteCore(cypher); } private async Task<NeoResponse> ExecuteCore(string cypher) { var neoResponse = await this.neoApi.SendCommandAsync(cypher); if (neoResponse.errors != null && neoResponse.errors.Any()) { throw new Exception(string.Join(Environment.NewLine, neoResponse.errors.Select(error => error.ToObject<string>()))); } return neoResponse; } } }```
6b1efa97-a787-4da5-9db5-4e2439479b7a
{ "language": "C#" }
```c# using System; namespace Hangman { public class Hangman { public static void Main(string[] args) { Table table = new Table(2, 3); string output = table.Draw(); Console.WriteLine(output); } } } ``` Comment out the code in Hangman that uses Table
```c# using System; namespace Hangman { public class Hangman { public static void Main(string[] args) { // Table table = new Table(2, 3); // string output = table.Draw(); // Console.WriteLine(output); } } } ```
b008280a-3e7f-4756-91a8-cb30b3b335d7
{ "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.Threading.Tasks; namespace osu.Game.Online.RealtimeMultiplayer { /// <summary> /// An interface defining a spectator client instance. /// </summary> public interface IMultiplayerClient { /// <summary> /// Signals that the room has changed state. /// </summary> /// <param name="state">The state of the room.</param> Task RoomStateChanged(MultiplayerRoomState state); /// <summary> /// Signals that a user has joined the room. /// </summary> /// <param name="user">The user.</param> Task UserJoined(MultiplayerRoomUser user); /// <summary> /// Signals that a user has left the room. /// </summary> /// <param name="user">The user.</param> Task UserLeft(MultiplayerRoomUser user); /// <summary> /// Signals that the settings for this room have changed. /// </summary> /// <param name="newSettings">The updated room settings.</param> Task SettingsChanged(MultiplayerRoomSettings newSettings); } } ``` Add client method for notifying about host changes
```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.Threading.Tasks; namespace osu.Game.Online.RealtimeMultiplayer { /// <summary> /// An interface defining a spectator client instance. /// </summary> public interface IMultiplayerClient { /// <summary> /// Signals that the room has changed state. /// </summary> /// <param name="state">The state of the room.</param> Task RoomStateChanged(MultiplayerRoomState state); /// <summary> /// Signals that a user has joined the room. /// </summary> /// <param name="user">The user.</param> Task UserJoined(MultiplayerRoomUser user); /// <summary> /// Signals that a user has left the room. /// </summary> /// <param name="user">The user.</param> Task UserLeft(MultiplayerRoomUser user); /// <summary> /// Signal that the host of the room has changed. /// </summary> /// <param name="userId">The user ID of the new host.</param> Task HostChanged(long userId); /// <summary> /// Signals that the settings for this room have changed. /// </summary> /// <param name="newSettings">The updated room settings.</param> Task SettingsChanged(MultiplayerRoomSettings newSettings); } } ```
52e2a779-9b09-4e03-bf2d-bccf9b800f9a
{ "language": "C#" }
```c# using System; using System.Threading; using Microsoft.SPOT; namespace AgentIntervals { public delegate void HeartBeatEventHandler(object sender, EventArgs e); public class HeartBeat { private Timer _timer; private int _period; public event HeartBeatEventHandler OnHeartBeat; public HeartBeat(int period) { _period = period; } private void TimerCallback(object state) { if (OnHeartBeat != null) { OnHeartBeat(this, new EventArgs()); } } public void Start(int delay) { if (_timer != null) return; _timer = new Timer(TimerCallback, null, delay, _period); } public void Stop() { if (_timer == null) return; _timer.Dispose(); _timer = null; } public bool Toggle(int delay) { bool started; if (_timer == null) { Start(delay); started = true; } else { Stop(); started = false; } return started; } public void Reset() { Stop(); Start(0); } public void ChangePeriod(int newPeriod) { _period = newPeriod; } } } ``` Add parameter-less defaults for Start, Toggle, Reset.
```c# using System; using System.Threading; using Microsoft.SPOT; namespace AgentIntervals { public delegate void HeartBeatEventHandler(object sender, EventArgs e); public class HeartBeat { private Timer _timer; private int _period; public event HeartBeatEventHandler OnHeartBeat; public HeartBeat(int period) { _period = period; } private void TimerCallback(object state) { if (OnHeartBeat != null) { OnHeartBeat(this, new EventArgs()); } } public void Start() { Start(0); } public void Start(int delay) { if (_timer != null) return; _timer = new Timer(TimerCallback, null, delay, _period); } public void Stop() { if (_timer == null) return; _timer.Dispose(); _timer = null; } public bool Toggle() { return Toggle(0); } public bool Toggle(int delay) { bool started; if (_timer == null) { Start(delay); started = true; } else { Stop(); started = false; } return started; } public void Reset() { Reset(0); } public void Reset(int delay) { Stop(); Start(delay); } public void ChangePeriod(int newPeriod) { _period = newPeriod; } } } ```
893554b8-f420-4938-8dca-ed9cb166d18c
{ "language": "C#" }
```c# using System; using System.Linq; namespace FibCSharp { class Program { static void Main(string[] args) { var max = 50; Enumerable.Range(0, int.MaxValue) .Select(Fib) .TakeWhile(x => x <= 50) .ToList() .ForEach(Console.WriteLine); } static int Fib(int arg) => arg == 0 ? 0 : arg == 1 ? 1 : Fib(arg - 2) + Fib(arg - 1); } } ``` Use the defined max value
```c# using System; using System.Linq; namespace FibCSharp { class Program { static void Main(string[] args) { var max = 50; Enumerable.Range(0, int.MaxValue) .Select(Fib) .TakeWhile(x => x <= max) .ToList() .ForEach(Console.WriteLine); } static int Fib(int arg) => arg == 0 ? 0 : arg == 1 ? 1 : Fib(arg - 2) + Fib(arg - 1); } } ```
6c0c0a78-004b-4c38-9274-0f8c1035cd65
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace IvionSoft { public class History<T> { int length; HashSet<T> hashes; Queue<T> queue; object _locker; public History(int length) { if (length < 1) throw new ArgumentException("Must be 1 or larger", "length"); this.length = length; hashes = new HashSet<T>(); queue = new Queue<T>(length + 1); _locker = new object(); } public bool Contains(T item) { return hashes.Contains(item); } public bool Add(T item) { bool added; lock (_locker) { added = hashes.Add(item); if (added) { queue.Enqueue(item); if (queue.Count > length) { T toRemove = queue.Dequeue(); hashes.Remove(toRemove); } } } return added; } } }``` Add the option of specifying a comparer.
```c# using System; using System.Collections.Generic; namespace IvionSoft { public class History<T> { public int Length { get; private set; } HashSet<T> hashes; Queue<T> queue; object _locker = new object(); public History(int length) : this(length, null) {} public History(int length, IEqualityComparer<T> comparer) { if (length < 1) throw new ArgumentException("Must be 1 or larger", "length"); Length = length; queue = new Queue<T>(length + 1); if (comparer != null) hashes = new HashSet<T>(comparer); else hashes = new HashSet<T>(); } public bool Contains(T item) { return hashes.Contains(item); } public bool Add(T item) { bool added; lock (_locker) { added = hashes.Add(item); if (added) { queue.Enqueue(item); if (queue.Count > Length) { T toRemove = queue.Dequeue(); hashes.Remove(toRemove); } } } return added; } } }```
ff2d959f-b8bc-45ec-a33f-0a45d4c26f1f
{ "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.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osuTK.Graphics; namespace osu.Game.Screens.OnlinePlay.Lounge.Components { public class RoomSpecialCategoryPill : OnlinePlayComposite { private SpriteText text; public RoomSpecialCategoryPill() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(OsuColour colours) { InternalChild = new PillContainer { Background = { Colour = colours.Pink, Alpha = 1 }, Child = text = new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, Font = OsuFont.GetFont(weight: FontWeight.SemiBold, size: 12), Colour = Color4.Black } }; } protected override void LoadComplete() { base.LoadComplete(); Category.BindValueChanged(c => text.Text = c.NewValue.ToString(), true); } } } ``` Update colour of spotlights playlist to match new specs
```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.Framework.Allocation; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Online.Rooms; using osuTK.Graphics; namespace osu.Game.Screens.OnlinePlay.Lounge.Components { public class RoomSpecialCategoryPill : OnlinePlayComposite { private SpriteText text; private PillContainer pill; [Resolved] private OsuColour colours { get; set; } public RoomSpecialCategoryPill() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { InternalChild = pill = new PillContainer { Background = { Colour = colours.Pink, Alpha = 1 }, Child = text = new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, Font = OsuFont.GetFont(weight: FontWeight.SemiBold, size: 12), Colour = Color4.Black } }; } protected override void LoadComplete() { base.LoadComplete(); Category.BindValueChanged(c => { text.Text = c.NewValue.GetLocalisableDescription(); switch (c.NewValue) { case RoomCategory.Spotlight: pill.Background.Colour = colours.Green2; break; case RoomCategory.FeaturedArtist: pill.Background.Colour = colours.Blue2; break; } }, true); } } } ```
ed81a2c3-e7dd-4c55-80c9-7e7d0162bc00
{ "language": "C#" }
```c# namespace PegSharp.External { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class BlockChain { private List<BlockData> blocks = new List<BlockData>(); private List<BlockData> others = new List<BlockData>(); public long Height { get { return blocks.Count; } } public BlockData BestBlock { get { return this.blocks.Last(); } } public bool Add(BlockData block) { if ((this.blocks.Count == 0 && block.Number == 0) || (this.blocks.Count > 0 && this.BestBlock.Hash.Equals(block.ParentHash))) { this.blocks.Add(block); var children = this.others.Where(b => b.ParentHash.Equals(block.Hash)); foreach (var child in children) { this.others.Remove(child); this.Add(child); } return true; } others.Add(block); return false; } } } ``` Add blocks not in order
```c# namespace PegSharp.External { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class BlockChain { private List<BlockData> blocks = new List<BlockData>(); private List<BlockData> others = new List<BlockData>(); public long Height { get { return blocks.Count; } } public BlockData BestBlock { get { return this.blocks.Last(); } } public bool Add(BlockData block) { if ((this.blocks.Count == 0 && block.Number == 0) || (this.blocks.Count > 0 && this.BestBlock.Hash.Equals(block.ParentHash))) { this.blocks.Add(block); var children = this.others.Where(b => b.ParentHash.Equals(block.Hash)).ToList(); foreach (var child in children) { this.others.Remove(child); this.Add(child); } return true; } others.Add(block); return false; } } } ```
31611199-684c-4bae-a62d-d1ec2959f8d8
{ "language": "C#" }
```c# using System; namespace BitCommitment { /// <summary> /// A class to perform bit commitment. It does not care what the input is; it's just a /// facility for exchanging bit commitment messages. /// </summary> public class BitCommitmentEngine { #region properties public byte[] BobRandBytesR { get; set; } public byte[] AliceEncryptedMessage { get; set; } #endregion } } ``` Use one way function protocol for bit commitment
```c# using System; namespace BitCommitment { /// <summary> /// A class to perform bit commitment. It does not care what the input is; it's just a /// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way /// function method for committing bits /// </summary> public class BitCommitmentEngine { public byte[] AliceRandBytes1 { get; set; } public byte[] AliceRandBytes2 { get; set; } public byte[] AliceMessageBytesBytes { get; set; } public BitCommitmentEngine(byte[] one, byte[] two, byte[] messageBytes) { AliceRandBytes1 = one; AliceRandBytes2 = two; AliceMessageBytesBytes = messageBytes; } } } ```
14be6c52-798b-45da-bf72-f269fa04c98d
{ "language": "C#" }
```c# /* * Created by SharpDevelop. * User: Lars Magnus * Date: 12.06.2014 * Time: 20:54 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Text; using Nancy; using SubmittedData; namespace Modules { /// <summary> /// Description of WebService. /// </summary> public class RootMenuModule : NancyModule { private ITournament _tournament; public RootMenuModule(ITournament tournament) { _tournament = tournament; var groups = new Groups() { Tournament = _tournament.GetName() }; Get["/"] = _ => { return View["groups.sshtml", groups]; }; } private string PrintGroups() { StringBuilder s = new StringBuilder(); s.AppendFormat("Welcome to {0} betting scores\n", _tournament.GetName()); char gn = 'A'; foreach (object[] group in _tournament.GetGroups()) { s.AppendLine("Group " + gn); foreach (var team in group) { s.AppendLine(team.ToString()); } gn++; } return s.ToString(); } } class Groups { public string Tournament { get; set; } } } ``` Make a proper view model
```c# /* * Created by SharpDevelop. * User: Lars Magnus * Date: 12.06.2014 * Time: 20:54 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Text; using Nancy; using SubmittedData; namespace Modules { /// <summary> /// Description of WebService. /// </summary> public class RootMenuModule : NancyModule { public RootMenuModule(ITournament tournament) { Get["/"] = _ => { return View["groups.sshtml", new GroupsViewModel(tournament)]; }; } } public class GroupsViewModel { public string Tournament { get { return _tournament.GetName(); } } ITournament _tournament; public GroupsViewModel(ITournament t) { _tournament = t; } private string PrintGroups() { StringBuilder s = new StringBuilder(); s.AppendFormat("Welcome to {0} betting scores\n", _tournament.GetName()); char gn = 'A'; foreach (object[] group in _tournament.GetGroups()) { s.AppendLine("Group " + gn); foreach (var team in group) { s.AppendLine(team.ToString()); } gn++; } return s.ToString(); } } } ```
9c16baac-d4e0-4d26-9e68-140026880139
{ "language": "C#" }
```c# using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("Intro Settings")] public class IntroData { [DisplayName("Duration")] public int Duration { get; set; } = -1; [DisplayName("Reversable")] public bool Reversable { get; set; } = false; [DisplayName("Activate")] public bool Activate { get; set; } = false; [DisplayName("Hide On Finish")] public bool HideOnFinish { get; set; } = true; [DisplayName("Execute Finish Action")] public bool ExecuteFinishAction { get; set; } = true; } }``` Change some intro settings property names
```c# using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("Intro Settings")] public class IntroData { [DisplayName("Duration")] public int Duration { get; set; } = -1; [DisplayName("Reversable")] public bool Reversable { get; set; } = false; [DisplayName("Activate")] public bool Activate { get; set; } = false; [DisplayName("Hide On End")] public bool HideOnFinish { get; set; } = true; [DisplayName("Trigger End Event")] public bool ExecuteFinishAction { get; set; } = true; } }```
51043eff-0972-4844-8cf8-7aa5d01799d2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using Microsoft.AspNet.SignalR; namespace SignalRDemo.Hubs { public class Chat : Hub { public void SayHello() { while (true) { Clients.All.addMessage("Date time : "+DateTime.Now); Thread.Sleep(500); } } } }``` Use timer rather than blocking sleep
```c# using System; using System.Collections.Generic; using System.Linq; using System.Timers; using System.Web; using Microsoft.AspNet.SignalR; using Timer = System.Timers.Timer; namespace SignalRDemo.Hubs { public class Chat : Hub { static string messageToSend = DateTime.Now.ToString(); Timer t = new Timer(500); public void SayHello() { t.Elapsed +=t_Elapsed; t.Start(); } private void t_Elapsed(object sender, ElapsedEventArgs e) { Clients.All.addMessage("Date time : " + messageToSend); messageToSend = DateTime.Now.ToString(); } } }```
2d407fd1-27a5-4b2e-8a4f-451b2030fefa
{ "language": "C#" }
```c# using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class EmbedsController : ApiController { public EmbedsController(Database db) : base(db) { // Nothing to do here } [HttpGet] public IEnumerable<Embed> List() { return db.Embeds.ToList(); } [HttpPost] public async Task<IActionResult> Create([FromBody]Embed embed) { db.Embeds.Add(embed); await db.SaveChangesAsync(); return Ok(); } [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { var embed = await db.Embeds.SingleOrDefaultAsync(_ => _.Id == id); db.Embeds.Remove(embed); await db.SaveChangesAsync(); return Ok(); } } }``` Switch to not serialize the full embed object
```c# using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { public class EmbedsController : ApiController { public EmbedsController(Database db) : base(db) { // Nothing to do here } [HttpGet] public async Task<IEnumerable<dynamic>> List() { return await db .Embeds .Select(embed => new { embed.Id, embed.UnitId, embed.Name, embed.Route, embed.Source }) .ToListAsync(); } [HttpPost] public async Task<IActionResult> Create([FromBody]Embed embed) { db.Embeds.Add(embed); await db.SaveChangesAsync(); return Ok(); } [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { var embed = await db.Embeds.SingleOrDefaultAsync(_ => _.Id == id); db.Embeds.Remove(embed); await db.SaveChangesAsync(); return Ok(); } } }```
d5e682a0-0e41-4c04-be66-c0f79675d4eb
{ "language": "C#" }
```c# using Roguelike.UI; using System; namespace Roguelike.Entities.Components { public class FighterComponent : Component { public int MaximumHealth { get; set; } public int CurrentHealth { get; set; } public int Power { get; set; } public int Defense { get; set; } public Action<Entity> DeathFunction { get; set; } public void Damage(int amount) { CurrentHealth -= amount; if (CurrentHealth <= 0) { DeathFunction?.Invoke(Entity); } } public void Attack(Entity target) { if (target.GetComponent<FighterComponent>() == null) { return; } var damage = Power - target.GetComponent<FighterComponent>().Defense; if (damage > 0) { MessageLog.Add($"{Entity.Name} attacks {target.Name} for {damage} HP."); target.GetComponent<FighterComponent>().Damage(damage); } else { MessageLog.Add($"{Entity.Name} attacks {target.Name} but it has no effect!"); } } } } ``` Add a 5% chance for attacks to be critical hits, which ignore defense.
```c# using Roguelike.UI; using System; namespace Roguelike.Entities.Components { public class FighterComponent : Component { public const float CriticalHitChance = 0.05f; public int MaximumHealth { get; set; } public int CurrentHealth { get; set; } public int Power { get; set; } public int Defense { get; set; } public Action<Entity> DeathFunction { get; set; } public void Damage(int amount) { CurrentHealth -= amount; if (CurrentHealth <= 0) { DeathFunction?.Invoke(Entity); } } public void Attack(Entity target) { if (target.GetComponent<FighterComponent>() == null) { return; } int damage = 0; if (Program.Random.NextDouble() < CriticalHitChance) { damage = Power; } else { damage = Power - target.GetComponent<FighterComponent>().Defense; } if (damage > 0) { MessageLog.Add($"{Entity.Name} attacks {target.Name} for {damage} HP."); target.GetComponent<FighterComponent>().Damage(damage); } else { MessageLog.Add($"{Entity.Name} attacks {target.Name} but it has no effect!"); } } } } ```
7d2483d1-32ed-4c52-8430-e4cec2ec4fba
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeFirstMigrations { public class Address { public Int32 Id { get; set; } public Int32 HouseNumber { get; set; } public String Street { get; set; } public String City { get; set; } } } ``` Change model and EF errors with schema change
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeFirstMigrations { public class Address { public Int32 Id { get; set; } public Int32 HouseNumber { get; set; } public String Street { get; set; } public String City { get; set; } public String Postcode { get; set; } } } ```
f4cb04e6-1acc-42ed-9efb-d3560bbbda58
{ "language": "C#" }
```c# using BSParser.Data; using CsvHelper; using System.IO; using System.Text; namespace BSParser.Writers { public class StrictCSVWriter : Writer { private string _fileName; public StrictCSVWriter(string fileName) { _fileName = fileName; } public override bool Write(StatementTable data) { using (var sw = new StreamWriter(_fileName, false, Encoding.UTF8)) { var csv = new CsvWriter(sw); csv.Configuration.Delimiter = ";"; csv.WriteRecords(data); } return true; } } } ``` Change the order of the columns in CSV export
```c# using BSParser.Data; using CsvHelper; using System.IO; using System.Linq; using System.Text; namespace BSParser.Writers { public class StrictCSVWriter : Writer { private string _fileName; public StrictCSVWriter(string fileName) { _fileName = fileName; } public override bool Write(StatementTable data) { if (!data.Any()) return false; var orderedData = data.Select(x => new { x.Category, x.RefNum, x.DocNum, x.Amount, x.Direction, x.RegisteredOn, x.Description, x.PayerINN, x.PayerName, x.ReceiverINN, x.ReceiverName }); using (var sw = new StreamWriter(_fileName, false, Encoding.UTF8)) { var csv = new CsvWriter(sw); csv.Configuration.Delimiter = ";"; csv.WriteRecords(orderedData); } return true; } } } ```
bbc2875a-437c-41fa-beeb-d466cc333f30
{ "language": "C#" }
```c# using CompatApiClient.Utils; using DSharpPlus.Entities; using IrdLibraryClient; using IrdLibraryClient.POCOs; namespace CompatBot.Utils.ResultFormatters { public static class IrdSearchResultFormattercs { public static DiscordEmbedBuilder AsEmbed(this SearchResult searchResult) { var result = new DiscordEmbedBuilder { //Title = "IRD Library Search Result", Color = Config.Colors.DownloadLinks, }; if (searchResult.Data.Count == 0) { result.Color = Config.Colors.LogResultFailed; result.Description = "No matches were found"; return result; } foreach (var item in searchResult.Data) { var parts = item.Filename?.Split('-'); if (parts == null) parts = new string[] {null, null}; else if (parts.Length == 1) parts = new[] {null, item.Filename}; result.AddField( $"[{parts?[0]}] {item.Title?.Sanitize().Trim(EmbedPager.MaxFieldTitleLength)}", $"⏬ [`{parts[1]?.Sanitize().Trim(200)}`]({IrdClient.GetDownloadLink(item.Filename)}) ℹ [Info]({IrdClient.GetInfoLink(item.Filename)})" ); } return result; } } } ``` Add game version to the results (for e.g. heavy rain)
```c# using CompatApiClient.Utils; using DSharpPlus.Entities; using IrdLibraryClient; using IrdLibraryClient.POCOs; namespace CompatBot.Utils.ResultFormatters { public static class IrdSearchResultFormattercs { public static DiscordEmbedBuilder AsEmbed(this SearchResult searchResult) { var result = new DiscordEmbedBuilder { //Title = "IRD Library Search Result", Color = Config.Colors.DownloadLinks, }; if (searchResult.Data.Count == 0) { result.Color = Config.Colors.LogResultFailed; result.Description = "No matches were found"; return result; } foreach (var item in searchResult.Data) { var parts = item.Filename?.Split('-'); if (parts == null) parts = new string[] {null, null}; else if (parts.Length == 1) parts = new[] {null, item.Filename}; result.AddField( $"[{parts?[0]} v{item.GameVersion}] {item.Title?.Sanitize().Trim(EmbedPager.MaxFieldTitleLength)}", $"⏬ [`{parts[1]?.Sanitize().Trim(200)}`]({IrdClient.GetDownloadLink(item.Filename)}) ℹ [Info]({IrdClient.GetInfoLink(item.Filename)})" ); } return result; } } } ```
c859e7a4-9fd9-438b-8ee9-8dc59dc95fee
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Livraria; namespace LivrariaTest { [TestClass] public class AutorTest { [TestMethod] public void TestProperties() { Autor autor = new Autor(); autor.CodAutor = 999; autor.Nome = "George R. R. Martin"; autor.Cpf = "012.345.678.90"; autor.DtNascimento = new DateTime(1948, 9, 20); Assert.AreEqual(autor.CodAutor, 999); Assert.AreEqual(autor.Nome, "George R. R. Martin"); Assert.AreEqual(autor.Cpf, "012.345.678.90"); Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20)); } } } ``` Add test for ListaAutores method
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Livraria; using System.Collections.Generic; namespace LivrariaTest { [TestClass] public class AutorTest { [TestMethod] public void TestProperties() { Autor autor = new Autor(); autor.CodAutor = 999; autor.Nome = "George R. R. Martin"; autor.Cpf = "012.345.678.90"; autor.DtNascimento = new DateTime(1948, 9, 20); Assert.AreEqual(autor.CodAutor, 999); Assert.AreEqual(autor.Nome, "George R. R. Martin"); Assert.AreEqual(autor.Cpf, "012.345.678.90"); Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20)); } [TestMethod] public void TestListaAutores() { Autor autor = new Autor(); List<Autor> lstAutores = autor.ListaAutores(); foreach (var aut in lstAutores) { Assert.IsInstanceOfType(aut, typeof(Autor)); } } } } ```
3d405aba-efd3-4be6-9935-115424278de1
{ "language": "C#" }
```c# using System; class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); foreach (var arg in args) { Console.Write("Hello "); Console.Write(arg); Console.WriteLine("!"); } Console.WriteLine("Press ENTER to exit ..."); Console.ReadLine(); } } ``` Make coding style consistent with corefx
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; internal class Program { private static void Main(string[] args) { Console.WriteLine("Hello World!"); foreach (var arg in args) { Console.Write("Hello "); Console.Write(arg); Console.WriteLine("!"); } Console.WriteLine("Press ENTER to exit ..."); Console.ReadLine(); } }```
7cb9b003-4562-408c-85be-66be8e5d128d
{ "language": "C#" }
```c# // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEditor; using System.Collections; using System.Reflection; namespace TiltBrushToolkit { [InitializeOnLoad] public class GammaSettings : EditorWindow { static ColorSpace m_LastColorSpace; static GammaSettings() { EditorApplication.update += OnUpdate; SetKeywords(); m_LastColorSpace = PlayerSettings.colorSpace; } static void OnUpdate() { if (m_LastColorSpace != PlayerSettings.colorSpace) { SetKeywords(); m_LastColorSpace = PlayerSettings.colorSpace; } } static void SetKeywords() { bool linear = PlayerSettings.colorSpace == ColorSpace.Linear; if (linear) { Shader.DisableKeyword("FORCE_SRGB"); } else { Shader.EnableKeyword("FORCE_SRGB"); } } } }``` Use correct TBT_LINEAR_TARGET shader feature keyword.
```c# // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEditor; using System.Collections; using System.Reflection; namespace TiltBrushToolkit { [InitializeOnLoad] public class GammaSettings : EditorWindow { static ColorSpace m_LastColorSpace; static GammaSettings() { EditorApplication.update += OnUpdate; SetKeywords(); m_LastColorSpace = PlayerSettings.colorSpace; } static void OnUpdate() { if (m_LastColorSpace != PlayerSettings.colorSpace) { SetKeywords(); m_LastColorSpace = PlayerSettings.colorSpace; } } static void SetKeywords() { bool linear = PlayerSettings.colorSpace == ColorSpace.Linear; if (linear) { Shader.EnableKeyword("TBT_LINEAR_TARGET"); } else { Shader.DisableKeyword("TBT_LINEAR_TARGET"); } } } }```
9ea49385-00c6-4bf9-a08f-d6741a180d1f
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using ManagedBass; using System; using System.Collections.Concurrent; namespace osu.Framework.Audio.Sample { internal class SampleBass : Sample, IBassAudio { private volatile int sampleId; public override bool IsLoaded => sampleId != 0; public SampleBass(byte[] data, ConcurrentQueue<Action> customPendingActions = null) { if (customPendingActions != null) PendingActions = customPendingActions; PendingActions.Enqueue(() => { sampleId = Bass.SampleLoad(data, 0, data.Length, 8, BassFlags.Default); }); } protected override void Dispose(bool disposing) { Bass.SampleFree(sampleId); base.Dispose(disposing); } void IBassAudio.UpdateDevice(int deviceIndex) { if (IsLoaded) // counter-intuitively, this is the correct API to use to migrate a sample to a new device. Bass.ChannelSetDevice(sampleId, deviceIndex); } public int CreateChannel() => Bass.SampleGetChannel(sampleId); } } ``` Allow bass sample channels to overwrite older ones by default.
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using ManagedBass; using System; using System.Collections.Concurrent; namespace osu.Framework.Audio.Sample { internal class SampleBass : Sample, IBassAudio { private volatile int sampleId; public override bool IsLoaded => sampleId != 0; public SampleBass(byte[] data, ConcurrentQueue<Action> customPendingActions = null) { if (customPendingActions != null) PendingActions = customPendingActions; PendingActions.Enqueue(() => { sampleId = Bass.SampleLoad(data, 0, data.Length, 8, BassFlags.Default | BassFlags.SampleOverrideLongestPlaying); }); } protected override void Dispose(bool disposing) { Bass.SampleFree(sampleId); base.Dispose(disposing); } void IBassAudio.UpdateDevice(int deviceIndex) { if (IsLoaded) // counter-intuitively, this is the correct API to use to migrate a sample to a new device. Bass.ChannelSetDevice(sampleId, deviceIndex); } public int CreateChannel() => Bass.SampleGetChannel(sampleId); } } ```
62df9761-a065-4598-a10f-b4fad135b5db
{ "language": "C#" }
```c# using Microsoft.AspNetCore.SignalR; using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti; using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti; using System; using System.Threading.Tasks; namespace SO115App.SignalR.Sender.GestioneUtenti { public class NotificationDeleteUtente : INotifyDeleteUtente { private readonly IHubContext<NotificationHub> _notificationHubContext; private readonly IGetUtenteByCF _getUtenteByCF; public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF) { _notificationHubContext = notificationHubContext; _getUtenteByCF = getUtenteByCF; } public async Task Notify(DeleteUtenteCommand command) { var utente = _getUtenteByCF.Get(command.CodFiscale); await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true); await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true); await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id); } } } ``` Fix - Modificata notifica delete utente
```c# using Microsoft.AspNetCore.SignalR; using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti; using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti; using System; using System.Threading.Tasks; namespace SO115App.SignalR.Sender.GestioneUtenti { public class NotificationDeleteUtente : INotifyDeleteUtente { private readonly IHubContext<NotificationHub> _notificationHubContext; private readonly IGetUtenteByCF _getUtenteByCF; public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF) { _notificationHubContext = notificationHubContext; _getUtenteByCF = getUtenteByCF; } public async Task Notify(DeleteUtenteCommand command) { var utente = _getUtenteByCF.Get(command.CodFiscale); //await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true); //await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true); await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id); } } } ```
e2fc3210-3aaa-42a7-9922-eac30dffe507
{ "language": "C#" }
```c# // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Wangkanai.Detection.Hosting { public class ResponsivePageLocationExpander : IViewLocationExpander { private const string ValueKey = "device"; public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { context.Values.TryGetValue(ValueKey, out var device); if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor)) return viewLocations; if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device)) return viewLocations; var expandLocations = ExpandPageHierarchy().ToList(); return expandLocations; IEnumerable<string> ExpandPageHierarchy() { foreach (var location in viewLocations) { if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/")) { yield return location; continue; } yield return location.Replace("{0}", "{0}." + device); yield return location; } } } public void PopulateValues(ViewLocationExpanderContext context) { context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower(); } } }``` Add explanation of why having 2 yield return
```c# // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Wangkanai.Detection.Hosting { public class ResponsivePageLocationExpander : IViewLocationExpander { private const string ValueKey = "device"; public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { context.Values.TryGetValue(ValueKey, out var device); if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor)) return viewLocations; if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device)) return viewLocations; var expandLocations = ExpandPageHierarchy().ToList(); return expandLocations; IEnumerable<string> ExpandPageHierarchy() { foreach (var location in viewLocations) { if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/")) { yield return location; continue; } // Device View if exist on disk yield return location.Replace("{0}", "{0}." + device); // Fallback to the original default view yield return location; } } } public void PopulateValues(ViewLocationExpanderContext context) { context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower(); } } }```
85dd64dd-5f20-4fa4-aafa-71827a6db8ce
{ "language": "C#" }
```c# namespace BatteryCommander.Web { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; 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(); } private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369") .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(); }); } } ``` Remove Seq compact flag, default now
```c# namespace BatteryCommander.Web { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; 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(); } private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369") .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(); }); } } ```
ec823bbb-ff1d-4c59-aba6-45f7572be59b
{ "language": "C#" }
```c# using System; using System.Data; using System.Text.Json; using Dapper; namespace Dommel.Json { internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler { private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, }; public void SetValue(IDbDataParameter parameter, object? value) { parameter.Value = value is null || value is DBNull ? (object)DBNull.Value : JsonSerializer.Serialize(value, JsonOptions); parameter.DbType = DbType.String; } public object? Parse(Type destinationType, object? value) => value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null; } } ``` Allow reading numbers from strings in JSON
```c# using System; using System.Data; using System.Text.Json; using System.Text.Json.Serialization; using Dapper; namespace Dommel.Json { internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler { private static readonly JsonSerializerOptions JsonOptions = new() { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, NumberHandling = JsonNumberHandling.AllowReadingFromString, }; public void SetValue(IDbDataParameter parameter, object? value) { parameter.Value = value is null || value is DBNull ? DBNull.Value : JsonSerializer.Serialize(value, JsonOptions); parameter.DbType = DbType.String; } public object? Parse(Type destinationType, object? value) => value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null; } } ```
fc597278-a0cc-4826-9455-9e4699a371bd
{ "language": "C#" }
```c# using System.Text; namespace TweetDck.Plugins{ static class PluginScriptGenerator{ public static string GenerateConfig(PluginConfig config){ return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty; } public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150); build.Append("(function(").Append(environment.GetScriptVariables()).Append("){"); build.Append("let tmp={"); build.Append("id:\"").Append(pluginIdentifier).Append("\","); build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}"); build.Append("});"); build.Append("tmp.obj.$token=").Append(pluginToken).Append(";"); build.Append("window.TD_PLUGINS.install(tmp);"); build.Append("})(").Append(environment.GetScriptVariables()).Append(");"); return build.ToString(); } } } ``` Fix plugin script generator causing JS syntax error
```c# using System.Text; namespace TweetDck.Plugins{ static class PluginScriptGenerator{ public static string GenerateConfig(PluginConfig config){ return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty; } public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150); build.Append("(function(").Append(environment.GetScriptVariables()).Append("){"); build.Append("let tmp={"); build.Append("id:\"").Append(pluginIdentifier).Append("\","); build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}"); build.Append("};"); build.Append("tmp.obj.$token=").Append(pluginToken).Append(";"); build.Append("window.TD_PLUGINS.install(tmp);"); build.Append("})(").Append(environment.GetScriptVariables()).Append(");"); return build.ToString(); } } } ```
e84f1b20-195f-4cbf-a6d9-a97bacec38c2
{ "language": "C#" }
```c# using FreecraftCore.Serializer.KnownTypes; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FreecraftCore.Serializer.Tests { [TestFixture] public class StringTests { [Test] public static void Test_String_Serializer_Serializes() { //arrange SerializerService serializer = new SerializerService(); serializer.Compile(); //act string value = serializer.Deserialize<string>(serializer.Serialize("Hello!")); //assert Assert.AreEqual(value, "Hello!"); } } } ``` Add empty to null check
```c# using FreecraftCore.Serializer.KnownTypes; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FreecraftCore.Serializer.Tests { [TestFixture] public class StringTests { [Test] public static void Test_String_Serializer_Serializes() { //arrange SerializerService serializer = new SerializerService(); serializer.Compile(); //act string value = serializer.Deserialize<string>(serializer.Serialize("Hello!")); //assert Assert.AreEqual(value, "Hello!"); } [Test] public static void Test_String_Serializer_Can_Serialize_Empty_String() { //arrange SerializerService serializer = new SerializerService(); serializer.Compile(); //act string value = serializer.Deserialize<string>(serializer.Serialize("")); //assert Assert.Null(value); } } } ```
b16f9374-b7ec-48e1-bf61-963d985c46e6
{ "language": "C#" }
```c# using System; using System.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace AudioWorks.Extensions { abstract class ExtensionContainerBase { static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty, "Extensions")); protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration() .WithAssemblies(_extensionRoot .EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories) .Select(f => f.FullName) .Select(Assembly.LoadFrom)) .CreateContainer(); static ExtensionContainerBase() { // Search all extension directories for unresolved references // .NET Core AssemblyLoadContext.Default.Resolving += (context, name) => AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories) .FirstOrDefault()? .FullName); // Full Framework AppDomain.CurrentDomain.AssemblyResolve += (context, name) => Assembly.LoadFrom(_extensionRoot .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories) .FirstOrDefault()? .FullName); } } } ``` Resolve binding exception on netfx.
```c# using System; using System.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; namespace AudioWorks.Extensions { abstract class ExtensionContainerBase { static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty, "Extensions")); protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration() .WithAssemblies(_extensionRoot .EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories) .Select(f => f.FullName) .Select(Assembly.LoadFrom)) .CreateContainer(); static ExtensionContainerBase() { // Search all extension directories for unresolved references // Assembly.LoadFrom only works on the full framework if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.Ordinal)) AppDomain.CurrentDomain.AssemblyResolve += (context, name) => Assembly.LoadFrom(_extensionRoot .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories) .FirstOrDefault()? .FullName); // Use AssemblyLoadContext on .NET Core else UseAssemblyLoadContext(); } static void UseAssemblyLoadContext() { // Workaround - this needs to reside in a separate method to avoid a binding exception with the desktop // framework, as System.Runtime.Loader does not include a net462 library. AssemblyLoadContext.Default.Resolving += (context, name) => AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories) .FirstOrDefault()? .FullName); } } } ```
963e2501-33c1-4326-8270-1a9a68af6941
{ "language": "C#" }
```c# @model JoinRpg.DataModel.MarkdownString @{ var requiredMsg = new MvcHtmlString(""); var validation = false; foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata)) { if (attr.Key == "data-val-required") { requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'"); validation = true; } } } <div> Можно использовать MarkDown (**<b>полужирный</b>**, _<i>курсив</i>_) <br/> <textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea> </div> @if (validation) { @Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" }) }``` Add link to Markdown help
```c# @model JoinRpg.DataModel.MarkdownString @{ var requiredMsg = new MvcHtmlString(""); var validation = false; foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata)) { if (attr.Key == "data-val-required") { requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'"); validation = true; } } } <div> Можно использовать <a href="http://daringfireball.net/projects/markdown/syntax">MarkDown</a> (**<b>полужирный</b>**, _<i>курсив</i>_) <br/> <textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea> </div> @if (validation) { @Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" }) }```
7c3fefad-115e-4a18-ab39-501fdd7d8b9e
{ "language": "C#" }
```c# using Microsoft.Analytics.Interfaces; using Microsoft.Analytics.Types.Sql; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; // TweetAnalysis Assembly // Show the use of a U-SQL user-defined function (UDF) // // Register this assembly at master.TweetAnalysis e`ither using Register Assembly on TweetAnalysisClass project in Visual Studio // or by compiling the assembly, uploading it (if you want to run it in Azure), and registering it with REGISTER ASSEMBLY U-SQL script. // namespace TweetAnalysis { public class Udfs { // SqlArray<string> get_mentions(string tweet) // // Returns a U-SQL array of string containing the twitter handles that were mentioned inside the tweet. // public static SqlArray<string> get_mentions(string tweet) { return new SqlArray<string>( tweet.Split(new char[] { ' ', ',', '.', ':', '!', ';', '"', '“' }).Where(x => x.StartsWith("@")) ); } } } ``` Fix a typo in comment
```c# using Microsoft.Analytics.Interfaces; using Microsoft.Analytics.Types.Sql; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; // TweetAnalysis Assembly // Show the use of a U-SQL user-defined function (UDF) // // Register this assembly at master.TweetAnalysis either using Register Assembly on TweetAnalysisClass project in Visual Studio // or by compiling the assembly, uploading it (if you want to run it in Azure), and registering it with REGISTER ASSEMBLY U-SQL script. // namespace TweetAnalysis { public class Udfs { // SqlArray<string> get_mentions(string tweet) // // Returns a U-SQL array of string containing the twitter handles that were mentioned inside the tweet. // public static SqlArray<string> get_mentions(string tweet) { return new SqlArray<string>( tweet.Split(new char[] { ' ', ',', '.', ':', '!', ';', '"', '“' }).Where(x => x.StartsWith("@")) ); } } } ```
30e9a226-cdc9-45fd-89e4-0465d2ca9074
{ "language": "C#" }
```c# using Microsoft.Build.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace Microsoft.NET.Build.Tasks { public class CheckForImplicitPackageReferenceOverrides : TaskBase { const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined"; [Required] public ITaskItem [] PackageReferenceItems { get; set; } [Required] public string MoreInformationLink { get; set; } [Output] public ITaskItem[] ItemsToRemove { get; set; } protected override void ExecuteCore() { var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec.ToLowerInvariant()).Where(g => g.Count() > 1); var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where( item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase))); ItemsToRemove = duplicateItemsToRemove.ToArray(); foreach (var itemToRemove in ItemsToRemove) { string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning, itemToRemove.ItemSpec, MoreInformationLink); Log.LogWarning(message); } } } } ``` Switch to OrdinalIgnoreCase comparison for PackageReference deduplication
```c# using Microsoft.Build.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace Microsoft.NET.Build.Tasks { public class CheckForImplicitPackageReferenceOverrides : TaskBase { const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined"; [Required] public ITaskItem [] PackageReferenceItems { get; set; } [Required] public string MoreInformationLink { get; set; } [Output] public ITaskItem[] ItemsToRemove { get; set; } protected override void ExecuteCore() { var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1); var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where( item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase))); ItemsToRemove = duplicateItemsToRemove.ToArray(); foreach (var itemToRemove in ItemsToRemove) { string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning, itemToRemove.ItemSpec, MoreInformationLink); Log.LogWarning(message); } } } } ```
4e916f7b-3362-4b81-bbc6-56e47294b115
{ "language": "C#" }
```c# using OpenTK; using OpenTK.Graphics; using StorybrewCommon.Mapset; using StorybrewCommon.Scripting; using StorybrewCommon.Storyboarding; using StorybrewCommon.Storyboarding.Util; using StorybrewCommon.Subtitles; using StorybrewCommon.Util; using System; using System.Collections.Generic; using System.Linq; namespace StorybrewScripts { public class %CLASSNAME% : StoryboardObjectGenerator { public override void Generate() { } } } ``` Remove extra tab in the script template.
```c# using OpenTK; using OpenTK.Graphics; using StorybrewCommon.Mapset; using StorybrewCommon.Scripting; using StorybrewCommon.Storyboarding; using StorybrewCommon.Storyboarding.Util; using StorybrewCommon.Subtitles; using StorybrewCommon.Util; using System; using System.Collections.Generic; using System.Linq; namespace StorybrewScripts { public class %CLASSNAME% : StoryboardObjectGenerator { public override void Generate() { } } } ```
04ff6444-8b07-4a3a-8b81-918133e136b5
{ "language": "C#" }
```c# namespace Ooui { public class Iframe : Element { public string Source { get => GetStringAttribute ("src", null); set => SetAttributeProperty ("src", value); } public Iframe () : base ("iframe") { } } } ``` Fix closing tag on iframe
```c# namespace Ooui { public class Iframe : Element { public string Source { get => GetStringAttribute ("src", null); set => SetAttributeProperty ("src", value); } public Iframe () : base ("iframe") { } protected override bool HtmlNeedsFullEndElement => true; } } ```
584fe194-544c-4a8b-b6a7-ef556b0b2926
{ "language": "C#" }
```c# using UnityEngine; namespace Weapons.Projectiles.Behaviours { /// <summary> /// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something. /// </summary> public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn { [SerializeField] private GameObject decal = null; [Tooltip("Living time of decal.")] [SerializeField] private float animationTime = 0; [Tooltip("Spawn decal on collision?")] [SerializeField] private bool isTriggeredOnHit = true; public void OnDespawn(RaycastHit2D hit, Vector2 point) { if (isTriggeredOnHit && hit.collider != null) { OnBeamEnd(hit.point); } else { OnBeamEnd(point); } } private bool OnBeamEnd(Vector2 position) { var newDecal = Spawn.ClientPrefab(decal.name, position).GameObject; var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>(); timeLimitedDecal.SetUpDecal(animationTime); return false; } } }``` Make decal on despawn script use void.
```c# using UnityEngine; namespace Weapons.Projectiles.Behaviours { /// <summary> /// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something. /// </summary> public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn { [SerializeField] private GameObject decal = null; [Tooltip("Living time of decal.")] [SerializeField] private float animationTime = 0; [Tooltip("Spawn decal on collision?")] [SerializeField] private bool isTriggeredOnHit = true; public void OnDespawn(RaycastHit2D hit, Vector2 point) { if (isTriggeredOnHit && hit.collider != null) { OnBeamEnd(hit.point); } else { OnBeamEnd(point); } } private void OnBeamEnd(Vector2 position) { var newDecal = Spawn.ClientPrefab(decal.name, position).GameObject; var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>(); timeLimitedDecal.SetUpDecal(animationTime); } } }```
9221dccc-e875-4367-9831-057ddc0b4f86
{ "language": "C#" }
```c# @using Hops.Models; @model ListModel<HopModel> @{ Layout = "~/Views/Shared/_Layout.cshtml"; } @{ ViewBag.Title = "Search results - Hops"; } @if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm)) { <h3>Search results for "@Model.Pagination.SearchTerm":</h3> } @Html.Partial("~/Views/Hop/List", Model)``` Fix search result when returning multiple results
```c# @using Hops.Models; @model ListModel<HopModel> @{ Layout = "~/Views/Shared/_Layout.cshtml"; } @{ ViewBag.Title = "Search results - Hops"; } @if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm)) { <h3>Search results for "@Model.Pagination.SearchTerm":</h3> } @Html.Partial("~/Views/Hop/List.cshtml", Model)```
7e9b8839-a690-4d2c-8980-074f79f5629d
{ "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("Glob")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Glob")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Glob.Tests")] [assembly: InternalsVisibleTo("Glob.Benchmarks")]``` Fix extra assembly info attributes since they are generated by nuget
```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("Glob")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Glob")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // 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: InternalsVisibleTo("Glob.Tests")] [assembly: InternalsVisibleTo("Glob.Benchmarks")]```
1552aa73-45b5-407f-ab15-d0a8e6e817a4
{ "language": "C#" }
```c# using System; using System.Text; using Microsoft.AspNetCore.Mvc; namespace Markdig.WebApp { public class ApiController : Controller { // GET api/to_html?text=xxx&extensions=advanced [Route("api/to_html")] [HttpGet()] public object Get([FromQuery] string text, [FromQuery] string extension) { try { if (text == null) { text = string.Empty; } if (text.Length > 1000) { text = text.Substring(0, 1000); } var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build(); var result = Markdown.ToHtml(text, pipeline); return new {name = "markdig", html = result, version = Markdown.Version}; } catch (Exception ex) { return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version }; } } private static string GetPrettyMessageFromException(Exception exception) { var builder = new StringBuilder(); while (exception != null) { builder.Append(exception.Message); exception = exception.InnerException; } return builder.ToString(); } } } ``` Return an empty string for / on markdig webapi
```c# using System; using System.Text; using Microsoft.AspNetCore.Mvc; namespace Markdig.WebApp { public class ApiController : Controller { [HttpGet()] [Route("")] public string Empty() { return string.Empty; } // GET api/to_html?text=xxx&extensions=advanced [Route("api/to_html")] [HttpGet()] public object Get([FromQuery] string text, [FromQuery] string extension) { try { if (text == null) { text = string.Empty; } if (text.Length > 1000) { text = text.Substring(0, 1000); } var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build(); var result = Markdown.ToHtml(text, pipeline); return new {name = "markdig", html = result, version = Markdown.Version}; } catch (Exception ex) { return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version }; } } private static string GetPrettyMessageFromException(Exception exception) { var builder = new StringBuilder(); while (exception != null) { builder.Append(exception.Message); exception = exception.InnerException; } return builder.ToString(); } } } ```
72ffb710-d341-40d7-afc5-4fcba63f4898
{ "language": "C#" }
```c# using System; namespace Python.Runtime.Codecs { [Obsolete] public sealed class EnumPyIntCodec : IPyObjectEncoder, IPyObjectDecoder { public static EnumPyIntCodec Instance { get; } = new EnumPyIntCodec(); public bool CanDecode(PyType objectType, Type targetType) { return targetType.IsEnum && objectType.IsSubclass(Runtime.PyLongType); } public bool CanEncode(Type type) { return type == typeof(object) || type == typeof(ValueType) || type.IsEnum; } public bool TryDecode<T>(PyObject pyObj, out T? value) { value = default; if (!typeof(T).IsEnum) return false; Type etype = Enum.GetUnderlyingType(typeof(T)); if (!PyInt.IsIntType(pyObj)) return false; object? result; try { result = pyObj.AsManagedObject(etype); } catch (InvalidCastException) { return false; } if (Enum.IsDefined(typeof(T), result) || typeof(T).IsFlagsEnum()) { value = (T)Enum.ToObject(typeof(T), result); return true; } return false; } public PyObject? TryEncode(object value) { if (value is null) return null; var enumType = value.GetType(); if (!enumType.IsEnum) return null; return new PyInt(Convert.ToInt64(value)); } private EnumPyIntCodec() { } } } ``` Allow conversion of UInt64 based enums
```c# using System; namespace Python.Runtime.Codecs { [Obsolete] public sealed class EnumPyIntCodec : IPyObjectEncoder, IPyObjectDecoder { public static EnumPyIntCodec Instance { get; } = new EnumPyIntCodec(); public bool CanDecode(PyType objectType, Type targetType) { return targetType.IsEnum && objectType.IsSubclass(Runtime.PyLongType); } public bool CanEncode(Type type) { return type == typeof(object) || type == typeof(ValueType) || type.IsEnum; } public bool TryDecode<T>(PyObject pyObj, out T? value) { value = default; if (!typeof(T).IsEnum) return false; Type etype = Enum.GetUnderlyingType(typeof(T)); if (!PyInt.IsIntType(pyObj)) return false; object? result; try { result = pyObj.AsManagedObject(etype); } catch (InvalidCastException) { return false; } if (Enum.IsDefined(typeof(T), result) || typeof(T).IsFlagsEnum()) { value = (T)Enum.ToObject(typeof(T), result); return true; } return false; } public PyObject? TryEncode(object value) { if (value is null) return null; var enumType = value.GetType(); if (!enumType.IsEnum) return null; try { return new PyInt(Convert.ToInt64(value)); } catch (OverflowException) { return new PyInt(Convert.ToUInt64(value)); } } private EnumPyIntCodec() { } } } ```
5ecb0c15-cb49-4ded-9738-0e2d3a9ab021
{ "language": "C#" }
```c# /* Copyright © Iain McDonald 2010-2020 This file is part of Decider. */ using System; using System.Collections.Generic; using System.Linq; namespace Decider.Example.LeagueGeneration { public class Program { static void Main(string[] args) { var leagueGeneration = new LeagueGeneration((args.Length >= 1) ? Int32.Parse(args[0]) : 20); leagueGeneration.Search(); leagueGeneration.GenerateFixtures(); for (var i = 0; i < leagueGeneration.FixtureWeeks.Length; ++i) { for (var j = 0; j < leagueGeneration.FixtureWeeks[i].Length; ++j) Console.Write(string.Format("{0,2}", leagueGeneration.FixtureWeeks[i][j]) + " "); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("Runtime:\t{0}\nBacktracks:\t{1}", leagueGeneration.State.Runtime, leagueGeneration.State.Backtracks); Console.WriteLine("Solutions:\t{0}", leagueGeneration.State.NumberOfSolutions); } } }``` Create first automated acceptance test
```c# /* Copyright © Iain McDonald 2010-2020 This file is part of Decider. */ using System; using System.Collections.Generic; using System.Linq; namespace Decider.Example.LeagueGeneration { public class Program { static void Main(string[] args) { var leagueGeneration = new LeagueGeneration((args.Length >= 1) ? Int32.Parse(args[0]) : 20); leagueGeneration.Search(); leagueGeneration.GenerateFixtures(); for (var i = 0; i < leagueGeneration.FixtureWeeks.Length; ++i) { for (var j = 0; j < leagueGeneration.FixtureWeeks[i].Length; ++j) Console.Write(string.Format("{0,2}", leagueGeneration.FixtureWeeks[i][j]) + " "); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("Runtime:\t{0}\nBacktracks:\t{1}", leagueGeneration.State.Runtime, leagueGeneration.State.Backtracks); Console.WriteLine("Solutions:\t{0}", leagueGeneration.State.NumberOfSolutions); } } } ```
0698db79-41eb-461c-bd9f-a51c702d591a
{ "language": "C#" }
```c# using System; using System.Diagnostics; namespace Nett { [DebuggerDisplay("{FromType} -> {ToType}")] internal sealed class TomlConverter<TFrom, TTo> : TomlConverterBase<TFrom, TTo> { private readonly Func<TFrom, TTo> convert; public TomlConverter(Func<TFrom, TTo> convert) { if (convert == null) { throw new ArgumentNullException(nameof(convert)); } this.convert = convert; } public override TTo Convert(TFrom from, Type targetType) => this.convert(from); } } ``` Remove DebuggerDisplay attribute not applicable anymore
```c# using System; namespace Nett { internal sealed class TomlConverter<TFrom, TTo> : TomlConverterBase<TFrom, TTo> { private readonly Func<TFrom, TTo> convert; public TomlConverter(Func<TFrom, TTo> convert) { if (convert == null) { throw new ArgumentNullException(nameof(convert)); } this.convert = convert; } public override TTo Convert(TFrom from, Type targetType) => this.convert(from); } } ```
0eff61b5-007d-4dc4-9f8e-da5006f32df4
{ "language": "C#" }
```c# namespace TAUtil.Tdf { using System.Collections.Generic; public class TdfNodeAdapter : ITdfNodeAdapter { private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>(); public TdfNodeAdapter() { this.RootNode = new TdfNode(); this.nodeStack.Push(this.RootNode); } public TdfNode RootNode { get; private set; } public void BeginBlock(string name) { TdfNode n = new TdfNode(name); this.nodeStack.Peek().Keys[name] = n; this.nodeStack.Push(n); } public void AddProperty(string name, string value) { this.nodeStack.Peek().Entries[name] = value; } public void EndBlock() { this.nodeStack.Pop(); } } } ``` Make all strings in loaded TdfNodes lowercase
```c# namespace TAUtil.Tdf { using System.Collections.Generic; public class TdfNodeAdapter : ITdfNodeAdapter { private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>(); public TdfNodeAdapter() { this.RootNode = new TdfNode(); this.nodeStack.Push(this.RootNode); } public TdfNode RootNode { get; private set; } public void BeginBlock(string name) { name = name.ToLowerInvariant(); TdfNode n = new TdfNode(name); this.nodeStack.Peek().Keys[name] = n; this.nodeStack.Push(n); } public void AddProperty(string name, string value) { name = name.ToLowerInvariant(); value = value.ToLowerInvariant(); this.nodeStack.Peek().Entries[name] = value; } public void EndBlock() { this.nodeStack.Pop(); } } } ```
9fc15493-e56a-44d7-bc43-3b7779c30d10
{ "language": "C#" }
```c# @model ChatApp.Controllers.ChatMessagesViewModel @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" @using ChatApp.Models <!DOCTYPE html> <html> <head> <title>ChatApp</title> </head> <body> <table> @foreach (Message msg in Model.OldMessages) { <tr> <td class="author">@msg.Author</td> <td class="text">@msg.Text</td> <td class="timestamp">@msg.Timestamp</td> </tr> } </table> <form asp-action="SendNewMessage" method="post"> <input asp-for="NewMessage.Author"/> <input asp-for="NewMessage.Text"/> <input type="submit" value="Send"/> </form> </body> </html> ``` Update UI look and feel
```c# @model ChatApp.Controllers.ChatMessagesViewModel @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" @using ChatApp.Models <!DOCTYPE html> <html> <head> <title>ChatApp</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css" async> </head> <body> <table class="w3-table w3-striped"> @foreach (Message msg in Model.OldMessages) { <tr> <td name="author" class="w3-right-align" style="width: 10em;">@msg.Author:</td> <td name="text">@msg.Text</td> <td name="timestamp" class="w3-right-align">@msg.Timestamp</td> </tr> } </table> <form asp-action="SendNewMessage" method="post" class="w3-row"> <input asp-for="NewMessage.Author" class="w3-input w3-border w3-col m2" placeholder="Name"/> <input asp-for="NewMessage.Text" class="w3-input w3-border w3-col m8" placeholder="Message"/> <input type="submit" value="Send" class="w3-btn w3-blue w3-col w3-large m2"/> </form> </body> </html> ```
f83379fb-0e21-41b8-a195-530a9ff261e7
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCopyright(XsdDocMetadata.Copyright)] [assembly: AssemblyCompany("Immo Landwerth")] [assembly: AssemblyProduct("XML Schema Documenter")] [assembly: CLSCompliant(false)] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion(XsdDocMetadata.Version)] [assembly: AssemblyFileVersion(XsdDocMetadata.Version)] internal static class XsdDocMetadata { public const string Version = "15.10.10.0"; public const string Copyright = "Copyright 2009-2015 Immo Landwerth"; }``` Align XSD Doc version number with SHFB
```c# using System; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCopyright(XsdDocMetadata.Copyright)] [assembly: AssemblyCompany("Immo Landwerth")] [assembly: AssemblyProduct("XML Schema Documenter")] [assembly: CLSCompliant(false)] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion(XsdDocMetadata.Version)] [assembly: AssemblyFileVersion(XsdDocMetadata.Version)] internal static class XsdDocMetadata { public const string Version = "16.9.17.0"; public const string Copyright = "Copyright 2009-2015 Immo Landwerth"; }```
9c625c5c-54dc-4cb5-9d38-414bbbac503c
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("© Yevgeniy Shunevych 2018")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")] ``` Increment copyright year of projects to 2019
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("© Yevgeniy Shunevych 2019")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")] ```
1580902a-532c-4238-b82f-7defbee7bc53
{ "language": "C#" }
```c# using SimpleStack.Orm.Expressions; namespace SimpleStack.Orm.PostgreSQL { /// <summary>A postgre SQL expression visitor.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> public class PostgreSQLExpressionVisitor<T>:SqlExpressionVisitor<T> { public PostgreSQLExpressionVisitor(IDialectProvider dialectProvider) : base(dialectProvider) { } /// <summary>Gets the limit expression.</summary> /// <value>The limit expression.</value> public override string LimitExpression{ get{ if(!Rows.HasValue) return ""; string offset; if(Skip.HasValue){ offset= string.Format(" OFFSET {0}", Skip.Value ); } else{ offset=string.Empty; } return string.Format("LIMIT {0}{1}", Rows.Value, offset); } } } }``` Add support for XOR in PostgreSQL
```c# using System.Linq.Expressions; using SimpleStack.Orm.Expressions; namespace SimpleStack.Orm.PostgreSQL { /// <summary>A postgre SQL expression visitor.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> public class PostgreSQLExpressionVisitor<T>:SqlExpressionVisitor<T> { public PostgreSQLExpressionVisitor(IDialectProvider dialectProvider) : base(dialectProvider) { } protected override string BindOperant(ExpressionType e) { switch (e) { case ExpressionType.ExclusiveOr: return "#"; } return base.BindOperant(e); } /// <summary>Gets the limit expression.</summary> /// <value>The limit expression.</value> public override string LimitExpression{ get{ if(!Rows.HasValue) return ""; string offset; if(Skip.HasValue){ offset= string.Format(" OFFSET {0}", Skip.Value ); } else{ offset=string.Empty; } return string.Format("LIMIT {0}{1}", Rows.Value, offset); } } } }```