doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
1b29e693-996b-4020-b7d8-97c36132c3e5 | {
"language": "C#"
} | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Reflection.Context
{
public class CustomReflectionContextTests
{
[Fact]
public void InstantiateContext_Throws()
{
Assert.Throws<PlatformNotSupportedException>(() => new DerivedContext());
}
private class DerivedContext : CustomReflectionContext { }
}
}
```
Fix System.Reflection.Context test to run on Desktop | ```c#
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Reflection.Context
{
public class CustomReflectionContextTests
{
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void InstantiateContext_Throws()
{
Assert.Throws<PlatformNotSupportedException>(() => new DerivedContext());
}
private class DerivedContext : CustomReflectionContext { }
}
}
``` |
f093030c-7b91-4ade-ac66-c88a3c2da395 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Arkivverket.Arkade.Util;
namespace Arkivverket.Arkade.Core.Addml.Definitions
{
public class Separator
{
private static readonly Dictionary<string, string> SpecialSeparators = new Dictionary<string, string>
{
{"CRLF", "\r\n"}
};
public static readonly Separator CRLF = new Separator("CRLF");
private readonly string _name;
private readonly string _separator;
public Separator(string separator)
{
Assert.AssertNotNullOrEmpty("separator", separator);
_name = separator;
_separator = Convert(separator);
}
public string Get()
{
return _separator;
}
public override string ToString()
{
return _name;
}
protected bool Equals(Separator other)
{
return string.Equals(_name, other._name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Separator) obj);
}
public override int GetHashCode()
{
return _name?.GetHashCode() ?? 0;
}
private string Convert(string s)
{
return SpecialSeparators.ContainsKey(s) ? SpecialSeparators[s] : s;
}
internal int GetLength()
{
return _separator.Length;
}
}
}```
Add support for LF record separator | ```c#
using System;
using System.Collections.Generic;
using Arkivverket.Arkade.Util;
namespace Arkivverket.Arkade.Core.Addml.Definitions
{
public class Separator
{
private static readonly Dictionary<string, string> SpecialSeparators = new Dictionary<string, string>
{
{"CRLF", "\r\n"},
{"LF", "\n"}
};
public static readonly Separator CRLF = new Separator("CRLF");
private readonly string _name;
private readonly string _separator;
public Separator(string separator)
{
Assert.AssertNotNullOrEmpty("separator", separator);
_name = separator;
_separator = Convert(separator);
}
public string Get()
{
return _separator;
}
public override string ToString()
{
return _name;
}
protected bool Equals(Separator other)
{
return string.Equals(_name, other._name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Separator) obj);
}
public override int GetHashCode()
{
return _name?.GetHashCode() ?? 0;
}
private string Convert(string s)
{
return SpecialSeparators.ContainsKey(s) ? SpecialSeparators[s] : s;
}
internal int GetLength()
{
return _separator.Length;
}
}
}``` |
bcc706e5-cfdd-474f-9612-cbce9bc724c7 | {
"language": "C#"
} | ```c#
using Espera.Core;
using Espera.Core.Management;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace Espera.Services
{
public static class MobileHelper
{
public static async Task<byte[]> CompressContentAsync(byte[] content)
{
using (var targetStream = new MemoryStream())
{
using (var stream = new GZipStream(targetStream, CompressionMode.Compress))
{
await stream.WriteAsync(content, 0, content.Length);
}
return targetStream.ToArray();
}
}
public static JObject SerializePlaylist(Playlist playlist)
{
return JObject.FromObject(new
{
name = playlist.Name,
current = playlist.CurrentSongIndex.Value.ToString(),
songs = playlist.Select(x => new
{
artist = x.Song.Artist,
title = x.Song.Title,
source = x.Song is LocalSong ? "local" : "youtube",
guid = x.Guid
})
});
}
public static JObject SerializeSongs(IEnumerable<LocalSong> songs)
{
return JObject.FromObject(new
{
songs = songs
.Select(s => new
{
album = s.Album,
artist = s.Artist,
duration = s.Duration.TotalSeconds,
genre = s.Genre,
title = s.Title,
guid = s.Guid
})
});
}
}
}```
Send the current song index as nullable | ```c#
using Espera.Core;
using Espera.Core.Management;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace Espera.Services
{
public static class MobileHelper
{
public static async Task<byte[]> CompressContentAsync(byte[] content)
{
using (var targetStream = new MemoryStream())
{
using (var stream = new GZipStream(targetStream, CompressionMode.Compress))
{
await stream.WriteAsync(content, 0, content.Length);
}
return targetStream.ToArray();
}
}
public static JObject SerializePlaylist(Playlist playlist)
{
return JObject.FromObject(new
{
name = playlist.Name,
current = playlist.CurrentSongIndex.Value,
songs = playlist.Select(x => new
{
artist = x.Song.Artist,
title = x.Song.Title,
source = x.Song is LocalSong ? "local" : "youtube",
guid = x.Guid
})
});
}
public static JObject SerializeSongs(IEnumerable<LocalSong> songs)
{
return JObject.FromObject(new
{
songs = songs
.Select(s => new
{
album = s.Album,
artist = s.Artist,
duration = s.Duration.TotalSeconds,
genre = s.Genre,
title = s.Title,
guid = s.Guid
})
});
}
}
}``` |
01d44fc7-081a-4bec-97a6-22f03b27ffce | {
"language": "C#"
} | ```c#
using SubMapper.EnumerableMapping;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SubMapper.EnumerableMapping.Adders
{
public static partial class PartialEnumerableMappingExtensions
{
public static PartialEnumerableMapping<TSubA, TSubB, IEnumerable<TSubIItem>, TSubJ, TSubIItem>
WithArrayConcatAdder<TSubA, TSubB, TSubJ, TSubIItem>(
this PartialEnumerableMapping<TSubA, TSubB, IEnumerable<TSubIItem>, TSubJ, TSubIItem> source)
where TSubJ : new()
where TSubIItem : new()
{
source.WithAdder((bc, b) => new[] { b }.Concat(bc ?? new TSubIItem[] { }).ToArray());
return source;
}
}
}
```
Make concat add to the eof array | ```c#
using SubMapper.EnumerableMapping;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SubMapper.EnumerableMapping.Adders
{
public static partial class PartialEnumerableMappingExtensions
{
public static PartialEnumerableMapping<TSubA, TSubB, IEnumerable<TSubIItem>, TSubJ, TSubIItem>
WithArrayConcatAdder<TSubA, TSubB, TSubJ, TSubIItem>(
this PartialEnumerableMapping<TSubA, TSubB, IEnumerable<TSubIItem>, TSubJ, TSubIItem> source)
where TSubJ : new()
where TSubIItem : new()
{
source.WithAdder((bc, b) => (bc ?? new TSubIItem[] { }).Concat(new[] { b }).ToArray());
return source;
}
}
}
``` |
63c4f505-c982-4750-ad5b-09119899245c | {
"language": "C#"
} | ```c#
using CSharpMath.Apple;
namespace CSharpMath.Ios
{
static class IosMathLabels
{
public static AppleLatexView LatexView(string latex)
{
var typesettingContext = AppleTypesetters.CreateTypesettingContext()
var view = new AppleLatexView();
view.SetLatex(latex);
return view;
}
}
}```
Use the new factory for Typesetting context | ```c#
using CSharpMath.Apple;
namespace CSharpMath.Ios
{
static class IosMathLabels
{
public static AppleLatexView LatexView(string latex)
{
var typesettingContext = AppleTypesetters.CreateLatinMath();
var view = new AppleLatexView(typesettingContext);
view.SetLatex(latex);
return view;
}
}
}``` |
304e3312-3485-44e7-8b80-043e5f9278db | {
"language": "C#"
} | ```c#
using GalaSoft.MvvmLight;
namespace twitch_tv_viewer.ViewModels.Components
{
internal class MessageDisplayViewModel : ViewModelBase
{
private string _message;
public string Message
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged();
}
}
}
}
```
Clear notification on change in textbox text | ```c#
using GalaSoft.MvvmLight;
namespace twitch_tv_viewer.ViewModels.Components
{
internal class MessageDisplayViewModel : ViewModelBase
{
private string _message;
public string Message
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged();
MessengerInstance.Send(new NotificationMessage());
}
}
}
}
``` |
f2c01d5d-375c-493b-baac-9090606fe0d1 | {
"language": "C#"
} | ```c#
using System;
using UnityEngine;
namespace FullSerializer {
/// <summary>
/// Enables some top-level customization of Full Serializer.
/// </summary>
public static class fsConfig {
/// <summary>
/// The attributes that will force a field or property to be serialized.
/// </summary>
public static Type[] SerializeAttributes = new[] { typeof(SerializeField), typeof(fsPropertyAttribute) };
/// <summary>
/// The attributes that will force a field or property to *not* be serialized.
/// </summary>
public static Type[] IgnoreSerializeAttributes = new[] { typeof(NonSerializedAttribute), typeof(fsIgnoreAttribute) };
/// <summary>
/// The default member serialization.
/// </summary>
public static fsMemberSerialization DefaultMemberSerialization {
get {
return _defaultMemberSerialization;
}
set {
_defaultMemberSerialization = value;
fsMetaType.ClearCache();
}
}
private static fsMemberSerialization _defaultMemberSerialization = fsMemberSerialization.OptOut;
}
}```
Correct default serialization strategy to `Default` | ```c#
using System;
using UnityEngine;
namespace FullSerializer {
/// <summary>
/// Enables some top-level customization of Full Serializer.
/// </summary>
public static class fsConfig {
/// <summary>
/// The attributes that will force a field or property to be serialized.
/// </summary>
public static Type[] SerializeAttributes = new[] { typeof(SerializeField), typeof(fsPropertyAttribute) };
/// <summary>
/// The attributes that will force a field or property to *not* be serialized.
/// </summary>
public static Type[] IgnoreSerializeAttributes = new[] { typeof(NonSerializedAttribute), typeof(fsIgnoreAttribute) };
/// <summary>
/// The default member serialization.
/// </summary>
public static fsMemberSerialization DefaultMemberSerialization {
get {
return _defaultMemberSerialization;
}
set {
_defaultMemberSerialization = value;
fsMetaType.ClearCache();
}
}
private static fsMemberSerialization _defaultMemberSerialization = fsMemberSerialization.Default;
}
}``` |
2953a370-b4a5-4672-96ce-bc88d2a26807 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Objects.Post.Scrobbles
{
using Newtonsoft.Json;
using System;
public abstract class TraktScrobblePost : IValidatable
{
[JsonProperty(PropertyName = "progress")]
public float Progress { get; set; }
[JsonProperty(PropertyName = "app_version")]
public string AppVersion { get; set; }
[JsonProperty(PropertyName = "app_date")]
public string AppDate { get; set; }
public void Validate()
{
if (Progress.CompareTo(0.0f) < 0)
throw new ArgumentException("progress value not valid");
if (Progress.CompareTo(100.0f) > 0)
throw new ArgumentException("progress value not valid");
}
}
}
```
Improve argument exception message of scrobble post. | ```c#
namespace TraktApiSharp.Objects.Post.Scrobbles
{
using Newtonsoft.Json;
using System;
public abstract class TraktScrobblePost : IValidatable
{
[JsonProperty(PropertyName = "progress")]
public float Progress { get; set; }
[JsonProperty(PropertyName = "app_version")]
public string AppVersion { get; set; }
[JsonProperty(PropertyName = "app_date")]
public string AppDate { get; set; }
public void Validate()
{
if (Progress.CompareTo(0.0f) < 0 || Progress.CompareTo(100.0f) > 0)
throw new ArgumentException("progress value not valid - value must be between 0 and 100");
}
}
}
``` |
e09e8606-8b43-44e3-b659-0882ba83d92f | {
"language": "C#"
} | ```c#
using System.Net.Http;
using SFA.DAS.CommitmentPayments.WebJob.Configuration;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
using SFA.DAS.NLog.Logger.Web.MessageHandlers;
using SFA.DAS.Provider.Events.Api.Client;
using SFA.DAS.Provider.Events.Api.Client.Configuration;
using StructureMap;
namespace SFA.DAS.CommitmentPayments.WebJob.DependencyResolution
{
internal class PaymentsRegistry : Registry
{
public PaymentsRegistry()
{
For<PaymentEventsApi>().Use(c => c.GetInstance<CommitmentPaymentsConfiguration>().PaymentEventsApi);
For<IPaymentsEventsApiConfiguration>().Use(c => c.GetInstance<PaymentEventsApi>());
For<IPaymentsEventsApiClient>().Use<PaymentsEventsApiClient>().Ctor<HttpClient>().Is(c => CreateClient(c));
}
private HttpClient CreateClient(IContext context)
{
var config = context.GetInstance<CommitmentPaymentsConfiguration>().PaymentEventsApi;
HttpClient httpClient = new HttpClientBuilder()
.WithBearerAuthorisationHeader(new AzureActiveDirectoryBearerTokenGenerator(config))
.WithHandler(new RequestIdMessageRequestHandler())
.WithHandler(new SessionIdMessageRequestHandler())
.WithDefaultHeaders()
.Build();
return httpClient;
}
}
}
```
Add default request header to Payments API httpClient to look for version 2. Since removing the SecureHttpClient from PaymentEventsApiClient this header was lost. This only matters for data locks as that is the only controller action split by api version at present | ```c#
using System.Net.Http;
using SFA.DAS.CommitmentPayments.WebJob.Configuration;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
using SFA.DAS.NLog.Logger.Web.MessageHandlers;
using SFA.DAS.Provider.Events.Api.Client;
using SFA.DAS.Provider.Events.Api.Client.Configuration;
using StructureMap;
namespace SFA.DAS.CommitmentPayments.WebJob.DependencyResolution
{
internal class PaymentsRegistry : Registry
{
public PaymentsRegistry()
{
For<PaymentEventsApi>().Use(c => c.GetInstance<CommitmentPaymentsConfiguration>().PaymentEventsApi);
For<IPaymentsEventsApiConfiguration>().Use(c => c.GetInstance<PaymentEventsApi>());
For<IPaymentsEventsApiClient>().Use<PaymentsEventsApiClient>().Ctor<HttpClient>().Is(c => CreateClient(c));
}
private HttpClient CreateClient(IContext context)
{
var config = context.GetInstance<CommitmentPaymentsConfiguration>().PaymentEventsApi;
HttpClient httpClient = new HttpClientBuilder()
.WithBearerAuthorisationHeader(new AzureActiveDirectoryBearerTokenGenerator(config))
.WithHandler(new RequestIdMessageRequestHandler())
.WithHandler(new SessionIdMessageRequestHandler())
.WithDefaultHeaders()
.Build();
httpClient.DefaultRequestHeaders.Add("api-version", "2");
return httpClient;
}
}
}
``` |
77e6bc62-4723-422b-8877-7b33e76baed6 | {
"language": "C#"
} | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using System.Drawing;
using ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.SystemDrawing.Tests
{
public partial class MagickImageFactoryTests
{
public partial class TheCreateMethod
{
[TestMethod]
public void ShouldCreateImageFromBitmap()
{
using (var bitmap = new Bitmap(Files.SnakewarePNG))
{
var factory = new MagickImageFactory();
using (var image = factory.Create(bitmap))
{
Assert.AreEqual(286, image.Width);
Assert.AreEqual(67, image.Height);
Assert.AreEqual(MagickFormat.Png, image.Format);
}
}
}
}
}
}```
Add extra tests and missing TestClass attribute. | ```c#
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using System;
using System.Drawing;
using ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.SystemDrawing.Tests
{
public partial class MagickImageFactoryTests
{
[TestClass]
public partial class TheCreateMethod
{
[TestMethod]
public void ShouldThrowExceptionWhenBitmapIsNull()
{
var factory = new MagickImageFactory();
ExceptionAssert.Throws<ArgumentNullException>("bitmap", () => factory.Create((Bitmap)null));
}
[TestMethod]
public void ShouldCreateImageFromBitmap()
{
using (var bitmap = new Bitmap(Files.SnakewarePNG))
{
var factory = new MagickImageFactory();
using (var image = factory.Create(bitmap))
{
Assert.AreEqual(286, image.Width);
Assert.AreEqual(67, image.Height);
Assert.AreEqual(MagickFormat.Png, image.Format);
}
}
}
}
}
}``` |
b759eafc-0c1e-4c81-83ce-aaa911a103f2 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.Native
{
public static class Library
{
[DllImport("libdl.so", EntryPoint = "dlopen")]
private static extern IntPtr dlopen(string filename, int flags);
public static void LoadLazyLocal(string filename)
{
dlopen(filename, 0x001); // RTLD_LOCAL + RTLD_NOW
}
public static void LoadNowLocal(string filename)
{
dlopen(filename, 0x002); // RTLD_LOCAL + RTLD_NOW
}
public static void LoadLazyGlobal(string filename)
{
dlopen(filename, 0x101); // RTLD_GLOBAL + RTLD_LAZY
}
public static void LoadNowGlobal(string filename)
{
dlopen(filename, 0x102); // RTLD_GLOBAL + RTLD_NOW
}
}
}```
Make comment say that 0x001 is RTLD_LOCAL + RTLD_LAZY | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.Native
{
public static class Library
{
[DllImport("libdl.so", EntryPoint = "dlopen")]
private static extern IntPtr dlopen(string filename, int flags);
public static void LoadLazyLocal(string filename)
{
dlopen(filename, 0x001); // RTLD_LOCAL + RTLD_LAZY
}
public static void LoadNowLocal(string filename)
{
dlopen(filename, 0x002); // RTLD_LOCAL + RTLD_NOW
}
public static void LoadLazyGlobal(string filename)
{
dlopen(filename, 0x101); // RTLD_GLOBAL + RTLD_LAZY
}
public static void LoadNowGlobal(string filename)
{
dlopen(filename, 0x102); // RTLD_GLOBAL + RTLD_NOW
}
}
}``` |
c3610d5a-a21c-47df-85ef-1ec325f938a0 | {
"language": "C#"
} | ```c#
// Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Apis.Storage.v1.Data;
using System;
using System.Collections.Generic;
using System.Text;
namespace Google.Cloud.Storage.V1
{
/// <summary>
/// String constants for the names of the storage classes, as used in <see cref="HmacKeyMetadata.State" />.
/// </summary>
public static class HmacKeyStates
{
/// <summary>
/// The key is active, and can be used for signing. It cannot be deleted in this state.
/// </summary>
public const string Active = "ACTIVE";
/// <summary>
/// The key is inactive, and can be used for signing. It can be deleted.
/// </summary>
public const string Inactive = "INACTIVE";
/// <summary>
/// The key has been deleted.
/// </summary>
public const string Deleted = "DELETE";
}
}
```
Fix typo for HMAC key states | ```c#
// Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Apis.Storage.v1.Data;
using System;
using System.Collections.Generic;
using System.Text;
namespace Google.Cloud.Storage.V1
{
/// <summary>
/// String constants for the names of the storage classes, as used in <see cref="HmacKeyMetadata.State" />.
/// </summary>
public static class HmacKeyStates
{
/// <summary>
/// The key is active, and can be used for signing. It cannot be deleted in this state.
/// </summary>
public const string Active = "ACTIVE";
/// <summary>
/// The key is inactive, and can be used for signing. It can be deleted.
/// </summary>
public const string Inactive = "INACTIVE";
/// <summary>
/// The key has been deleted.
/// </summary>
public const string Deleted = "DELETED";
}
}
``` |
7ed4edf6-33bc-4fc8-801d-a5f0643d1d51 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace PogoLocationFeeder.Helper
{
public class JsonSerializerSettingsCultureInvariant : JsonSerializerSettings
{
public JsonSerializerSettingsCultureInvariant()
{
Culture = CultureInfo.InvariantCulture;
}
}
}
```
Fix error when unserializing json object | ```c#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PogoLocationFeeder.Helper
{
public class JsonSerializerSettingsCultureInvariant : JsonSerializerSettings
{
public JsonSerializerSettingsCultureInvariant()
{
Culture = CultureInfo.InvariantCulture;
Converters = new List<JsonConverter> { new DoubleConverter()};
}
}
public class DoubleConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(double) || objectType == typeof(double?));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
{
return token.ToObject<double>();
}
if (token.Type == JTokenType.String)
{
var match = Regex.Match(token.ToString(), @"(1?\-?\d+\.?\d*)");
if (match.Success)
{
return Double.Parse(match.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
}
return Double.Parse(token.ToString(),
System.Globalization.CultureInfo.InvariantCulture);
}
if (token.Type == JTokenType.Null && objectType == typeof(double?))
{
return null;
}
throw new JsonSerializationException("Unexpected token type: " +
token.Type.ToString());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
``` |
80a20934-52d4-4eab-b256-cbfaabf0cce1 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedShow>, TraktMostAnticipatedShow>
{
internal TraktShowsMostAnticipatedRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/anticipated{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
```
Add filter property to most anticipated shows request. | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedShow>, TraktMostAnticipatedShow>
{
internal TraktShowsMostAnticipatedRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/anticipated{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktShowFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
``` |
9745d96d-db1a-4890-87b0-b31b5993e9fa | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
public const string RoslynInlineRenameFile = "Roslyn.FileRename";
// Syntactic LSP experiment treatments.
public const string SyntacticExp_LiveShareTagger_Remote = "RoslynLsp_Tagger";
public const string SyntacticExp_LiveShareTagger_TextMate = "RoslynTextMate_Tagger";
}
}
```
Add dots to experiment names so they can be enabled as feature flags. | ```c#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
public const string RoslynInlineRenameFile = "Roslyn.FileRename";
// Syntactic LSP experiment treatments.
public const string SyntacticExp_LiveShareTagger_Remote = "Roslyn.LspTagger";
public const string SyntacticExp_LiveShareTagger_TextMate = "Roslyn.TextMateTagger";
}
}
``` |
e8b22311-24e7-441c-9be2-8a2d16bf06ff | {
"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.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.BeatmapListing
{
public enum SearchGeneral
{
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralRecommended))]
[Description("Recommended difficulty")]
Recommended,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralConverts))]
[Description("Include converted beatmaps")]
Converts,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFollows))]
[Description("Subscribed mappers")]
Follows,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFeaturedArtists))]
[Description("Featured artists")]
FeaturedArtists
}
}
```
Add spotlighted beatmaps filter to beatmap listing | ```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.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.BeatmapListing
{
public enum SearchGeneral
{
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralRecommended))]
[Description("Recommended difficulty")]
Recommended,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralConverts))]
[Description("Include converted beatmaps")]
Converts,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFollows))]
[Description("Subscribed mappers")]
Follows,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralSpotlights))]
Spotlights,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFeaturedArtists))]
[Description("Featured artists")]
FeaturedArtists
}
}
``` |
6bcbd3a2-5767-4d6a-9efb-9ac483b18d52 | {
"language": "C#"
} | ```c#
using System;
using Shuttle.Core.Infrastructure;
namespace Shuttle.Esb
{
public class DefaultMessageHandlerInvoker : IMessageHandlerInvoker
{
public MessageHandlerInvokeResult Invoke(IPipelineEvent pipelineEvent)
{
Guard.AgainstNull(pipelineEvent, "pipelineEvent");
var state = pipelineEvent.Pipeline.State;
var bus = state.GetServiceBus();
var message = state.GetMessage();
var handler = bus.Configuration.MessageHandlerFactory.GetHandler(message);
if (handler == null)
{
return MessageHandlerInvokeResult.InvokeFailure();
}
try
{
var transportMessage = state.GetTransportMessage();
var messageType = message.GetType();
var contextType = typeof (HandlerContext<>).MakeGenericType(messageType);
var method = handler.GetType().GetMethod("ProcessMessage", new[] {contextType});
if (method == null)
{
throw new ProcessMessageMethodMissingException(string.Format(
EsbResources.ProcessMessageMethodMissingException,
handler.GetType().FullName,
messageType.FullName));
}
var handlerContext = Activator.CreateInstance(contextType, bus, transportMessage, message, state.GetActiveState());
method.Invoke(handler, new[] {handlerContext});
}
finally
{
bus.Configuration.MessageHandlerFactory.ReleaseHandler(handler);
}
return MessageHandlerInvokeResult.InvokedHandler(handler);
}
}
}```
Call the correct implementation if IMessageHandler.ProcessMessage method | ```c#
using System;
using System.Linq;
using Shuttle.Core.Infrastructure;
namespace Shuttle.Esb
{
public class DefaultMessageHandlerInvoker : IMessageHandlerInvoker
{
public MessageHandlerInvokeResult Invoke(IPipelineEvent pipelineEvent)
{
Guard.AgainstNull(pipelineEvent, "pipelineEvent");
var state = pipelineEvent.Pipeline.State;
var bus = state.GetServiceBus();
var message = state.GetMessage();
var handler = bus.Configuration.MessageHandlerFactory.GetHandler(message);
if (handler == null)
{
return MessageHandlerInvokeResult.InvokeFailure();
}
try
{
var transportMessage = state.GetTransportMessage();
var messageType = message.GetType();
var interfaceType = typeof(IMessageHandler<>).MakeGenericType(messageType);
var method = handler.GetType().GetInterfaceMap(interfaceType).TargetMethods.SingleOrDefault();
if (method == null)
{
throw new ProcessMessageMethodMissingException(string.Format(
EsbResources.ProcessMessageMethodMissingException,
handler.GetType().FullName,
messageType.FullName));
}
var contextType = typeof(HandlerContext<>).MakeGenericType(messageType);
var handlerContext = Activator.CreateInstance(contextType, bus, transportMessage, message, state.GetActiveState());
method.Invoke(handler, new[] {handlerContext});
}
finally
{
bus.Configuration.MessageHandlerFactory.ReleaseHandler(handler);
}
return MessageHandlerInvokeResult.InvokedHandler(handler);
}
}
}``` |
dbc6037e-657d-47c1-82aa-bab99f46abbd | {
"language": "C#"
} | ```c#
using System;
using ExRam.Gremlinq.Providers.Neptune;
using Microsoft.Extensions.Configuration;
namespace ExRam.Gremlinq.Core.AspNet
{
public static class GremlinqSetupExtensions
{
public static GremlinqSetup UseNeptune(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
{
return setup
.UseProvider(
"Neptune",
(e, f) => e.UseNeptune(f),
(configurator, configuration) =>
{
if (configuration["ElasticSearchEndPoint"] is { } endPoint)
{
var indexConfiguration = Enum.TryParse<NeptuneElasticSearchIndexConfiguration>(configuration["IndexConfiguration"], true, out var outVar)
? outVar
: NeptuneElasticSearchIndexConfiguration.Standard;
configurator = configurator
.UseElasticSearch(new Uri(endPoint), indexConfiguration);
}
return configurator;
},
extraConfiguration);
}
public static GremlinqSetup UseNeptune<TVertex, TEdge>(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
{
return setup
.UseNeptune(extraConfiguration)
.ConfigureEnvironment(env => env
.UseModel(GraphModel
.FromBaseTypes<TVertex, TEdge>(lookup => lookup
.IncludeAssembliesOfBaseTypes())));
}
}
}
```
Use a section for ElasticSearch. | ```c#
using System;
using ExRam.Gremlinq.Providers.Neptune;
using Microsoft.Extensions.Configuration;
namespace ExRam.Gremlinq.Core.AspNet
{
public static class GremlinqSetupExtensions
{
public static GremlinqSetup UseNeptune(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
{
return setup
.UseProvider(
"Neptune",
(e, f) => e.UseNeptune(f),
(configurator, configuration) =>
{
if (configuration.GetSection("ElasticSearch") is { } elasticSearchSection)
{
if (bool.TryParse(elasticSearchSection["Enabled"], out var isEnabled) && isEnabled && configuration["EndPoint"] is { } endPoint)
{
var indexConfiguration = Enum.TryParse<NeptuneElasticSearchIndexConfiguration>(configuration["IndexConfiguration"], true, out var outVar)
? outVar
: NeptuneElasticSearchIndexConfiguration.Standard;
configurator = configurator
.UseElasticSearch(new Uri(endPoint), indexConfiguration);
}
}
return configurator;
},
extraConfiguration);
}
public static GremlinqSetup UseNeptune<TVertex, TEdge>(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
{
return setup
.UseNeptune(extraConfiguration)
.ConfigureEnvironment(env => env
.UseModel(GraphModel
.FromBaseTypes<TVertex, TEdge>(lookup => lookup
.IncludeAssembliesOfBaseTypes())));
}
}
}
``` |
a81c71ff-de62-4469-a6e1-fb519e0afc4b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public abstract partial class Repository<TSession, TEntity, TPk>
where TEntity : class, IEntity<TPk>
where TSession : ISession
{
public IEnumerable<TEntity> GetAll(ISession session = null)
{
return GetAllAsync(session).Result;
}
public async Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null)
{
if (session != null)
{
return await session.FindAsync<TEntity>();
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync<TEntity>();
}
}
protected async Task<IEnumerable<TEntity>> GetAllAsync(ISession session, Action<IRangedBatchSelectSqlSqlStatementOptionsOptionsBuilder<TEntity>> statement)
{
if (session != null)
{
return await session.FindAsync(statement);
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync(statement);
}
}
}
}
```
Remove get all with dynamic clause. SHould be handeled by user in own class. Otherwise forced to use FastCRUD | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public abstract partial class Repository<TSession, TEntity, TPk>
where TEntity : class, IEntity<TPk>
where TSession : ISession
{
public IEnumerable<TEntity> GetAll(ISession session = null)
{
return GetAllAsync(session).Result;
}
public async Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null)
{
if (session != null)
{
return await session.FindAsync<TEntity>();
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync<TEntity>();
}
}
}
}
``` |
bbeb1a43-be70-4bec-831b-aa3337246f06 | {
"language": "C#"
} | ```c#
using System;
namespace Arango.Client
{
[AttributeUsage(AttributeTargets.Property)]
public class ArangoProperty : Attribute
{
public string Alias { get; set; }
public bool Serializable { get; set; }
public ArangoProperty()
{
Serializable = true;
}
}
}
```
Add more arango specific attributes. | ```c#
using System;
namespace Arango.Client
{
[AttributeUsage(AttributeTargets.Property)]
public class ArangoProperty : Attribute
{
public bool Serializable { get; set; }
public bool Identity { get; set; }
public bool Key { get; set; }
public bool Revision { get; set; }
public bool From { get; set; }
public bool To { get; set; }
public string Alias { get; set; }
public ArangoProperty()
{
Serializable = true;
Identity = false;
Key = false;
Revision = false;
From = false;
To = false;
}
}
}
``` |
4cb3544f-c637-4a84-ba96-f43fb41cea40 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace Serilog.Sinks.PeriodicBatching
{
class BoundedConcurrentQueue<T>
{
const int NON_BOUNDED = -1;
readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
readonly int _queueLimit;
int _counter;
public BoundedConcurrentQueue()
{
_queueLimit = NON_BOUNDED;
}
public BoundedConcurrentQueue(int queueLimit)
{
if (queueLimit <= 0)
throw new ArgumentOutOfRangeException(nameof(queueLimit), "queue limit must be positive");
_queueLimit = queueLimit;
}
public int Count => _queue.Count;
public bool TryDequeue(out T item)
{
if (_queueLimit == NON_BOUNDED)
return _queue.TryDequeue(out item);
var result = false;
try
{ }
finally // prevent state corrupt while aborting
{
if (_queue.TryDequeue(out item))
{
Interlocked.Decrement(ref _counter);
result = true;
}
}
return result;
}
public bool TryEnqueue(T item)
{
if (_queueLimit == NON_BOUNDED)
{
_queue.Enqueue(item);
return true;
}
var result = true;
try
{ }
finally
{
if (Interlocked.Increment(ref _counter) <= _queueLimit)
{
_queue.Enqueue(item);
}
else
{
Interlocked.Decrement(ref _counter);
result = false;
}
}
return result;
}
}
}
```
Allow NON_BOUNDED value to be used as constructor parameter. | ```c#
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace Serilog.Sinks.PeriodicBatching
{
class BoundedConcurrentQueue<T>
{
const int NON_BOUNDED = -1;
readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
readonly int _queueLimit;
int _counter;
public BoundedConcurrentQueue()
: this(NON_BOUNDED) { }
public BoundedConcurrentQueue(int queueLimit)
{
if (queueLimit <= 0 && queueLimit != NON_BOUNDED)
throw new ArgumentOutOfRangeException(nameof(queueLimit), $"Queue limit must be positive, or {NON_BOUNDED} (to indicate unlimited).");
_queueLimit = queueLimit;
}
public int Count => _queue.Count;
public bool TryDequeue(out T item)
{
if (_queueLimit == NON_BOUNDED)
return _queue.TryDequeue(out item);
var result = false;
try
{ }
finally // prevent state corrupt while aborting
{
if (_queue.TryDequeue(out item))
{
Interlocked.Decrement(ref _counter);
result = true;
}
}
return result;
}
public bool TryEnqueue(T item)
{
if (_queueLimit == NON_BOUNDED)
{
_queue.Enqueue(item);
return true;
}
var result = true;
try
{ }
finally
{
if (Interlocked.Increment(ref _counter) <= _queueLimit)
{
_queue.Enqueue(item);
}
else
{
Interlocked.Decrement(ref _counter);
result = false;
}
}
return result;
}
}
}
``` |
394e3f62-be64-4b3e-9853-63ce5d33616d | {
"language": "C#"
} | ```c#
using System.Linq;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Dangl.WebDocumentation.Models
{
public static class DatabaseInitialization
{
public static void Initialize(ApplicationDbContext Context)
{
SetUpRoles(Context);
}
private static void SetUpRoles(ApplicationDbContext Context)
{
// Add Admin role if not present
if (Context.Roles.All(Role => Role.Name != "Admin"))
{
Context.Roles.Add(new IdentityRole {Name = "Admin"});
Context.SaveChanges();
}
}
}
}```
Fix creation of admin role in DB initialization | ```c#
using System.Linq;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Dangl.WebDocumentation.Models
{
public static class DatabaseInitialization
{
public static void Initialize(ApplicationDbContext Context)
{
SetUpRoles(Context);
}
private static void SetUpRoles(ApplicationDbContext Context)
{
// Add Admin role if not present
if (Context.Roles.All(role => role.Name != "Admin"))
{
Context.Roles.Add(new IdentityRole {Name = "Admin", NormalizedName = "ADMIN"});
Context.SaveChanges();
}
else if (Context.Roles.Any(role => role.Name == "Admin" && role.NormalizedName != "Admin"))
{
var adminRole = Context.Roles.FirstOrDefault(role => role.Name == "Admin");
adminRole.NormalizedName = "ADMIN";
Context.SaveChanges();
}
}
}
}``` |
4e605dd3-1cad-4cfb-ae5f-dbcf47cd9268 | {
"language": "C#"
} | ```c#
using System.Web;
using System.Web.UI;
namespace Unicorn.ControlPanel
{
public class AccessDenied : IControlPanelControl
{
public void Render(HtmlTextWriter writer)
{
writer.Write("<h2>Access Denied</h2>");
writer.Write("<p>You need to <a href=\"/sitecore/admin/login.aspx?ReturnUrl={0}\">sign in to Sitecore as an administrator</a> to use the Unicorn control panel.</p>", HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
}
}
}
```
Send proper 401 for access denied | ```c#
using System.Web;
using System.Web.UI;
namespace Unicorn.ControlPanel
{
public class AccessDenied : IControlPanelControl
{
public void Render(HtmlTextWriter writer)
{
writer.Write("<h2>Access Denied</h2>");
writer.Write("<p>You need to <a href=\"/sitecore/admin/login.aspx?ReturnUrl={0}\">sign in to Sitecore as an administrator</a> to use the Unicorn control panel.</p>", HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
HttpContext.Current.Response.StatusCode = 401;
}
}
}
``` |
59a12a95-3262-4f45-b4ff-9ac6db67188e | {
"language": "C#"
} | ```c#
using System;
namespace KnckoutBindingGenerater
{
public class KnockoutProxy
{
private readonly string m_ViewModelName;
private readonly string m_PrimitiveObservables;
private readonly string m_MethodProxies;
private readonly string m_CollectionObservables;
const string c_ViewModelTemplate = @"
var {0}ProxyObject = function() {{
{1}
{2}
{3}
}}
window.{4} = new {0}ProxyObject();
ko.applyBindings({4});
";
public KnockoutProxy(string viewModelName, string primitiveObservables, string methodProxies, string collectionObservables)
{
m_ViewModelName = viewModelName;
m_PrimitiveObservables = primitiveObservables;
m_MethodProxies = methodProxies;
m_CollectionObservables = collectionObservables;
}
public string KnockoutViewModel
{
get
{
return String.Format(c_ViewModelTemplate,
m_ViewModelName,
m_PrimitiveObservables,
m_MethodProxies,
m_CollectionObservables,
ViewModelInstanceName);
}
}
public string ViewModelInstanceName
{
get { return "kevin"; }
}
}
}```
Remove this last piece of hardcodedness | ```c#
using System;
namespace KnckoutBindingGenerater
{
public class KnockoutProxy
{
private readonly string m_ViewModelName;
private readonly string m_PrimitiveObservables;
private readonly string m_MethodProxies;
private readonly string m_CollectionObservables;
const string c_ViewModelTemplate = @"
var {0}ProxyObject = function() {{
{1}
{2}
{3}
}}
window.{4} = new {0}ProxyObject();
ko.applyBindings({4});
";
public KnockoutProxy(string viewModelName, string primitiveObservables, string methodProxies, string collectionObservables)
{
m_ViewModelName = viewModelName;
m_PrimitiveObservables = primitiveObservables;
m_MethodProxies = methodProxies;
m_CollectionObservables = collectionObservables;
}
public string KnockoutViewModel
{
get
{
return String.Format(c_ViewModelTemplate,
m_ViewModelName,
m_PrimitiveObservables,
m_MethodProxies,
m_CollectionObservables,
ViewModelInstanceName);
}
}
public string ViewModelInstanceName
{
get { return String.Format("{0}ProxyObjectInstance", m_ViewModelName); }
}
}
}``` |
6dc2d6ca-2481-4431-9e82-318fd239bae1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;
namespace Reni.FeatureTest.Reference
{
[TestFixture]
[ArrayElementType]
[TargetSet(@"
text: 'abcdefghijklmnopqrstuvwxyz';
pointer: ((text type >>)*1) array_reference instance (text);
(pointer >> 7) dump_print;
(pointer >> 0) dump_print;
(pointer >> 11) dump_print;
(pointer >> 11) dump_print;
(pointer >> 14) dump_print;
", "hallo")]
public sealed class ArrayReferenceByInstance : CompilerTest {}
}```
Access operator for array is now "item" | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;
namespace Reni.FeatureTest.Reference
{
[TestFixture]
[ArrayElementType]
[TargetSet(@"
text: 'abcdefghijklmnopqrstuvwxyz';
pointer: ((text type item)*1) array_reference instance (text);
pointer item(7) dump_print;
pointer item(0) dump_print;
pointer item(11) dump_print;
pointer item(11) dump_print;
pointer item(14) dump_print;
", "hallo")]
public sealed class ArrayReferenceByInstance : CompilerTest {}
}``` |
460e4d75-c5fd-481e-b4a9-31950b02f2ce | {
"language": "C#"
} | ```c#
using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
namespace SFA.DAS.CommitmentsV2.Api.Client
{
public interface ICommitmentsApiClient
{
Task<bool> HealthCheck();
Task<AccountLegalEntityResponse> GetLegalEntity(long accountLegalEntityId, CancellationToken cancellationToken = default);
// To be removed latter
Task<string> SecureCheck();
Task<string> SecureEmployerCheck();
Task<string> SecureProviderCheck();
Task<CreateCohortResponse> CreateCohort(CreateCohortRequest request, CancellationToken cancellationToken = default);
Task<UpdateDraftApprenticeshipResponse> UpdateDraftApprenticeship(long cohortId, long apprenticeshipId, UpdateDraftApprenticeshipRequest request, CancellationToken cancellationToken = default);
}
}
```
Add missing client method to interface | ```c#
using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
namespace SFA.DAS.CommitmentsV2.Api.Client
{
public interface ICommitmentsApiClient
{
Task<bool> HealthCheck();
Task<AccountLegalEntityResponse> GetLegalEntity(long accountLegalEntityId, CancellationToken cancellationToken = default);
// To be removed latter
Task<string> SecureCheck();
Task<string> SecureEmployerCheck();
Task<string> SecureProviderCheck();
Task<CreateCohortResponse> CreateCohort(CreateCohortRequest request, CancellationToken cancellationToken = default);
Task<UpdateDraftApprenticeshipResponse> UpdateDraftApprenticeship(long cohortId, long apprenticeshipId, UpdateDraftApprenticeshipRequest request, CancellationToken cancellationToken = default);
Task<GetCohortResponse> GetCohort(long cohortId, CancellationToken cancellationToken = default);
}
}
``` |
a3038da3-2bb1-4871-89d1-56e1aece763e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Threading;
namespace ProjectExtensions.Azure.ServiceBus.Tests.Unit {
[TestFixture]
public class SampleTest {
[Test]
public void Test() {
Thread.Sleep(30000);
Assert.IsTrue(true);
}
}
}
```
Set pause to 2 seconds so we can watch the mock run | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Threading;
namespace ProjectExtensions.Azure.ServiceBus.Tests.Unit {
[TestFixture]
public class SampleTest {
[Test]
public void Test() {
Thread.Sleep(2000);
Assert.IsTrue(true);
}
}
}
``` |
ef3f080c-abe2-4669-b080-16f121d6faf8 | {
"language": "C#"
} | ```c#
using Subtle.Model;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
namespace Subtle.Registry
{
[RunInstaller(true)]
public partial class Installer : System.Configuration.Install.Installer
{
public Installer()
{
InitializeComponent();
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
if (!Context.Parameters.ContainsKey("targetdir"))
{
throw new InstallException("Missing 'targetdir' parameter");
}
var targetDir = Context.Parameters["targetdir"].TrimEnd(Path.DirectorySeparatorChar);
RegistryHelper.SetShellCommands(
FileTypes.VideoTypes,
Path.Combine(targetDir, "Subtle.exe"),
Path.Combine(targetDir, "Subtle.ico"));
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
//RegistryHelper.DeleteShellCommands(FileTypes.VideoTypes);
}
}
}```
Create const for targetdir key | ```c#
using Subtle.Model;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
namespace Subtle.Registry
{
[RunInstaller(true)]
public partial class Installer : System.Configuration.Install.Installer
{
private const string TargetDirKey = "targetdir";
public Installer()
{
InitializeComponent();
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
if (!Context.Parameters.ContainsKey(TargetDirKey))
{
throw new InstallException($"Missing '{TargetDirKey}' parameter");
}
var targetDir = Context.Parameters[TargetDirKey].TrimEnd(Path.DirectorySeparatorChar);
RegistryHelper.SetShellCommands(
FileTypes.VideoTypes,
Path.Combine(targetDir, "Subtle.exe"),
Path.Combine(targetDir, "Subtle.ico"));
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
//RegistryHelper.DeleteShellCommands(FileTypes.VideoTypes);
}
}
}``` |
a2f5130d-c040-4297-a261-50809041e60e | {
"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.Graphics;
using osu.Framework.Graphics.Cursor;
#nullable enable
namespace osu.Framework.Extensions
{
public static class PopoverExtensions
{
/// <summary>
/// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover);
/// <summary>
/// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null);
private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target)
{
var popoverContainer = origin.FindClosestParent<PopoverContainer>()
?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy");
popoverContainer.SetTarget(target);
}
}
}
```
Allow `HidePopover()` to be called directly on popover containers | ```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.Graphics;
using osu.Framework.Graphics.Cursor;
#nullable enable
namespace osu.Framework.Extensions
{
public static class PopoverExtensions
{
/// <summary>
/// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover);
/// <summary>
/// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null);
private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target)
{
var popoverContainer = origin as PopoverContainer
?? origin.FindClosestParent<PopoverContainer>()
?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy");
popoverContainer.SetTarget(target);
}
}
}
``` |
54e028c4-a1a5-472b-a1cd-75b7692fb815 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Roton.Emulation
{
internal class ExecuteCodeContext : ICodeSeekable
{
private ICodeSeekable _instructionSource;
public ExecuteCodeContext(int index, ICodeSeekable instructionSource, string name)
{
_instructionSource = instructionSource;
this.Index = index;
this.Name = name;
}
public Actor Actor
{
get;
set;
}
public int CommandsExecuted
{
get;
set;
}
public bool Died
{
get;
set;
}
public bool Finished
{
get;
set;
}
public int Index
{
get;
set;
}
public int Instruction
{
get { return _instructionSource.Instruction; }
set { _instructionSource.Instruction = value; }
}
public string Message
{
get;
set;
}
public bool Moved
{
get;
set;
}
public string Name
{
get;
set;
}
public int PreviousInstruction
{
get;
set;
}
public bool Repeat
{
get;
set;
}
}
}
```
Add NextLine to execution context | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Roton.Emulation
{
internal class ExecuteCodeContext : ICodeSeekable
{
private ICodeSeekable _instructionSource;
public ExecuteCodeContext(int index, ICodeSeekable instructionSource, string name)
{
_instructionSource = instructionSource;
this.Index = index;
this.Name = name;
}
public Actor Actor
{
get;
set;
}
public int CommandsExecuted
{
get;
set;
}
public bool Died
{
get;
set;
}
public bool Finished
{
get;
set;
}
public int Index
{
get;
set;
}
public int Instruction
{
get { return _instructionSource.Instruction; }
set { _instructionSource.Instruction = value; }
}
public string Message
{
get;
set;
}
public bool Moved
{
get;
set;
}
public string Name
{
get;
set;
}
public bool NextLine
{
get;
set;
}
public int PreviousInstruction
{
get;
set;
}
public bool Repeat
{
get;
set;
}
}
}
``` |
dc288467-4015-4656-a4fb-bb4b920d02ed | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YuukaWaterController : MonoBehaviour {
public int requiredCompletion = 3;
int completionCounter = 0;
public delegate void VictoryAction();
public static event VictoryAction OnVictory;
public void Notify() {
completionCounter++;
if (completionCounter >= requiredCompletion) {
MicrogameController.instance.setVictory(true, true);
OnVictory();
}
}
private void OnDestroy() {
OnVictory = null;
}
}
```
Fix victory delegate clearing in stage | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YuukaWaterController : MonoBehaviour {
public int requiredCompletion = 3;
int completionCounter = 0;
public delegate void VictoryAction();
public static event VictoryAction OnVictory;
private void Awake()
{
OnVictory = null;
}
public void Notify() {
completionCounter++;
if (completionCounter >= requiredCompletion) {
MicrogameController.instance.setVictory(true, true);
OnVictory();
}
}
}
``` |
67601983-1606-4c92-8d0e-4022a484c727 | {
"language": "C#"
} | ```c#
#r "Newtonsoft.Json"
using System;
using Red_Folder.WebCrawl;
using Red_Folder.WebCrawl.Data;
using Red_Folder.Logging;
using Newtonsoft.Json;
public static void Run(string request, out object outputDocument, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {crawlRequest.Id}");
var azureLogger = new AzureLogger(log);
var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request);
var crawler = new Crawler(crawlRequest, azureLogger);
crawler.AddUrl("https://www.red-folder.com/sitemap.xml");
var crawlResult = crawler.Crawl();
outputDocument = crawlResult;
}
public class AzureLogger : ILogger
{
private TraceWriter _log;
public AzureLogger(TraceWriter log)
{
_log = log;
}
public void Info(string message)
{
_log.Info(message);
}
}
```
Change sitemap.xml to reference requested host | ```c#
#r "Newtonsoft.Json"
using System;
using Red_Folder.WebCrawl;
using Red_Folder.WebCrawl.Data;
using Red_Folder.Logging;
using Newtonsoft.Json;
public static void Run(string request, out object outputDocument, TraceWriter log)
{
var crawlRequest = JsonConvert.DeserializeObject<CrawlRequest>(request);
log.Info($"C# Queue trigger function processed: {crawlRequest.Id}");
var azureLogger = new AzureLogger(log);
var crawler = new Crawler(crawlRequest, azureLogger);
crawler.AddUrl($"{crawlRequest.Host}/sitemap.xml");
var crawlResult = crawler.Crawl();
outputDocument = crawlResult;
}
public class AzureLogger : ILogger
{
private TraceWriter _log;
public AzureLogger(TraceWriter log)
{
_log = log;
}
public void Info(string message)
{
_log.Info(message);
}
}
``` |
752cbcb9-3fbc-440d-9eb3-31d56cb95e60 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SampleProject.Domain.Products;
using SampleProject.Domain.SharedKernel;
namespace SampleProject.Application.Orders.PlaceCustomerOrder
{
public static class ProductPriceProvider
{
public static async Task<List<ProductPriceData>> GetAllProductPrices(IDbConnection connection)
{
var productPrices = await connection.QueryAsync<ProductPriceResponse>("SELECT " +
$"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " +
$"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " +
$"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " +
"FROM orders.v_ProductPrices AS [ProductPrice]");
return productPrices.AsList()
.Select(x => new ProductPriceData(
new ProductId(x.ProductId),
MoneyValue.Of(x.Value, x.Currency)))
.ToList();
}
private sealed class ProductPriceResponse
{
public Guid ProductId { get; set; }
public decimal Value { get; set; }
public string Currency { get; set; }
}
}
}```
Fix bug with querying ProductPrices in SampleAPI case study | ```c#
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SampleProject.Domain.Products;
using SampleProject.Domain.SharedKernel;
namespace SampleProject.Application.Orders.PlaceCustomerOrder
{
public static class ProductPriceProvider
{
public static async Task<List<ProductPriceData>> GetAllProductPrices(IDbConnection connection)
{
var productPrices = await connection.QueryAsync<ProductPriceResponse>("SELECT " +
$"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " +
$"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " +
$"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " +
"FROM orders.ProductPrices AS [ProductPrice]");
return productPrices.AsList()
.Select(x => new ProductPriceData(
new ProductId(x.ProductId),
MoneyValue.Of(x.Value, x.Currency)))
.ToList();
}
private sealed class ProductPriceResponse
{
public Guid ProductId { get; set; }
public decimal Value { get; set; }
public string Currency { get; set; }
}
}
}``` |
41f9784e-3c20-4b57-aed3-6baf645927fe | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Configuration;
using osu.Framework.IO.Stores;
namespace osu.Framework.Localisation
{
public partial class LocalisationManager
{
private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString
{
private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>();
private LocalisableString text;
public LocalisedBindableString(IBindable<IResourceStore<string>> storage)
{
this.storage.BindTo(storage);
this.storage.BindValueChanged(_ => updateValue(), true);
}
private void updateValue()
{
string newText = text.Text;
if (text.ShouldLocalise && storage.Value != null)
newText = storage.Value.Get(newText);
if (text.Args != null && !string.IsNullOrEmpty(newText))
{
try
{
newText = string.Format(newText, text.Args);
}
catch (FormatException)
{
// Prevent crashes if the formatting fails. The string will be in a non-formatted state.
}
}
Value = newText;
}
LocalisableString ILocalisedBindableString.Original
{
set
{
text = value;
updateValue();
}
}
}
}
}
```
Reduce potential value updates when setting localisablestring | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Configuration;
using osu.Framework.IO.Stores;
namespace osu.Framework.Localisation
{
public partial class LocalisationManager
{
private class LocalisedBindableString : Bindable<string>, ILocalisedBindableString
{
private readonly IBindable<IResourceStore<string>> storage = new Bindable<IResourceStore<string>>();
private LocalisableString text;
public LocalisedBindableString(IBindable<IResourceStore<string>> storage)
{
this.storage.BindTo(storage);
this.storage.BindValueChanged(_ => updateValue(), true);
}
private void updateValue()
{
string newText = text.Text;
if (text.ShouldLocalise && storage.Value != null)
newText = storage.Value.Get(newText);
if (text.Args != null && !string.IsNullOrEmpty(newText))
{
try
{
newText = string.Format(newText, text.Args);
}
catch (FormatException)
{
// Prevent crashes if the formatting fails. The string will be in a non-formatted state.
}
}
Value = newText;
}
LocalisableString ILocalisedBindableString.Original
{
set
{
if (text == value)
return;
text = value;
updateValue();
}
}
}
}
}
``` |
4c9d59cb-2a62-41a4-ae94-6c7f0816d733 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
```
Create server side API for single multiple answer question | ```c#
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
/// <summary>
/// Adding single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
}
}
``` |
3c8018e4-1a19-4c5f-aa4e-f4b9ea764fad | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Movies.Common;
internal class TraktMoviesTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingMovie>, TraktTrendingMovie>
{
internal TraktMoviesTrendingRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "movies/trending{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
```
Add filter property to trending movies request. | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Movies.Common;
internal class TraktMoviesTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingMovie>, TraktTrendingMovie>
{
internal TraktMoviesTrendingRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "movies/trending{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktMovieFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
``` |
98bac33e-303c-4fe3-9d53-4d58d89398e8 | {
"language": "C#"
} | ```c#
using System;
using System.Web;
namespace Canonicalize
{
internal static class HttpRequestBaseExtensions
{
public static Uri GetOriginalUrl(this HttpRequestBase request)
{
if (request.Url == null || request.Headers == null)
{
return request.Url;
}
var uriBuilder = new UriBuilder(request.Url);
var forwardedProtocol = request.Headers["X-Forwarded-Proto"];
if (forwardedProtocol != null)
{
uriBuilder.Scheme = forwardedProtocol;
}
var hostHeader = request.Headers["X-Forwarded-Host"] ?? request.Headers["Host"];
if (hostHeader != null)
{
var parsedHost = new Uri(uriBuilder.Scheme + Uri.SchemeDelimiter + hostHeader);
uriBuilder.Host = parsedHost.Host;
uriBuilder.Port = parsedHost.Port;
}
return uriBuilder.Uri;
}
}
}
```
Add XML documentation to extension method HttpRequestBase.GetOriginalUrl() and make the method public. | ```c#
using System;
using System.Web;
namespace Canonicalize
{
/// <summary>
/// Adds extension methods on <see cref="HttpRequestBase"/>.
/// </summary>
public static class HttpRequestBaseExtensions
{
/// <summary>
/// Gets the original URL requested by the client, without artifacts from proxies or load balancers.
/// In particular HTTP headers Host, X-Forwarded-Host, X-Forwarded-Proto are applied on top of <see cref="HttpRequestBase.Url"/>.
/// </summary>
/// <param name="request">The request for which the original URL should be computed.</param>
/// <returns>The original URL requested by the client.</returns>
public static Uri GetOriginalUrl(this HttpRequestBase request)
{
if (request.Url == null || request.Headers == null)
{
return request.Url;
}
var uriBuilder = new UriBuilder(request.Url);
var forwardedProtocol = request.Headers["X-Forwarded-Proto"];
if (forwardedProtocol != null)
{
uriBuilder.Scheme = forwardedProtocol;
}
var hostHeader = request.Headers["X-Forwarded-Host"] ?? request.Headers["Host"];
if (hostHeader != null)
{
var parsedHost = new Uri(uriBuilder.Scheme + Uri.SchemeDelimiter + hostHeader);
uriBuilder.Host = parsedHost.Host;
uriBuilder.Port = parsedHost.Port;
}
return uriBuilder.Uri;
}
}
}
``` |
9630eb4a-3899-4d3a-8136-254787dc6fd1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace JabberBCIT {
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
```
Add routing rules for profile | ```c#
using System.Web.Mvc;
using System.Web.Routing;
namespace JabberBCIT
{
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "EditProfile",
url: "Profile/Edit/{id}",
defaults: new { controller = "Manage", action = "Edit" }
);
routes.MapRoute(
name: "Profile",
url: "Profile/{id}",
defaults: new { controller = "Manage", action = "Index"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
``` |
643e77b1-c463-4d13-9a37-c72bf666876f | {
"language": "C#"
} | ```c#
namespace Htc.Vita.Core.Diagnostics
{
public partial class LocationManager
{
/// <summary>
/// Class LocationInfo.
/// </summary>
public class LocationInfo
{
/// <summary>
/// Gets or sets the country code alpha2.
/// </summary>
/// <value>The country code alpha2.</value>
public string CountryCodeAlpha2 { get; set; }
/// <summary>
/// Gets or sets the provider name.
/// </summary>
/// <value>The provider name.</value>
public string ProviderName { get; set; }
/// <summary>
/// Gets or sets the provider type.
/// </summary>
/// <value>The provider type.</value>
public LocationProviderType ProviderType { get; set; } = LocationProviderType.Unknown;
}
/// <summary>
/// Enum LocationProviderType
/// </summary>
public enum LocationProviderType
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Provided by operating system
/// </summary>
OperatingSystem,
/// <summary>
/// Provided by network
/// </summary>
Network,
/// <summary>
/// Provided by user
/// </summary>
User
}
}
}
```
Add provider name and provider type into LocationInfo, part 2 | ```c#
namespace Htc.Vita.Core.Diagnostics
{
public partial class LocationManager
{
/// <summary>
/// Class LocationInfo.
/// </summary>
public class LocationInfo
{
/// <summary>
/// Gets or sets the country code alpha2.
/// </summary>
/// <value>The country code alpha2.</value>
public string CountryCodeAlpha2 { get; set; }
/// <summary>
/// Gets or sets the provider name.
/// </summary>
/// <value>The provider name.</value>
public string ProviderName { get; set; }
/// <summary>
/// Gets or sets the provider type.
/// </summary>
/// <value>The provider type.</value>
public LocationProviderType ProviderType { get; set; } = LocationProviderType.Unknown;
}
/// <summary>
/// Enum LocationProviderType
/// </summary>
public enum LocationProviderType
{
/// <summary>
/// Unknown
/// </summary>
Unknown,
/// <summary>
/// Provided by operating system
/// </summary>
OperatingSystem,
/// <summary>
/// Provided by network
/// </summary>
Network,
/// <summary>
/// Provided by user
/// </summary>
User,
/// <summary>
/// The external application
/// </summary>
ExternalApplication
}
}
}
``` |
bb55d98d-4334-4c6d-8265-5a8ecdf81af3 | {
"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 Xunit;
namespace System.Globalization.Tests
{
public class DateTimeFormatInfoReadOnly
{
public static IEnumerable<object[]> ReadOnly_TestData()
{
yield return new object[] { DateTimeFormatInfo.InvariantInfo, true };
yield return new object[] { new DateTimeFormatInfo(), false };
yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false };
}
[Theory]
[MemberData(nameof(ReadOnly_TestData))]
public void ReadOnly(DateTimeFormatInfo format, bool expected)
{
Assert.Equal(expected, format.IsReadOnly);
DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format);
Assert.True(readOnlyFormat.IsReadOnly);
}
[Fact]
public void ReadOnly_Null_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("dtfi", () => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null
}
}
}
```
Add tests for sameness in DateTimeFormatInfo | ```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 Xunit;
namespace System.Globalization.Tests
{
public class DateTimeFormatInfoReadOnly
{
public static IEnumerable<object[]> ReadOnly_TestData()
{
yield return new object[] { DateTimeFormatInfo.InvariantInfo, true };
yield return new object[] { DateTimeFormatInfo.ReadOnly(new DateTimeFormatInfo()), true };
yield return new object[] { new DateTimeFormatInfo(), false };
yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false };
}
[Theory]
[MemberData(nameof(ReadOnly_TestData))]
public void ReadOnly(DateTimeFormatInfo format, bool originalFormatIsReadOnly)
{
Assert.Equal(originalFormatIsReadOnly, format.IsReadOnly);
DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format);
if (originalFormatIsReadOnly)
{
Assert.Same(format, readOnlyFormat);
}
else
{
Assert.NotSame(format, readOnlyFormat);
}
Assert.True(readOnlyFormat.IsReadOnly);
}
[Fact]
public void ReadOnly_Null_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("dtfi", () => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null
}
}
}
``` |
32974cea-b640-4e4b-b1b6-dc1157a83fbe | {
"language": "C#"
} | ```c#
using System;
using FullSerializer.Internal;
using NUnit.Framework;
using System.Collections.Generic;
namespace FullSerializer.Tests {
[fsObject(Converter = typeof(MyConverter))]
public class MyModel {
}
public class MyConverter : fsConverter {
public static bool DidSerialize = false;
public static bool DidDeserialize = false;
public override bool CanProcess(Type type) {
throw new NotSupportedException();
}
public override object CreateInstance(fsData data, Type storageType) {
return new MyModel();
}
public override fsFailure TrySerialize(object instance, out fsData serialized, Type storageType) {
DidSerialize = true;
serialized = new fsData();
return fsFailure.Success;
}
public override fsFailure TryDeserialize(fsData data, ref object instance, Type storageType) {
DidDeserialize = true;
return fsFailure.Success;
}
}
public class SpecifiedConverterTests {
[Test]
public void VerifyConversion() {
var serializer = new fsSerializer();
fsData result;
serializer.TrySerialize(new MyModel(), out result);
Assert.IsTrue(MyConverter.DidSerialize);
Assert.IsFalse(MyConverter.DidDeserialize);
MyConverter.DidSerialize = false;
object resultObj = null;
serializer.TryDeserialize(result, typeof (MyModel), ref resultObj);
Assert.IsFalse(MyConverter.DidSerialize);
Assert.IsTrue(MyConverter.DidDeserialize);
}
}
}```
Fix running test multiple times in same .NET runtime instance | ```c#
using System;
using FullSerializer.Internal;
using NUnit.Framework;
using System.Collections.Generic;
namespace FullSerializer.Tests {
[fsObject(Converter = typeof(MyConverter))]
public class MyModel {
}
public class MyConverter : fsConverter {
public static bool DidSerialize = false;
public static bool DidDeserialize = false;
public override bool CanProcess(Type type) {
throw new NotSupportedException();
}
public override object CreateInstance(fsData data, Type storageType) {
return new MyModel();
}
public override fsFailure TrySerialize(object instance, out fsData serialized, Type storageType) {
DidSerialize = true;
serialized = new fsData();
return fsFailure.Success;
}
public override fsFailure TryDeserialize(fsData data, ref object instance, Type storageType) {
DidDeserialize = true;
return fsFailure.Success;
}
}
public class SpecifiedConverterTests {
[Test]
public void VerifyConversion() {
MyConverter.DidDeserialize = false;
MyConverter.DidSerialize = false;
var serializer = new fsSerializer();
fsData result;
serializer.TrySerialize(new MyModel(), out result);
Assert.IsTrue(MyConverter.DidSerialize);
Assert.IsFalse(MyConverter.DidDeserialize);
MyConverter.DidSerialize = false;
object resultObj = null;
serializer.TryDeserialize(result, typeof (MyModel), ref resultObj);
Assert.IsFalse(MyConverter.DidSerialize);
Assert.IsTrue(MyConverter.DidDeserialize);
}
}
}``` |
87b4ccd0-3205-4ca6-8b56-c4b6445f6db0 | {
"language": "C#"
} | ```c#
namespace Stripe
{
using Newtonsoft.Json;
public class CreditNoteListOptions : ListOptions
{
/// <summary>
/// ID of the invoice.
/// </summary>
[JsonProperty("invoice")]
public string InvoiceId { get; set; }
}
}
```
Add Customer filter when listing CreditNote | ```c#
namespace Stripe
{
using Newtonsoft.Json;
public class CreditNoteListOptions : ListOptions
{
/// <summary>
/// ID of the customer.
/// </summary>
[JsonProperty("customer")]
public string CustomerId { get; set; }
/// <summary>
/// ID of the invoice.
/// </summary>
[JsonProperty("invoice")]
public string InvoiceId { get; set; }
}
}
``` |
e38dfcaa-9525-42b9-9416-4c1716a56713 | {
"language": "C#"
} | ```c#
using System;
namespace MQTTnet.Core.Diagnostics
{
public static class MqttTrace
{
public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
public static void Verbose(string source, string message)
{
Publish(source, MqttTraceLevel.Verbose, null, message);
}
public static void Information(string source, string message)
{
Publish(source, MqttTraceLevel.Information, null, message);
}
public static void Warning(string source, string message)
{
Publish(source, MqttTraceLevel.Warning, null, message);
}
public static void Warning(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Warning, exception, message);
}
public static void Error(string source, string message)
{
Publish(source, MqttTraceLevel.Error, null, message);
}
public static void Error(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Error, exception, message);
}
private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
{
TraceMessagePublished?.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
}
}
}
```
Make string format optional if no trace listener is attached | ```c#
using System;
namespace MQTTnet.Core.Diagnostics
{
public static class MqttTrace
{
public static event EventHandler<MqttTraceMessagePublishedEventArgs> TraceMessagePublished;
public static void Verbose(string source, string message)
{
Publish(source, MqttTraceLevel.Verbose, null, message);
}
public static void Information(string source, string message)
{
Publish(source, MqttTraceLevel.Information, null, message);
}
public static void Warning(string source, string message)
{
Publish(source, MqttTraceLevel.Warning, null, message);
}
public static void Warning(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Warning, exception, message);
}
public static void Error(string source, string message)
{
Publish(source, MqttTraceLevel.Error, null, message);
}
public static void Error(string source, Exception exception, string message)
{
Publish(source, MqttTraceLevel.Error, exception, message);
}
private static void Publish(string source, MqttTraceLevel traceLevel, Exception exception, string message)
{
var handler = TraceMessagePublished;
if (handler == null)
{
return;
}
message = string.Format(message, 1);
handler.Invoke(null, new MqttTraceMessagePublishedEventArgs(Environment.CurrentManagedThreadId, source, traceLevel, message, exception));
}
}
}
``` |
09b7e553-b37c-476b-865a-1350be5980e3 | {
"language": "C#"
} | ```c#
using System;
namespace Sep.Git.Tfs
{
public static class GitTfsExitCodes
{
public const int OK = 0;
public const int Help = 1;
public const int InvalidArguments = 2;
public const int ForceRequired = 3;
public const int ExceptionThrown = Byte.MaxValue - 1;
}
}
```
Add rationale for exit status codes to comments. | ```c#
using System;
namespace Sep.Git.Tfs
{
/// <summary>
/// Collection of exit codes used by git-tfs.
/// </summary>
/// <remarks>
/// For consistency across all running environments, both various
/// Windows - shells (powershell.exe, cmd.exe) and UNIX - like environments
/// such as bash (MinGW), sh or zsh avoid using negative exit status codes
/// or codes 255 or higher.
///
/// Some running environments might either modulo exit codes with 256 or clamp
/// them to interval [0, 255].
///
/// For more information:
/// http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
/// http://tldp.org/LDP/abs/html/exitcodes.html
/// </remarks>
public static class GitTfsExitCodes
{
public const int OK = 0;
public const int Help = 1;
public const int InvalidArguments = 2;
public const int ForceRequired = 3;
public const int ExceptionThrown = Byte.MaxValue - 1;
}
}
``` |
90cb53b1-0070-415d-aa73-0734d0f366b4 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
namespace CroquetAustralia.DownloadTournamentEntries.ReadModels
{
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
public class FunctionReadModel
{
public FunctionReadModel(EntrySubmittedReadModel entrySubmitted, Tournament tournament, SubmitEntry.LineItem lineItem)
{
TournamentItem = tournament.Functions.First(f => f.Id == lineItem.Id);
EntrySubmitted = entrySubmitted;
LineItem = lineItem;
}
public EntrySubmittedReadModel EntrySubmitted { get; }
public SubmitEntry.LineItem LineItem { get; }
public TournamentItem TournamentItem { get; }
}
}```
Improve exception handling when function does not exist | ```c#
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.Features.TournamentEntry.Commands;
namespace CroquetAustralia.DownloadTournamentEntries.ReadModels
{
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
public class FunctionReadModel
{
public FunctionReadModel(EntrySubmittedReadModel entrySubmitted, Tournament tournament, SubmitEntry.LineItem lineItem)
{
TournamentItem = FindFirstFunction(tournament, lineItem);
EntrySubmitted = entrySubmitted;
LineItem = lineItem;
}
private static TournamentItem FindFirstFunction(Tournament tournament, SubmitEntry.LineItem lineItem)
{
try
{
return tournament.Functions.First(f => f.Id == lineItem.Id);
}
catch (Exception e)
{
throw new Exception($"Cannot find function '{lineItem.Id}' in tournament '{tournament.Title}'.", e);
}
}
public EntrySubmittedReadModel EntrySubmitted { get; }
public SubmitEntry.LineItem LineItem { get; }
public TournamentItem TournamentItem { get; }
}
}``` |
41a2c421-5ad3-48c0-9635-b8f52ba0a078 | {
"language": "C#"
} | ```c#
using Microsoft.Extensions.Options;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.IO;
namespace Umbraco.Core.Runtime
{
public class CoreInitialComponent : IComponent
{
private readonly IIOHelper _ioHelper;
private readonly GlobalSettings _globalSettings;
public CoreInitialComponent(IIOHelper ioHelper, IOptions<GlobalSettings> globalSettings)
{
_ioHelper = ioHelper;
_globalSettings = globalSettings.Value;
}
public void Initialize()
{
// ensure we have some essential directories
// every other component can then initialize safely
_ioHelper.EnsurePathExists(Constants.SystemDirectories.Data);
_ioHelper.EnsurePathExists(_globalSettings.UmbracoMediaPath);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.MvcViews);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.PartialViews);
_ioHelper.EnsurePathExists(Constants.SystemDirectories.MacroPartials);
}
public void Terminate()
{ }
}
}
```
Update Ensure calls to use full path | ```c#
using Microsoft.Extensions.Options;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.Models;
using Umbraco.Core.Hosting;
using Umbraco.Core.IO;
namespace Umbraco.Core.Runtime
{
public class CoreInitialComponent : IComponent
{
private readonly IIOHelper _ioHelper;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly GlobalSettings _globalSettings;
public CoreInitialComponent(IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, IOptions<GlobalSettings> globalSettings)
{
_ioHelper = ioHelper;
_hostingEnvironment = hostingEnvironment;
_globalSettings = globalSettings.Value;
}
public void Initialize()
{
// ensure we have some essential directories
// every other component can then initialize safely
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.Data));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathWebRoot(_globalSettings.UmbracoMediaPath));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MvcViews));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.PartialViews));
_ioHelper.EnsurePathExists(_hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.MacroPartials));
}
public void Terminate()
{ }
}
}
``` |
741afb93-ee29-4bd3-b461-bab49fd0f0e3 | {
"language": "C#"
} | ```c#
namespace BlockchainSharp.Tests.Processors
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BlockchainSharp.Stores;
using BlockchainSharp.Processors;
using BlockchainSharp.Tests.TestUtils;
using BlockchainSharp.Core;
[TestClass]
public class MinerProcessorTests
{
[TestMethod]
public void MineBlock()
{
TransactionPool transactionPool = new TransactionPool();
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(0, block.Transactions.Count);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
[TestMethod]
public void MineBlockWithTransaction()
{
TransactionPool transactionPool = new TransactionPool();
Transaction transaction = FactoryHelper.CreateTransaction(1000);
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(1, block.Transactions.Count);
Assert.AreSame(transaction, block.Transactions[0]);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
}
}
```
Fix test, mine block with transaction | ```c#
namespace BlockchainSharp.Tests.Processors
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BlockchainSharp.Stores;
using BlockchainSharp.Processors;
using BlockchainSharp.Tests.TestUtils;
using BlockchainSharp.Core;
[TestClass]
public class MinerProcessorTests
{
[TestMethod]
public void MineBlock()
{
TransactionPool transactionPool = new TransactionPool();
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(0, block.Transactions.Count);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
[TestMethod]
public void MineBlockWithTransaction()
{
TransactionPool transactionPool = new TransactionPool();
Transaction transaction = FactoryHelper.CreateTransaction(1000);
transactionPool.AddTransaction(transaction);
MinerProcessor processor = new MinerProcessor(transactionPool);
Block genesis = FactoryHelper.CreateGenesisBlock();
Block block = processor.MineBlock(genesis);
Assert.IsNotNull(block);
Assert.AreEqual(1, block.Number);
Assert.AreEqual(1, block.Transactions.Count);
Assert.AreSame(transaction, block.Transactions[0]);
Assert.AreEqual(genesis.Hash, block.ParentHash);
}
}
}
``` |
9213915c-ecd7-407e-aaf9-fdd2827632cd | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Windows.Data;
namespace NuGet.Dialog.PackageManagerUI
{
public class StringCollectionsToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(string))
{
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
else
{
IEnumerable<string> parts = (IEnumerable<string>)value;
return String.Join(", ", parts);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
```
Add a safety check for when Authors is null, which shouldn't happen in the first place. Work items: 1727, 1728 | ```c#
using System;
using System.Collections.Generic;
using System.Windows.Data;
namespace NuGet.Dialog.PackageManagerUI
{
public class StringCollectionsToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(string))
{
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
else if (value == null)
{
return String.Empty;
}
{
IEnumerable<string> parts = (IEnumerable<string>)value;
return String.Join(", ", parts);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
``` |
8eae0a5e-e4a4-4cf6-a3c6-b252d9108ce7 | {
"language": "C#"
} | ```c#
using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using SO115App.API.Models.Servizi.CQRS.Queries.ListaEventi;
using SO115App.Models.Servizi.Infrastruttura.GetListaEventi;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Persistence.MongoDB.GestioneInterventi
{
public class GetListaEventiByCodiceRichiesta : IGetListaEventi
{
private readonly DbContext _dbContext;
public GetListaEventiByCodiceRichiesta(DbContext dbContext)
{
_dbContext = dbContext;
}
public List<Evento> Get(ListaEventiQuery query)
{
return (List<Evento>)_dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Eq(x => x.Id, query.IdRichiesta)).Single().Eventi;
}
}
}
```
Fix - Cambiata chiave degli eventi da id richiesta a codice | ```c#
using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using SO115App.API.Models.Servizi.CQRS.Queries.ListaEventi;
using SO115App.Models.Servizi.Infrastruttura.GetListaEventi;
using System;
using System.Collections.Generic;
using System.Text;
namespace SO115App.Persistence.MongoDB.GestioneInterventi
{
public class GetListaEventiByCodiceRichiesta : IGetListaEventi
{
private readonly DbContext _dbContext;
public GetListaEventiByCodiceRichiesta(DbContext dbContext)
{
_dbContext = dbContext;
}
public List<Evento> Get(ListaEventiQuery query)
{
return (List<Evento>)_dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Eq(x => x.Codice, query.IdRichiesta)).Single().Eventi;
}
}
}
``` |
1619f8dd-c14d-4439-affe-239b584f644b | {
"language": "C#"
} | ```c#
using NUnit.Framework;
using System;
namespace Sailthru.Tests
{
[TestFixture()]
public class Test
{
[Test()]
public void TestCase()
{
Assert.Fail();
}
}
}
```
Revert "[DEVOPS-245] verify test failure" | ```c#
using NUnit.Framework;
using System;
namespace Sailthru.Tests
{
[TestFixture()]
public class Test
{
[Test()]
public void TestCase()
{
}
}
}
``` |
41a6c0c8-7bcb-48fa-8e46-ec841d141c02 | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH315
{
/// <summary>
/// Summary description for Fixture.
/// </summary>
[TestFixture]
[Ignore("Not working, see http://jira.nhibernate.org/browse/NH-315")]
public class Fixture : TestCase
{
protected override string MappingsAssembly
{
get { return "NHibernate.Test"; }
}
protected override System.Collections.IList Mappings
{
get
{
return new string[] { "NHSpecificTest.NH315.Mappings.hbm.xml" };
}
}
[Test]
public void SaveClient()
{
Client client = new Client();
Person person = new Person();
client.Contacts = new ClientPersons();
using( ISession s = OpenSession() )
{
s.Save( person );
client.Contacts.PersonId = person.Id;
client.Contacts.Person = person;
s.Save( client );
s.Flush();
}
using( ISession s = OpenSession() )
{
s.Delete( client );
s.Delete( person );
s.Flush();
}
}
}
}
```
Enable NH-315 fixture since it works now | ```c#
using System;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH315
{
/// <summary>
/// Summary description for Fixture.
/// </summary>
[TestFixture]
public class Fixture : BugTestCase
{
public override string BugNumber
{
get { return "NH315"; }
}
[Test]
public void SaveClient()
{
Client client = new Client();
Person person = new Person();
client.Contacts = new ClientPersons();
using( ISession s = OpenSession() )
{
s.Save( person );
client.Contacts.PersonId = person.Id;
client.Contacts.Person = person;
s.Save( client );
s.Flush();
}
using( ISession s = OpenSession() )
{
s.Delete( client );
s.Delete( person );
s.Flush();
}
}
}
}
``` |
7d38e589-d6e4-4509-b350-8e2ac8848d56 | {
"language": "C#"
} | ```c#
using RealEstateAgencyFranchise.Database;
using Starcounter;
using System.Linq;
namespace RealEstateAgencyFranchise.Controllers
{
internal class OfficeController
{
public Json Get(ulong officeObjectNo)
{
return Db.Scope(() =>
{
var offices = Db.SQL<Office>(
"select o from Office o where o.ObjectNo = ?",
officeObjectNo);
if (offices == null || !offices.Any())
{
return new Response()
{
StatusCode = 404,
StatusDescription = "Office not found"
};
}
var office = offices.First;
var json = new OfficeListJson
{
Data = office
};
if (Session.Current == null)
{
Session.Current = new Session(SessionOptions.PatchVersioning);
}
json.Session = Session.Current;
return json;
});
}
}
}
```
Fix missed view model reference | ```c#
using RealEstateAgencyFranchise.Database;
using RealEstateAgencyFranchise.ViewModels;
using Starcounter;
using System.Linq;
namespace RealEstateAgencyFranchise.Controllers
{
internal class OfficeController
{
public Json Get(ulong officeObjectNo)
{
return Db.Scope(() =>
{
var offices = Db.SQL<Office>(
"select o from Office o where o.ObjectNo = ?",
officeObjectNo);
if (offices == null || !offices.Any())
{
return new Response()
{
StatusCode = 404,
StatusDescription = "Office not found"
};
}
var office = offices.First;
var json = new OfficeDetailsJson
{
Data = office
};
if (Session.Current == null)
{
Session.Current = new Session(SessionOptions.PatchVersioning);
}
json.Session = Session.Current;
return json;
});
}
}
}
``` |
a4e2a3e6-2e0a-41f7-b17f-34da1968bd8e | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct ServerTimeMessage : INetSerializable
{
public int serverUnixTime;
public void Deserialize(NetDataReader reader)
{
serverUnixTime = reader.GetPackedInt();
}
public void Serialize(NetDataWriter writer)
{
writer.PutPackedInt(serverUnixTime);
}
}
}
```
Change time type to long | ```c#
using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public struct ServerTimeMessage : INetSerializable
{
public long serverUnixTime;
public void Deserialize(NetDataReader reader)
{
serverUnixTime = reader.GetPackedLong();
}
public void Serialize(NetDataWriter writer)
{
writer.PutPackedLong(serverUnixTime);
}
}
}
``` |
dbfa7470-f573-408e-af64-d58877ae8d7c | {
"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 UIKit;
namespace TemplateGame.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
```
Fix `TemplateGame.iOS` failing to build | ```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.iOS;
using UIKit;
namespace TemplateGame.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
``` |
883e187e-e90e-4c64-89f7-df3753007368 | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
namespace Avalonia.Utilities
{
#if !BUILDTASK
public
#endif
static class StyleClassParser
{
public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
{
if (IsValidIdentifierStart(r.Peek))
{
return r.TakeWhile(c => IsValidIdentifierChar(c));
}
else
{
return ReadOnlySpan<char>.Empty;
}
}
private static bool IsValidIdentifierStart(char c)
{
return char.IsLetter(c) || c == '_';
}
private static bool IsValidIdentifierChar(char c)
{
if (IsValidIdentifierStart(c) || c == '-')
{
return true;
}
else
{
var cat = CharUnicodeInfo.GetUnicodeCategory(c);
return cat == UnicodeCategory.NonSpacingMark ||
cat == UnicodeCategory.SpacingCombiningMark ||
cat == UnicodeCategory.ConnectorPunctuation ||
cat == UnicodeCategory.Format ||
cat == UnicodeCategory.DecimalDigitNumber;
}
}
}
}
```
Fix build failure from the merge to master. | ```c#
using System;
using System.Globalization;
namespace Avalonia.Utilities
{
#if !BUILDTASK
public
#endif
static class StyleClassParser
{
public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
{
if (IsValidIdentifierStart(r.PeekOneOrThrow))
{
return r.TakeWhile(c => IsValidIdentifierChar(c));
}
else
{
return ReadOnlySpan<char>.Empty;
}
}
private static bool IsValidIdentifierStart(char c)
{
return char.IsLetter(c) || c == '_';
}
private static bool IsValidIdentifierChar(char c)
{
if (IsValidIdentifierStart(c) || c == '-')
{
return true;
}
else
{
var cat = CharUnicodeInfo.GetUnicodeCategory(c);
return cat == UnicodeCategory.NonSpacingMark ||
cat == UnicodeCategory.SpacingCombiningMark ||
cat == UnicodeCategory.ConnectorPunctuation ||
cat == UnicodeCategory.Format ||
cat == UnicodeCategory.DecimalDigitNumber;
}
}
}
}
``` |
ce109a82-4631-459b-9bb1-fd2b7582ce2b | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Desktop.Platform
{
internal static class Architecture
{
public static string NativeIncludePath => $@"{Environment.CurrentDirectory}/{arch}/";
private static string arch => Is64Bit ? @"x64" : @"x86";
internal static bool Is64Bit => IntPtr.Size == 8;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
internal static void SetIncludePath()
{
//todo: make this not a thing for linux or whatever
try
{
SetDllDirectory(NativeIncludePath);
}
catch { }
}
}
}
```
Use RuntimeInfo.IsLinux to check for Linux | ```c#
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Runtime.InteropServices;
namespace osu.Framework.Desktop.Platform
{
internal static class Architecture
{
public static string NativeIncludePath => $@"{Environment.CurrentDirectory}/{arch}/";
private static string arch => Is64Bit ? @"x64" : @"x86";
internal static bool Is64Bit => IntPtr.Size == 8;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
internal static void SetIncludePath()
{
if (RuntimeInfo.IsWindows)
SetDllDirectory(NativeIncludePath);
}
}
}
``` |
43d85f46-00d1-4543-8203-bf30881af98d | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Windows;
namespace ReactiveUIMicro
{
public static class WhenAnyShim
{
public static IObservable<TVal> WhenAny<TSender, TTarget, TVal>(this TSender This, Expression<Func<TSender, TTarget>> property, Func<IObservedChange<TSender, TTarget>, TVal> selector)
where TSender : IReactiveNotifyPropertyChanged
{
var propName = Reflection.SimpleExpressionToPropertyName(property);
var getter = Reflection.GetValueFetcherForProperty<TSender>(propName);
return This.Changed
.Where(x => x.PropertyName == propName)
.Select(_ => new ObservedChange<TSender, TTarget>() {
Sender = This,
PropertyName = propName,
Value = (TTarget)getter(This),
})
.StartWith(new ObservedChange<TSender, TTarget>() { Sender = This, PropertyName = propName, Value = (TTarget)getter(This) })
.Select(selector);
}
}
}```
Fix casting error in WhenAny shim | ```c#
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Windows;
namespace ReactiveUIMicro
{
public static class WhenAnyShim
{
public static IObservable<TVal> WhenAny<TSender, TTarget, TVal>(this TSender This, Expression<Func<TSender, TTarget>> property, Func<IObservedChange<TSender, TTarget>, TVal> selector)
where TSender : IReactiveNotifyPropertyChanged
{
var propName = Reflection.SimpleExpressionToPropertyName(property);
var getter = Reflection.GetValueFetcherForProperty(This.GetType(), propName);
return This.Changed
.Where(x => x.PropertyName == propName)
.Select(_ => new ObservedChange<TSender, TTarget>() {
Sender = This,
PropertyName = propName,
Value = (TTarget)getter(This),
})
.StartWith(new ObservedChange<TSender, TTarget>() { Sender = This, PropertyName = propName, Value = (TTarget)getter(This) })
.Select(selector);
}
}
}``` |
0ec06b0b-74fd-4420-886d-4548641a4f63 | {
"language": "C#"
} | ```c#
namespace WindowsUniversalAppDriver.InnerServer.Commands
{
using System.Reflection;
using WindowsUniversalAppDriver.Common;
internal class GetElementAttributeCommand : CommandBase
{
#region Public Properties
public string ElementId { get; set; }
#endregion
#region Public Methods and Operators
public override string DoImpl()
{
var element = this.Automator.WebElements.GetRegisteredElement(this.ElementId);
object value;
var attributeName = (string)null;
if (this.Parameters.TryGetValue("NAME", out value))
{
attributeName = value.ToString();
}
if (attributeName == null)
{
return this.JsonResponse(ResponseStatus.Success, null);
}
var property = element.GetType().GetRuntimeProperty(attributeName);
if (property == null)
{
return this.JsonResponse(ResponseStatus.Success, null);
}
var attributeValue = property.GetValue(element, null).ToString();
return this.JsonResponse(ResponseStatus.Success, attributeValue);
}
#endregion
}
}
```
Add support for nested properties access in GetElementAttribute command using dot separated syntax | ```c#
namespace WindowsUniversalAppDriver.InnerServer.Commands
{
using System;
using System.Reflection;
using WindowsUniversalAppDriver.Common;
internal class GetElementAttributeCommand : CommandBase
{
#region Public Properties
public string ElementId { get; set; }
#endregion
#region Public Methods and Operators
public override string DoImpl()
{
var element = this.Automator.WebElements.GetRegisteredElement(this.ElementId);
object value;
string attributeName = null;
if (this.Parameters.TryGetValue("NAME", out value))
{
attributeName = value.ToString();
}
if (attributeName == null)
{
return this.JsonResponse(ResponseStatus.Success, null);
}
var properties = attributeName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
object propertyValueObject = element;
foreach (var property in properties)
{
propertyValueObject = GetProperty(propertyValueObject, property);
if (propertyValueObject == null)
{
break;
}
}
var propertyValue = propertyValueObject == null ? null : propertyValueObject.ToString();
return this.JsonResponse(ResponseStatus.Success, propertyValue);
}
private static object GetProperty(object obj, string propertyName)
{
var property = obj.GetType().GetRuntimeProperty(propertyName);
return property == null ? null : property.GetValue(obj, null);
}
#endregion
}
}
``` |
db6f1a5d-77c2-4b96-b5ad-9d566ab52684 | {
"language": "C#"
} | ```c#
@using StackExchange.DataExplorer
@{this.SetPageTitle("Page not found - Stack Exchange Data Explorer");}
<div class="subheader">
<h2>Page Not Found</h2>
</div>
<div style="width:400px; float:left;">
<p>Sorry we could not find the page requested. However, we did find a picture of <a href="http://en.wikipedia.org/wiki/Edgar_F._Codd">Edgar F. Codd </a>, the inventor of the relational data model.</p>
<p>If you feel something is missing that should be here, <a href="http://meta.stackexchange.com/contact">contact us</a>.</p>
</div>
<img src="/Content/images/edgar.jpg" style="float:right;" />
<br class="clear" />
<p> </p>```
Remove stray space in 404 page | ```c#
@using StackExchange.DataExplorer
@{this.SetPageTitle("Page not found - Stack Exchange Data Explorer");}
<div class="subheader">
<h2>Page Not Found</h2>
</div>
<div style="width:400px; float:left;">
<p>Sorry we could not find the page requested. However, we did find a picture of <a href="http://en.wikipedia.org/wiki/Edgar_F._Codd">Edgar F. Codd</a>, the inventor of the relational data model.</p>
<p>If you feel something is missing that should be here, <a href="http://meta.stackexchange.com/contact">contact us</a>.</p>
</div>
<img src="/Content/images/edgar.jpg" style="float:right;" />
<br class="clear" />
<p> </p>
``` |
179b7a80-c2c0-4347-b9de-e264e14a703c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace JabbR.Models
{
public class ChatRoom
{
[Key]
public int Key { get; set; }
public DateTime LastActivity { get; set; }
public DateTime? LastNudged { get; set; }
public string Name { get; set; }
public virtual ChatUser Owner { get; set; }
public virtual ICollection<ChatMessage> Messages { get; set; }
public virtual ICollection<ChatUser> Users { get; set; }
public ChatRoom()
{
Messages = new HashSet<ChatMessage>();
Users = new HashSet<ChatUser>();
}
}
}```
Set the last activity on creation so sql doesn't blow up. | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace JabbR.Models
{
public class ChatRoom
{
[Key]
public int Key { get; set; }
public DateTime LastActivity { get; set; }
public DateTime? LastNudged { get; set; }
public string Name { get; set; }
public virtual ChatUser Owner { get; set; }
public virtual ICollection<ChatMessage> Messages { get; set; }
public virtual ICollection<ChatUser> Users { get; set; }
public ChatRoom()
{
LastActivity = DateTime.UtcNow;
Messages = new HashSet<ChatMessage>();
Users = new HashSet<ChatUser>();
}
}
}``` |
c5c0ba54-de17-49a0-a0aa-b347d9ddae67 | {
"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. Based on Bruce Schneier's RandBytes1-way
/// function method for committing bits
/// </summary>
public class BitCommitmentProvider
{
public byte[] AliceRandBytes1 { get; set; }
public byte[] AliceRandBytes2 { get; set; }
public byte[] AliceBytesToCommitBytesToCommit { get; set; }
public BitCommitmentProvider(byte[] randBytes1,
byte[] randBytes2,
byte[] bytesToCommit)
{
AliceRandBytes1 = randBytes1;
AliceRandBytes2 = randBytes2;
AliceBytesToCommitBytesToCommit = bytesToCommit;
}
public byte[] BitCommitMessage()
{
throw new NotImplementedException();
}
}
}
```
Fix refactor fail and add book reference | ```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. See p.87 of `Applied Cryptography`.
/// </summary>
public class BitCommitmentProvider
{
public byte[] AliceRandBytes1 { get; set; }
public byte[] AliceRandBytes2 { get; set; }
public byte[] AliceBytesToCommitBytesToCommit { get; set; }
public BitCommitmentProvider(byte[] randBytes1,
byte[] randBytes2,
byte[] bytesToCommit)
{
AliceRandBytes1 = randBytes1;
AliceRandBytes2 = randBytes2;
AliceBytesToCommitBytesToCommit = bytesToCommit;
}
public byte[] BitCommitMessage()
{
throw new NotImplementedException();
}
}
}
``` |
51538c77-3259-48d2-9b95-5834eb635f93 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;
namespace TeaCommerce.Umbraco.Configuration.Compatibility {
public static class Domain {
private const string CacheKey = "Domains";
public static umbraco.cms.businesslogic.web.Domain[] GetDomainsById( int nodeId ) {
List<umbraco.cms.businesslogic.web.Domain> domains = CacheService.Instance.GetCacheValue<List<umbraco.cms.businesslogic.web.Domain>>( CacheKey );
if ( domains == null ) {
domains = new List<umbraco.cms.businesslogic.web.Domain>();
List<dynamic> result = ApplicationContext.Current.DatabaseContext.Database.Fetch<dynamic>( "select id, domainName from umbracoDomains" );
foreach ( dynamic domain in result ) {
if ( domains.All( d => d.Name != domain.domainName ) ) {
domains.Add( new umbraco.cms.businesslogic.web.Domain( domain.domainId ) );
}
}
CacheService.Instance.SetCacheValue( CacheKey, domains );
}
return domains.Where( d => d.RootNodeId == nodeId ).ToArray();
}
public static void InvalidateCache() {
CacheService.Instance.Invalidate( CacheKey );
}
}
}```
Change domain id to new naming format | ```c#
using System.Collections.Generic;
using System.Linq;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;
namespace TeaCommerce.Umbraco.Configuration.Compatibility {
public static class Domain {
private const string CacheKey = "Domains";
public static umbraco.cms.businesslogic.web.Domain[] GetDomainsById( int nodeId ) {
List<umbraco.cms.businesslogic.web.Domain> domains = CacheService.Instance.GetCacheValue<List<umbraco.cms.businesslogic.web.Domain>>( CacheKey );
if ( domains == null ) {
domains = new List<umbraco.cms.businesslogic.web.Domain>();
List<dynamic> result = ApplicationContext.Current.DatabaseContext.Database.Fetch<dynamic>( "select id, domainName from umbracoDomains" );
foreach ( dynamic domain in result ) {
if ( domains.All( d => d.Name != domain.domainName ) ) {
domains.Add( new umbraco.cms.businesslogic.web.Domain( domain.id ) );
}
}
CacheService.Instance.SetCacheValue( CacheKey, domains );
}
return domains.Where( d => d.RootNodeId == nodeId ).ToArray();
}
public static void InvalidateCache() {
CacheService.Instance.Invalidate( CacheKey );
}
}
}``` |
e3bbb3d4-57e4-452b-ae95-43d508009566 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Crosscutter")]
[assembly: AssemblyDescription(".NET extensions, safety & convenience methods for known types.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daryl Benzel")]
[assembly: AssemblyProduct("Crosscutter")]
[assembly: AssemblyCopyright("Copyright © Daryl Benzel 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bd03676e-4bbc-4e8e-9f00-a3e2ae2d2b9d")]
// 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.*")]
[assembly: AssemblyFileVersion("1.0.0")]
```
Edit assembly description to make xml compliant for nuspec output. | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Crosscutter")]
[assembly: AssemblyDescription(".NET extensions, safety & convenience methods for known types.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daryl Benzel")]
[assembly: AssemblyProduct("Crosscutter")]
[assembly: AssemblyCopyright("Copyright © Daryl Benzel 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bd03676e-4bbc-4e8e-9f00-a3e2ae2d2b9d")]
// 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.*")]
[assembly: AssemblyFileVersion("1.0.0")]
``` |
58c2f219-cbbb-4ca8-8a3b-9fb88b39cdf3 | {
"language": "C#"
} | ```c#
using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Rellaid.Dto
{
[DataContract]
public class InboundQueueDistributorDto
{
[DataMember]
public string FilterNumber { get; set; }
[DataMember]
public int RungCount { get; set; }
}
}
```
Change FilterNumber to PhoneNumber so that it has the same name as the database field | ```c#
using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Rellaid.Dto
{
[DataContract]
public class InboundQueueDistributorDto
{
[DataMember]
public string PhoneNumber { get; set; }
[DataMember]
public int RungCount { get; set; }
}
}
``` |
6452293b-99ca-445c-a579-5a694ed83257 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;
namespace RocketRegions.Model.Flag.Impl
{
public class NoVehiclesUsageFlag : BoolFlag
{
public override string Description => "Allow/Disallow usage of vehicles in region";
private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();
public override void UpdateState(List<UnturnedPlayer> players)
{
foreach (var player in players)
{
var id = PlayerUtil.GetId(player);
var veh = player.Player.movement.getVehicle();
var isInVeh = veh != null;
if (!_lastVehicleStates.ContainsKey(id))
_lastVehicleStates.Add(id, veh);
var wasDriving = _lastVehicleStates[id];
if (!isInVeh || wasDriving ||
!GetValueSafe(Region.GetGroup(player))) continue;
byte seat;
Vector3 point;
byte angle;
veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
}
}
public override void OnRegionEnter(UnturnedPlayer p)
{
//do nothing
}
public override void OnRegionLeave(UnturnedPlayer p)
{
//do nothing
}
}
}```
Fix for NoVehicleUsage flag doing nothing | ```c#
using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;
namespace RocketRegions.Model.Flag.Impl
{
public class NoVehiclesUsageFlag : BoolFlag
{
public override string Description => "Allow/Disallow usage of vehicles in region";
private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();
public override void UpdateState(List<UnturnedPlayer> players)
{
foreach (var player in players)
{
var id = PlayerUtil.GetId(player);
var veh = player.Player.movement.getVehicle();
var isInVeh = veh != null;
if (!_lastVehicleStates.ContainsKey(id))
_lastVehicleStates.Add(id, veh);
var wasDriving = _lastVehicleStates[id];
if (!isInVeh || wasDriving ||
!GetValueSafe(Region.GetGroup(player))) continue;
byte seat;
Vector3 point;
byte angle;
veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
veh.removePlayer(seat, point, angle, true);
}
}
public override void OnRegionEnter(UnturnedPlayer p)
{
//do nothing
}
public override void OnRegionLeave(UnturnedPlayer p)
{
//do nothing
}
}
}``` |
c0f37117-3c7d-46bc-b0e0-7df74e368b61 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using UnityEngine;
namespace LiteNetLibManager
{
public class DefaultInterestManager : BaseInterestManager
{
[Tooltip("Update every ? seconds")]
public float updateInterval = 1f;
private float updateCountDown = 0f;
private void Update()
{
if (!IsServer)
{
// Update at server only
return;
}
updateCountDown -= Time.unscaledDeltaTime;
if (updateCountDown <= 0f)
{
updateCountDown = updateInterval;
HashSet<uint> subscribings = new HashSet<uint>();
foreach (LiteNetLibPlayer player in Manager.GetPlayers())
{
if (!player.IsReady)
{
// Don't subscribe if player not ready
continue;
}
foreach (LiteNetLibIdentity playerObject in player.GetSpawnedObjects())
{
// Skip destroyed player object
if (playerObject == null)
continue;
// Update subscribing list, it will unsubscribe objects which is not in this list
subscribings.Clear();
foreach (LiteNetLibIdentity spawnedObject in Manager.Assets.GetSpawnedObjects())
{
if (ShouldSubscribe(playerObject, spawnedObject))
subscribings.Add(spawnedObject.ObjectId);
}
playerObject.UpdateSubscribings(subscribings);
}
}
}
}
}
}
```
Delete null check codes, it is not necessary because set owner object function bugs was solved. | ```c#
using System.Collections.Generic;
using UnityEngine;
namespace LiteNetLibManager
{
public class DefaultInterestManager : BaseInterestManager
{
[Tooltip("Update every ? seconds")]
public float updateInterval = 1f;
private float updateCountDown = 0f;
private void Update()
{
if (!IsServer)
{
// Update at server only
return;
}
updateCountDown -= Time.unscaledDeltaTime;
if (updateCountDown <= 0f)
{
updateCountDown = updateInterval;
HashSet<uint> subscribings = new HashSet<uint>();
foreach (LiteNetLibPlayer player in Manager.GetPlayers())
{
if (!player.IsReady)
{
// Don't subscribe if player not ready
continue;
}
foreach (LiteNetLibIdentity playerObject in player.GetSpawnedObjects())
{
// Update subscribing list, it will unsubscribe objects which is not in this list
subscribings.Clear();
foreach (LiteNetLibIdentity spawnedObject in Manager.Assets.GetSpawnedObjects())
{
if (ShouldSubscribe(playerObject, spawnedObject))
subscribings.Add(spawnedObject.ObjectId);
}
playerObject.UpdateSubscribings(subscribings);
}
}
}
}
}
}
``` |
f744c967-38b4-4af6-9e8c-b882ffca42c6 | {
"language": "C#"
} | ```c#
using Machine.Specifications;
namespace TestingFxTests
{
[Subject("Booleans")]
public class When_comparing_booleans
{
private static bool Subject;
private Establish context = () => Subject = false;
private Because of = () => Subject = true;
private It should_be_true = () => Subject.ShouldEqual(true);
}
}```
Rename recommended mSpec convention to MspecExample for consistency | ```c#
using Machine.Specifications;
namespace TestingFxTests
{
[Subject("Mspec")]
public class MspecExample
{
private static bool Subject;
private Establish context = () => Subject = false;
private Because of = () => Subject = true;
private It should_be_true = () => Subject.ShouldEqual(true);
}
}``` |
dd7bfcd2-d107-47b5-9c7c-0c8f24e61c16 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Tiesmaster.Dcc
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(RunDccProxyAsync);
}
private static async Task RunDccProxyAsync(HttpContext context)
{
await context.Response.WriteAsync("Hello from DCC ;)");
}
}
}```
Copy in Proxy code from ProxyMiddleware.cs, | ```c#
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Tiesmaster.Dcc
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(RunDccProxyAsync);
}
private static async Task RunDccProxyAsync(HttpContext context)
{
var requestMessage = new HttpRequestMessage();
var requestMethod = context.Request.Method;
if(!HttpMethods.IsGet(requestMethod) &&
!HttpMethods.IsHead(requestMethod) &&
!HttpMethods.IsDelete(requestMethod) &&
!HttpMethods.IsTrace(requestMethod))
{
var streamContent = new StreamContent(context.Request.Body);
requestMessage.Content = streamContent;
}
// Copy the request headers
foreach(var header in context.Request.Headers)
{
if(!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
}
}
requestMessage.Headers.Host = _options.Host + ":" + _options.Port;
var uriString = $"{_options.Scheme}://{_options.Host}:{_options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
requestMessage.RequestUri = new Uri(uriString);
requestMessage.Method = new HttpMethod(context.Request.Method);
using(var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
context.Response.StatusCode = (int)responseMessage.StatusCode;
foreach(var header in responseMessage.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
foreach(var header in responseMessage.Content.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
// SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
context.Response.Headers.Remove("transfer-encoding");
await responseMessage.Content.CopyToAsync(context.Response.Body);
}
}
}``` |
30a8829a-c934-4c14-84f3-9ebc763fd1e1 | {
"language": "C#"
} | ```c#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel.Client;
using IdentityServer4.IntegrationTests.Clients;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace IdentityServer.IntegrationTests.Clients
{
public class DiscoveryClientTests
{
const string DiscoveryEndpoint = "https://server/.well-known/openid-configuration";
private readonly HttpClient _client;
private readonly HttpMessageHandler _handler;
public DiscoveryClientTests()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var server = new TestServer(builder);
_handler = server.CreateHandler();
_client = server.CreateClient();
}
[Fact]
public async Task Retrieving_discovery_document_should_succeed()
{
var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
var doc = await client.GetAsync();
}
}
}```
Add one more discovery test | ```c#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using FluentAssertions;
using IdentityModel.Client;
using IdentityServer4.IntegrationTests.Clients;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace IdentityServer.IntegrationTests.Clients
{
public class DiscoveryClientTests
{
const string DiscoveryEndpoint = "https://server/.well-known/openid-configuration";
private readonly HttpClient _client;
private readonly HttpMessageHandler _handler;
public DiscoveryClientTests()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var server = new TestServer(builder);
_handler = server.CreateHandler();
_client = server.CreateClient();
}
[Fact]
public async Task Retrieving_discovery_document_should_succeed()
{
var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
var doc = await client.GetAsync();
}
[Fact]
public async Task Discovery_document_should_have_expected_values()
{
var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
var doc = await client.GetAsync();
// endpoints
doc.TokenEndpoint.Should().Be("https://server/connect/token");
doc.AuthorizationEndpoint.Should().Be("https://server/connect/authorize");
doc.IntrospectionEndpoint.Should().Be("https://server/connect/introspect");
doc.EndSessionEndpoint.Should().Be("https://server/connect/endsession");
// jwk
doc.Keys.Keys.Count.Should().Be(1);
doc.Keys.Keys.First().E.Should().NotBeNull();
doc.Keys.Keys.First().N.Should().NotBeNull();
}
}
}``` |
05d672a2-6587-43e8-9607-fc2db60a51e1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sync.IRC.MessageFilter.Filters
{
class DefaultFormat : FilterBase, IDanmaku, IOsu
{
public override void onMsg(ref MessageBase msg)
{
msg.user.setPerfix("<");
msg.user.setSuffix(">");
}
}
}
```
Add ":" to default suffix | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sync.IRC.MessageFilter.Filters
{
class DefaultFormat : FilterBase, IDanmaku, IOsu
{
public override void onMsg(ref MessageBase msg)
{
msg.user.setPerfix("<");
msg.user.setSuffix(">: ");
}
}
}
``` |
c1e9b6ba-4a06-4622-9dcd-b82bfa7ec05e | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using AzureStorage.Tables;
using Microsoft.WindowsAzure.Storage.Table;
namespace CompetitionPlatform.Data.AzureRepositories.Project
{
public class ProjectFileInfoEntity : TableEntity, IProjectFileInfoData
{
public static string GeneratePartitionKey()
{
return "ProjectFileInfo";
}
public static string GenerateRowKey(string projectId)
{
return projectId;
}
public string ProjectId => RowKey;
public string FileName { get; set; }
public string ContentType { get; set; }
public static ProjectFileInfoEntity Create(IProjectFileInfoData src)
{
var result = new ProjectFileInfoEntity
{
PartitionKey = GeneratePartitionKey(),
RowKey = GenerateRowKey(src.ProjectId),
FileName = src.FileName,
ContentType = src.ContentType
};
return result;
}
}
public class ProjectFileInfoRepository : IProjectFileInfoRepository
{
private readonly IAzureTableStorage<ProjectFileInfoEntity> _projectFileInfoTableStorage;
public ProjectFileInfoRepository(IAzureTableStorage<ProjectFileInfoEntity> projectFileInfoTableStorage)
{
_projectFileInfoTableStorage = projectFileInfoTableStorage;
}
public async Task<IProjectFileInfoData> GetAsync(string projectId)
{
var partitionKey = ProjectFileInfoEntity.GeneratePartitionKey();
var rowKey = ProjectFileInfoEntity.GenerateRowKey(projectId);
return await _projectFileInfoTableStorage.GetDataAsync(partitionKey, rowKey);
}
public async Task SaveAsync(IProjectFileInfoData fileInfoData)
{
var newEntity = ProjectFileInfoEntity.Create(fileInfoData);
await _projectFileInfoTableStorage.InsertAsync(newEntity);
}
}
}
```
Change File Info repository save method, file info can now be updated. | ```c#
using System.Threading.Tasks;
using AzureStorage.Tables;
using Microsoft.WindowsAzure.Storage.Table;
namespace CompetitionPlatform.Data.AzureRepositories.Project
{
public class ProjectFileInfoEntity : TableEntity, IProjectFileInfoData
{
public static string GeneratePartitionKey()
{
return "ProjectFileInfo";
}
public static string GenerateRowKey(string projectId)
{
return projectId;
}
public string ProjectId => RowKey;
public string FileName { get; set; }
public string ContentType { get; set; }
public static ProjectFileInfoEntity Create(IProjectFileInfoData src)
{
var result = new ProjectFileInfoEntity
{
PartitionKey = GeneratePartitionKey(),
RowKey = GenerateRowKey(src.ProjectId),
FileName = src.FileName,
ContentType = src.ContentType
};
return result;
}
}
public class ProjectFileInfoRepository : IProjectFileInfoRepository
{
private readonly IAzureTableStorage<ProjectFileInfoEntity> _projectFileInfoTableStorage;
public ProjectFileInfoRepository(IAzureTableStorage<ProjectFileInfoEntity> projectFileInfoTableStorage)
{
_projectFileInfoTableStorage = projectFileInfoTableStorage;
}
public async Task<IProjectFileInfoData> GetAsync(string projectId)
{
var partitionKey = ProjectFileInfoEntity.GeneratePartitionKey();
var rowKey = ProjectFileInfoEntity.GenerateRowKey(projectId);
return await _projectFileInfoTableStorage.GetDataAsync(partitionKey, rowKey);
}
public async Task SaveAsync(IProjectFileInfoData fileInfoData)
{
var newEntity = ProjectFileInfoEntity.Create(fileInfoData);
await _projectFileInfoTableStorage.InsertOrReplaceAsync(newEntity);
}
}
}
``` |
32391c56-0d1d-448b-84ed-5e674d9ae06e | {
"language": "C#"
} | ```c#
using NUnit.Framework;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
public class MyDatabaseSettings : IMyDatabaseSettings
{
public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\Tests.db;Version=3;New=True;BinaryGUID=False;";
}
}
```
Change name of daabase for IoC | ```c#
using NUnit.Framework;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
public class MyDatabaseSettings : IMyDatabaseSettings
{
public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\IoCTests.db;Version=3;New=True;BinaryGUID=False;";
}
}
``` |
72c7629a-3417-4f18-9a12-7c35296b2c8c | {
"language": "C#"
} | ```c#
using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Linq;
namespace Injector
{
public class InstructionRemover
{
public InstructionRemover(ModuleDefinition targetModule)
{
_targetModule = targetModule;
}
ModuleDefinition _targetModule;
public void ReplaceByNopAt(string typeName, string methodName, int instructionIndex)
{
var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
var methodBody = method.Body;
ReplaceByNop(methodBody, methodBody.Instructions[instructionIndex]);
}
public void ReplaceByNop(MethodBody methodBody, Instruction instruction)
{
methodBody.GetILProcessor().Replace(instruction, Instruction.Create(OpCodes.Nop));
}
public void ClearAllButLast(string typeName, string methodName)
{
var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
var methodBody = method.Body;
var methodILProcessor = methodBody.GetILProcessor();
for (int i = methodBody.Instructions.Count - 1; i > 0; i--)
{
methodILProcessor.Remove(methodBody.Instructions.First());
}
}
}
}
```
Add useful overload for instruction remover | ```c#
using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Linq;
namespace Injector
{
public class InstructionRemover
{
public InstructionRemover(ModuleDefinition targetModule)
{
_targetModule = targetModule;
}
ModuleDefinition _targetModule;
public void ReplaceByNopAt(string typeName, string methodName, int instructionIndex)
{
var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
var methodBody = method.Body;
ReplaceByNop(methodBody, methodBody.Instructions[instructionIndex]);
}
public void ReplaceByNop(MethodBody methodBody, Instruction instruction)
{
methodBody.GetILProcessor().Replace(instruction, Instruction.Create(OpCodes.Nop));
}
public void ClearAllButLast(string typeName, string methodName)
{
var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
var methodBody = method.Body;
ClearAllButLast(methodBody);
}
public void ClearAllButLast(MethodBody methodBody)
{
var methodILProcessor = methodBody.GetILProcessor();
for (int i = methodBody.Instructions.Count - 1; i > 0; i--)
{
methodILProcessor.Remove(methodBody.Instructions.First());
}
}
}
}
``` |
77f2fe74-2d1e-4468-9aee-e6112e86e37a | {
"language": "C#"
} | ```c#
using Microsoft.Data.Tools.Schema.Sql.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
namespace Daves.DeepDataDuplicator.IntegrationTests
{
[TestClass]
public class SqlDatabaseSetup
{
public static readonly string ConnectionString;
static SqlDatabaseSetup()
{
using (var executionContext = SqlDatabaseTestClass.TestService.OpenExecutionContext())
{
ConnectionString = executionContext.Connection.ConnectionString;
}
}
[AssemblyInitialize]
public static void InitializeAssembly(TestContext testContext)
{
SqlDatabaseTestClass.TestService.DeployDatabaseProject();
using (var transaction = new TransactionScope())
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (IDbCommand command = connection.CreateCommand())
{
command.CommandText = DeepCopyGenerator.GenerateProcedure(
connection: connection,
rootTableName: "Nations");
command.ExecuteNonQuery();
}
}
transaction.Complete();
}
}
}
}
```
Fix connection bug for fresh environments | ```c#
using Microsoft.Data.Tools.Schema.Sql.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;
namespace Daves.DeepDataDuplicator.IntegrationTests
{
[TestClass]
public class SqlDatabaseSetup
{
[AssemblyInitialize]
public static void InitializeAssembly(TestContext testContext)
{
SqlDatabaseTestClass.TestService.DeployDatabaseProject();
string connectionString;
using (var executionContext = SqlDatabaseTestClass.TestService.OpenExecutionContext())
{
connectionString = executionContext.Connection.ConnectionString;
}
using (var transaction = new TransactionScope())
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (IDbCommand command = connection.CreateCommand())
{
command.CommandText = DeepCopyGenerator.GenerateProcedure(
connection: connection,
rootTableName: "Nations");
command.ExecuteNonQuery();
}
}
transaction.Complete();
}
}
}
}
``` |
1a93b36c-2bfb-4a04-a5d4-2cdb68190d71 | {
"language": "C#"
} | ```c#
using Aspose.Words.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aspose.Words.Examples.CSharp.Programming_Documents.Working_with_Fields
{
class InsertIncludeFieldWithoutDocumentBuilder
{
public static void Run()
{
// ExStart:InsertIncludeFieldWithoutDocumentBuilder
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this INCLUDETEXT field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
// Create instance of FieldAsk class and lets build the above field code
FieldInclude fieldinclude = (FieldInclude)para.AppendField(FieldType.FieldInclude, false);
fieldinclude.BookmarkName = "bookmark";
fieldinclude.SourceFullName = dataDir + @"IncludeText.docx";
doc.FirstSection.Body.AppendChild(para);
// Finally update this TOA field
fieldinclude.Update();
dataDir = dataDir + "InsertIncludeFieldWithoutDocumentBuilder_out.doc";
doc.Save(dataDir);
// ExEnd:InsertIncludeFieldWithoutDocumentBuilder
Console.WriteLine("\nInclude field without using document builder inserted successfully.\nFile saved at " + dataDir);
}
}
}
```
Update "Insert Include Field" example | ```c#
using Aspose.Words.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aspose.Words.Examples.CSharp.Programming_Documents.Working_with_Fields
{
class InsertIncludeFieldWithoutDocumentBuilder
{
public static void Run()
{
// ExStart:InsertIncludeFieldWithoutDocumentBuilder
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this INCLUDETEXT field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
// Create instance of FieldAsk class and lets build the above field code
FieldInclude fieldinclude = (FieldInclude)para.AppendField(FieldType.FieldInclude, false);
fieldinclude.BookmarkName = "bookmark";
fieldinclude.SourceFullName = dataDir + @"IncludeText.docx";
doc.FirstSection.Body.AppendChild(para);
// Finally update this Include field
fieldinclude.Update();
dataDir = dataDir + "InsertIncludeFieldWithoutDocumentBuilder_out.doc";
doc.Save(dataDir);
// ExEnd:InsertIncludeFieldWithoutDocumentBuilder
Console.WriteLine("\nInclude field without using document builder inserted successfully.\nFile saved at " + dataDir);
}
}
}
``` |
8aa1fc3f-fa94-4716-b2ab-0fd26df924a6 | {
"language": "C#"
} | ```c#
using System;
namespace Espera.Network
{
public class NetworkSong
{
public string Album { get; set; }
public string Artist { get; set; }
public TimeSpan Duration { get; set; }
public string Genre { get; set; }
public Guid Guid { get; set; }
public NetworkSongSource Source { get; set; }
public string Title { get; set; }
}
}```
Add the track number to the song | ```c#
using System;
namespace Espera.Network
{
public class NetworkSong
{
public string Album { get; set; }
public string Artist { get; set; }
public TimeSpan Duration { get; set; }
public string Genre { get; set; }
public Guid Guid { get; set; }
public NetworkSongSource Source { get; set; }
public string Title { get; set; }
public int TrackNumber { get; set; }
}
}``` |
449bfe08-0bad-4387-9a83-f125a4c43312 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base.Get;
using Enums;
using Objects.Basic;
using Objects.Get.Shows.Common;
using System.Collections.Generic;
internal class TraktShowsMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedShow>, TraktMostPlayedShow>
{
internal TraktShowsMostPlayedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; }
internal TraktPeriod? Period { get; set; }
protected override IDictionary<string, object> GetUriPathParameters()
{
var uriParams = base.GetUriPathParameters();
if (Period.HasValue && Period.Value != TraktPeriod.Unspecified)
uriParams.Add("period", Period.Value.AsString());
return uriParams;
}
protected override string UriTemplate => "shows/played{/period}{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
```
Add filter property to most played shows request. | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base;
using Base.Get;
using Enums;
using Objects.Basic;
using Objects.Get.Shows.Common;
using System.Collections.Generic;
internal class TraktShowsMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedShow>, TraktMostPlayedShow>
{
internal TraktShowsMostPlayedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; }
internal TraktPeriod? Period { get; set; }
protected override IDictionary<string, object> GetUriPathParameters()
{
var uriParams = base.GetUriPathParameters();
if (Period.HasValue && Period.Value != TraktPeriod.Unspecified)
uriParams.Add("period", Period.Value.AsString());
return uriParams;
}
protected override string UriTemplate => "shows/played{/period}{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktShowFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
``` |
740fed2e-a711-4edd-b36d-80efa5b6a107 | {
"language": "C#"
} | ```c#
using Orchard.Layouts.Helpers;
using Orchard.Layouts.Elements;
namespace Orchard.DynamicForms.Elements {
public class Fieldset : Container {
public override string Category {
get { return "Forms"; }
}
public string Legend {
get { return this.Retrieve(f => f.Legend); }
set { this.Store(f => f.Legend, value); }
}
public Form Form {
get {
var parent = Container;
while (parent != null) {
var form = parent as Form;
if (form != null)
return form;
parent = parent.Container;
}
return null;
}
}
}
}```
Remove editor completely when adding a fieldset to the layout editor. | ```c#
using Orchard.Layouts.Helpers;
using Orchard.Layouts.Elements;
namespace Orchard.DynamicForms.Elements {
public class Fieldset : Container {
public override string Category {
get { return "Forms"; }
}
public override bool HasEditor {
get { return false; }
}
public string Legend {
get { return this.Retrieve(f => f.Legend); }
set { this.Store(f => f.Legend, value); }
}
public Form Form {
get {
var parent = Container;
while (parent != null) {
var form = parent as Form;
if (form != null)
return form;
parent = parent.Container;
}
return null;
}
}
}
}``` |
aa1cad87-0528-47f0-acb2-56e8a01e4853 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Management.Automation;
namespace Microsoft.PowerShell.CrossCompatibility.Commands
{
internal static class CommandUtilities
{
private const string COMPATIBILITY_ERROR_ID = "CompatibilityAnalysisError";
public const string MODULE_PREFIX = "PSCompatibility";
public static void WriteExceptionAsError(
this Cmdlet cmdlet,
Exception exception,
string errorId = COMPATIBILITY_ERROR_ID,
ErrorCategory errorCategory = ErrorCategory.ReadError,
object targetObject = null)
{
cmdlet.WriteError(CreateCompatibilityErrorRecord(exception, errorId, errorCategory, targetObject));
}
public static string GetNormalizedAbsolutePath(this PSCmdlet cmdlet, string path)
{
if (Path.IsPathRooted(path))
{
return path;
}
return cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
}
private static ErrorRecord CreateCompatibilityErrorRecord(
Exception e,
string errorId = COMPATIBILITY_ERROR_ID,
ErrorCategory errorCategory = ErrorCategory.ReadError,
object targetObject = null)
{
return new ErrorRecord(
e,
errorId,
errorCategory,
targetObject);
}
}
}```
Convert scrap errors to warnings | ```c#
using System;
using System.IO;
using System.Management.Automation;
namespace Microsoft.PowerShell.CrossCompatibility.Commands
{
internal static class CommandUtilities
{
private const string COMPATIBILITY_ERROR_ID = "CompatibilityAnalysisError";
public const string MODULE_PREFIX = "PSCompatibility";
public static void WriteExceptionAsWarning(
this Cmdlet cmdlet,
Exception exception,
string errorId = COMPATIBILITY_ERROR_ID,
ErrorCategory errorCategory = ErrorCategory.ReadError,
object targetObject = null)
{
cmdlet.WriteWarning(exception.ToString());
}
public static string GetNormalizedAbsolutePath(this PSCmdlet cmdlet, string path)
{
if (Path.IsPathRooted(path))
{
return path;
}
return cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
}
private static ErrorRecord CreateCompatibilityErrorRecord(
Exception e,
string errorId = COMPATIBILITY_ERROR_ID,
ErrorCategory errorCategory = ErrorCategory.ReadError,
object targetObject = null)
{
return new ErrorRecord(
e,
errorId,
errorCategory,
targetObject);
}
}
}``` |
e08dac05-c80c-4877-8503-195d18dca26f | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Windows.UI.Xaml;
namespace Microsoft.Xaml.Interactivity
{
/// <summary>
/// A base class for behaviors, implementing the basic plumbing of IBehavior
/// </summary>
public abstract class Behavior : DependencyObject, IBehavior
{
public DependencyObject AssociatedObject { get; private set; }
public void Attach(DependencyObject associatedObject)
{
AssociatedObject = associatedObject;
OnAttached();
}
public void Detach()
{
OnDetaching();
}
protected virtual void OnAttached()
{
}
protected virtual void OnDetaching()
{
}
}
}
```
Check associated object parameter for null. Throw ArgumentNullException if it is null | ```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;
using Windows.UI.Xaml;
namespace Microsoft.Xaml.Interactivity
{
/// <summary>
/// A base class for behaviors, implementing the basic plumbing of IBehavior
/// </summary>
public abstract class Behavior : DependencyObject, IBehavior
{
public DependencyObject AssociatedObject { get; private set; }
public void Attach(DependencyObject associatedObject)
{
if (associatedObject == null) throw new ArgumentNullException(nameof(associatedObject));
AssociatedObject = associatedObject;
OnAttached();
}
public void Detach()
{
OnDetaching();
}
protected virtual void OnAttached()
{
}
protected virtual void OnDetaching()
{
}
}
}
``` |
57c4d9a2-028b-4cff-a75e-069805c6d1b3 | {
"language": "C#"
} | ```c#
using Fiddler;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace VCSJones.FiddlerCert
{
public class SettingsModel : INotifyPropertyChanged
{
private bool _checkForUpdates;
private RelayCommand _saveCommand, _cancelCommand;
public Version LatestVersion => CertificateInspector.LatestVersion?.Item1;
public Version CurrentVersion => typeof(CertInspector).Assembly.GetName().Version;
public bool CheckForUpdates
{
get
{
return _checkForUpdates;
}
set
{
_checkForUpdates = value;
OnPropertyChanged();
}
}
public RelayCommand SaveCommand
{
get
{
return _saveCommand;
}
set
{
_saveCommand = value;
OnPropertyChanged();
}
}
public RelayCommand CancelCommand
{
get
{
return _cancelCommand;
}
set
{
_cancelCommand = value;
OnPropertyChanged();
}
}
public SettingsModel()
{
SaveCommand = new RelayCommand(_ =>
{
FiddlerApplication.Prefs.SetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
CloseRequest?.Invoke();
});
CancelCommand = new RelayCommand(_ =>
{
CloseRequest?.Invoke();
});
CheckForUpdates = FiddlerApplication.Prefs.GetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
}
public event PropertyChangedEventHandler PropertyChanged;
public event Action CloseRequest;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
```
Fix default value in settings window. | ```c#
using Fiddler;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace VCSJones.FiddlerCert
{
public class SettingsModel : INotifyPropertyChanged
{
private bool _checkForUpdates;
private RelayCommand _saveCommand, _cancelCommand;
public Version LatestVersion => CertificateInspector.LatestVersion?.Item1;
public Version CurrentVersion => typeof(CertInspector).Assembly.GetName().Version;
public bool CheckForUpdates
{
get
{
return _checkForUpdates;
}
set
{
_checkForUpdates = value;
OnPropertyChanged();
}
}
public RelayCommand SaveCommand
{
get
{
return _saveCommand;
}
set
{
_saveCommand = value;
OnPropertyChanged();
}
}
public RelayCommand CancelCommand
{
get
{
return _cancelCommand;
}
set
{
_cancelCommand = value;
OnPropertyChanged();
}
}
public SettingsModel()
{
SaveCommand = new RelayCommand(_ =>
{
FiddlerApplication.Prefs.SetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
CloseRequest?.Invoke();
});
CancelCommand = new RelayCommand(_ =>
{
CloseRequest?.Invoke();
});
CheckForUpdates = FiddlerApplication.Prefs.GetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, false);
}
public event PropertyChangedEventHandler PropertyChanged;
public event Action CloseRequest;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
``` |
15acb991-0280-452e-9c1a-f734157ad867 | {
"language": "C#"
} | ```c#
using System.IO;
using NServiceBus.Persistence.Sql.ScriptBuilder;
class SubscriptionWriter
{
public static void WriteSubscriptionScript(string scriptPath, BuildSqlDialect sqlDialect)
{
var createPath = Path.Combine(scriptPath, "Subscription_Create.sql");
File.Delete(createPath);
using (var writer = File.CreateText(createPath))
{
SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
}
var dropPath = Path.Combine(scriptPath, "Subscription_Drop.sql");
File.Delete(dropPath);
using (var writer = File.CreateText(dropPath))
{
SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
}
}
}```
Fix the subscription drop script | ```c#
using System.IO;
using NServiceBus.Persistence.Sql.ScriptBuilder;
class SubscriptionWriter
{
public static void WriteSubscriptionScript(string scriptPath, BuildSqlDialect sqlDialect)
{
var createPath = Path.Combine(scriptPath, "Subscription_Create.sql");
File.Delete(createPath);
using (var writer = File.CreateText(createPath))
{
SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
}
var dropPath = Path.Combine(scriptPath, "Subscription_Drop.sql");
File.Delete(dropPath);
using (var writer = File.CreateText(dropPath))
{
SubscriptionScriptBuilder.BuildDropScript(writer, sqlDialect);
}
}
}``` |
a0ccb534-dd5b-45be-af58-189386b7446f | {
"language": "C#"
} | ```c#
using Mono.Addins;
using Mono.Addins.Description;
[assembly: Addin(
Id = "jzeferino.XSAddin",
Namespace = "jzeferino.XSAddin",
Version = "0.0.1"
)]
[assembly: AddinName("jzeferino.XSAddin")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("This add-in let you create a Xamarin Cross Platform solution (Xamarin.Native) or (Xamarin.Forms)." +
"When creating the project the addin will show you a custom wizard wich the user can select the application name, the application identifier and if he wants, .gitignore, readme and cake." +
"It already creates some PCL projects to allow the shared code to be separated in different layers using MVVM pattern." +
"It also allows you to create some file templates.")]
[assembly: AddinAuthor("jzeferino")]
[assembly: AddinUrl("https://github.com/jzeferino/jzeferino.XSAddin")]
```
Make addin version assembly to 0.1. | ```c#
using Mono.Addins;
using Mono.Addins.Description;
[assembly: Addin(
Id = "jzeferino.XSAddin",
Namespace = "jzeferino.XSAddin",
Version = "0.1"
)]
[assembly: AddinName("jzeferino.XSAddin")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("This add-in let you create a Xamarin Cross Platform solution (Xamarin.Native) or (Xamarin.Forms)." +
"When creating the project the addin will show you a custom wizard wich the user can select the application name, the application identifier and if he wants, .gitignore, readme and cake." +
"It already creates some PCL projects to allow the shared code to be separated in different layers using MVVM pattern." +
"It also allows you to create some file templates.")]
[assembly: AddinAuthor("jzeferino")]
[assembly: AddinUrl("https://github.com/jzeferino/jzeferino.XSAddin")]
``` |
30570a97-063b-4129-810b-bbfa500efb2f | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using JSIL.Meta;
using JSIL.Proxy;
namespace JSIL.Proxies {
[JSProxy(
new[] {
"System.Collections.ArrayList",
"System.Collections.Hashtable",
"System.Collections.Generic.List`1",
"System.Collections.Generic.Dictionary`2",
"System.Collections.Generic.Stack`1",
"System.Collections.Generic.Queue`1",
"System.Collections.Generic.HashSet`1",
},
memberPolicy: JSProxyMemberPolicy.ReplaceNone,
inheritable: false
)]
public abstract class CollectionProxy<T> : IEnumerable {
[JSIsPure]
[JSResultIsNew]
System.Collections.IEnumerator IEnumerable.GetEnumerator () {
throw new InvalidOperationException();
}
[JSIsPure]
[JSResultIsNew]
public AnyType GetEnumerator () {
throw new InvalidOperationException();
}
}
}
```
Fix MemberwiseClone calls being generated for .GetEnumerator() on dictionary keys/values collections. | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
using JSIL.Meta;
using JSIL.Proxy;
namespace JSIL.Proxies {
[JSProxy(
new[] {
"System.Collections.ArrayList",
"System.Collections.Hashtable",
"System.Collections.Generic.List`1",
"System.Collections.Generic.Dictionary`2",
"System.Collections.Generic.Stack`1",
"System.Collections.Generic.Queue`1",
"System.Collections.Generic.HashSet`1",
"System.Collections.Hashtable/KeyCollection",
"System.Collections.Hashtable/ValueCollection",
"System.Collections.Generic.Dictionary`2/KeyCollection",
"System.Collections.Generic.Dictionary`2/ValueCollection"
},
memberPolicy: JSProxyMemberPolicy.ReplaceNone,
inheritable: false
)]
public abstract class CollectionProxy<T> : IEnumerable {
[JSIsPure]
[JSResultIsNew]
System.Collections.IEnumerator IEnumerable.GetEnumerator () {
throw new InvalidOperationException();
}
[JSIsPure]
[JSResultIsNew]
public AnyType GetEnumerator () {
throw new InvalidOperationException();
}
}
}
``` |
0efba6a3-45fb-4162-b36e-04bd671f4223 | {
"language": "C#"
} | ```c#
using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema.Tags;
namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
[TestFixture]
public class ArtistTagsTests
{
[Test]
public void Can_hit_endpoint()
{
ArtistTags tags = Api<ArtistTags>.Create
.WithParameter("artistId", "1")
.Please();
Assert.That(tags, Is.Not.Null);
Assert.That(tags.TagList.Count, Is.GreaterThan(0));
Assert.That(tags.TagList.FirstOrDefault().Id, Is.Not.Empty);
Assert.That(tags.TagList.Where(x => x.Id == "rock").FirstOrDefault().Text, Is.EqualTo("rock"));
}
[Test]
public void Can_hit_endpoint_with_paging()
{
ArtistTags artistBrowse = Api<ArtistTags>.Create
.WithParameter("artistId", "1")
.WithParameter("page", "2")
.WithParameter("pageSize", "1")
.Please();
Assert.That(artistBrowse, Is.Not.Null);
Assert.That(artistBrowse.Page, Is.EqualTo(2));
Assert.That(artistBrowse.PageSize, Is.EqualTo(1));
}
}
}```
Change artist in tags test | ```c#
using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema.Tags;
namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
[TestFixture]
public class ArtistTagsTests
{
[Test]
public void Can_hit_endpoint()
{
ArtistTags tags = Api<ArtistTags>.Create
.WithParameter("artistId", "1")
.Please();
Assert.That(tags, Is.Not.Null);
Assert.That(tags.TagList.Count, Is.GreaterThan(0));
Assert.That(tags.TagList.FirstOrDefault().Id, Is.Not.Empty);
Assert.That(tags.TagList.Where(x => x.Id == "rock").FirstOrDefault().Text, Is.EqualTo("rock"));
}
[Test]
public void Can_hit_endpoint_with_paging()
{
ArtistTags artistBrowse = Api<ArtistTags>.Create
.WithParameter("artistId", "2")
.WithParameter("page", "2")
.WithParameter("pageSize", "1")
.Please();
Assert.That(artistBrowse, Is.Not.Null);
Assert.That(artistBrowse.Page, Is.EqualTo(2));
Assert.That(artistBrowse.PageSize, Is.EqualTo(1));
}
}
}``` |
29724003-ad1d-48bb-99ff-d3329b37ffae | {
"language": "C#"
} | ```c#
using Photosphere.Mapping.Static;
namespace Photosphere.Mapping.Extensions
{
public static class MappingObjectExtensions
{
/// <summary> Map from source to existent object target</summary>
public static void MapTo<TSource, TTarget>(this TSource source, TTarget target)
where TTarget : class, new()
{
StaticMapper<TSource, TTarget>.Map(source, target);
}
/// <summary> Map from source to new object of TTarget</summary>
public static TTarget Map<TSource, TTarget>(this TSource source)
where TTarget : class, new()
{
return StaticMapper<TSource, TTarget>.Map(source);
}
/// <summary> Map from object source to existent object target</summary>
public static void MapToObject(this object source, object target)
{
StaticMapper.Map(source, target);
}
/// <summary> Map from object source to new object of TTarget</summary>
public static TTarget MapObject<TTarget>(this object source)
where TTarget : new()
{
return StaticMapper.Map<TTarget>(source);
}
}
}```
Make beauty to extensions API | ```c#
using Photosphere.Mapping.Static;
namespace Photosphere.Mapping.Extensions
{
public static class MappingObjectExtensions
{
/// <summary> Map from source to existent object target</summary>
public static void MapTo<TSource, TTarget>(this TSource source, TTarget target)
where TTarget : class, new()
{
StaticMapper<TSource, TTarget>.Map(source, target);
}
/// <summary> Map from object source to existent object target</summary>
public static void MapToObject(this object source, object target)
{
StaticMapper.Map(source, target);
}
/// <summary> Map from source to new object of TTarget</summary>
public static TTarget Map<TSource, TTarget>(this TSource source)
where TTarget : class, new()
{
return StaticMapper<TSource, TTarget>.Map(source);
}
/// <summary> Map from object source to new object of TTarget</summary>
public static TTarget MapObject<TTarget>(this object source)
where TTarget : new()
{
return StaticMapper.Map<TTarget>(source);
}
}
}``` |
8b22acdd-cbba-4839-b1a0-aac852f98207 | {
"language": "C#"
} | ```c#
using FluentValidation;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.Validation
{
public sealed class ApprenticeshipViewModelValidator : AbstractValidator<ApprenticeshipViewModel>
{
public ApprenticeshipViewModelValidator()
{
RuleFor(x => x.ULN).Matches("^$|^[1-9]{1}[0-9]{9}$").WithMessage("'ULN' is not in the correct format.");
RuleFor(x => x.Cost).Matches("^$|^[1-9]{1}[0-9]*$").WithMessage("Cost is not in the correct format");
}
}
}```
Update the validation messages for uln and cost | ```c#
using FluentValidation;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.Validation
{
public sealed class ApprenticeshipViewModelValidator : AbstractValidator<ApprenticeshipViewModel>
{
public ApprenticeshipViewModelValidator()
{
RuleFor(x => x.ULN).Matches("^$|^[1-9]{1}[0-9]{9}$").WithMessage("Please enter the unique learner number - this should be 10 digits long.");
RuleFor(x => x.Cost).Matches("^$|^[1-9]{1}[0-9]*$").WithMessage("Please enter the cost in whole pounds. For example, for £1500 you should enter 1500.");
}
}
}``` |
a0813fca-ba5f-461a-b2ac-22346adbae6b | {
"language": "C#"
} | ```c#
using System;
namespace Toggl.Phoebe
{
public static class Build
{
#warning Please fill in build settings and make git assume this file is unchanged.
#region Phoebe build config
public static readonly Uri ApiUrl = new Uri ("https://toggl.com/api/");
public static readonly Uri ReportsApiUrl = new Uri ("https://toggl.com/reports/api/");
public static readonly Uri PrivacyPolicyUrl = new Uri ("https://toggl.com/privacy");
public static readonly Uri TermsOfServiceUrl = new Uri ("https://toggl.com/terms");
public static readonly string GoogleAnalyticsId = "";
public static readonly int GoogleAnalyticsPlanIndex = 1;
public static readonly int GoogleAnalyticsExperimentIndex = 2;
#endregion
#region Joey build configuration
#if __ANDROID__
public static readonly string AppIdentifier = "TogglJoey";
public static readonly string GcmSenderId = "";
public static readonly string BugsnagApiKey = "";
public static readonly string GooglePlayUrl = "https://play.google.com/store/apps/details?id=com.toggl.timer";
#endif
#endregion
#region Ross build configuration
#if __IOS__
public static readonly string AppStoreUrl = "itms-apps://itunes.com/apps/toggl/toggltimer";
public static readonly string AppIdentifier = "TogglRoss";
public static readonly string BugsnagApiKey = "";
public static readonly string GoogleOAuthClientId = "";
#endif
#endregion
}
}```
Add InsightsApiKey to conf file. | ```c#
using System;
namespace Toggl.Phoebe
{
public static class Build
{
#warning Please fill in build settings and make git assume this file is unchanged.
#region Phoebe build config
public static readonly Uri ApiUrl = new Uri ("https://toggl.com/api/");
public static readonly Uri ReportsApiUrl = new Uri ("https://toggl.com/reports/api/");
public static readonly Uri PrivacyPolicyUrl = new Uri ("https://toggl.com/privacy");
public static readonly Uri TermsOfServiceUrl = new Uri ("https://toggl.com/terms");
public static readonly string GoogleAnalyticsId = "";
public static readonly int GoogleAnalyticsPlanIndex = 1;
public static readonly int GoogleAnalyticsExperimentIndex = 2;
#endregion
#region Joey build configuration
#if __ANDROID__
public static readonly string AppIdentifier = "TogglJoey";
public static readonly string GcmSenderId = "";
public static readonly string BugsnagApiKey = "";
public static readonly string XamInsightsApiKey = "";
public static readonly string GooglePlayUrl = "https://play.google.com/store/apps/details?id=com.toggl.timer";
#endif
#endregion
#region Ross build configuration
#if __IOS__
public static readonly string AppStoreUrl = "itms-apps://itunes.com/apps/toggl/toggltimer";
public static readonly string AppIdentifier = "TogglRoss";
public static readonly string BugsnagApiKey = "";
public static readonly string GoogleOAuthClientId = "";
#endif
#endregion
}
}
``` |
8d931658-9c30-4c07-9bf0-cdec2a6e0fea | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace GRA.Data.Model
{
public class AvatarLayer : Abstract.BaseDbEntity
{
[Required]
public int SiteId { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
public int Position { get; set; }
public bool CanBeEmpty { get; set; }
public int GroupId { get; set; }
public int SortOrder { get; set; }
public bool DefaultLayer { get; set; }
public bool ShowItemSelector { get; set; }
public bool ShowColorSelector { get; set; }
[MaxLength(255)]
public string Icon { get; set; }
public decimal ZoomScale { get; set; }
public int ZoomYOffset { get; set; }
public ICollection<AvatarColor> AvatarColors { get; set; }
public ICollection<AvatarItem> AvatarItems { get; set; }
}
}
```
Add precision and scale to avatar zoom scale | ```c#
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace GRA.Data.Model
{
public class AvatarLayer : Abstract.BaseDbEntity
{
[Required]
public int SiteId { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
public int Position { get; set; }
public bool CanBeEmpty { get; set; }
public int GroupId { get; set; }
public int SortOrder { get; set; }
public bool DefaultLayer { get; set; }
public bool ShowItemSelector { get; set; }
public bool ShowColorSelector { get; set; }
[MaxLength(255)]
public string Icon { get; set; }
[Column(TypeName = "decimal(4,2)")]
public decimal ZoomScale { get; set; }
public int ZoomYOffset { get; set; }
public ICollection<AvatarColor> AvatarColors { get; set; }
public ICollection<AvatarItem> AvatarItems { get; set; }
}
}
``` |
5baead60-16fb-4cad-961d-b9aa073f4fb2 | {
"language": "C#"
} | ```c#
using System;
using Amazon.SQS.Model;
using JustEat.Testing;
using NSubstitute;
using NUnit.Framework;
namespace AwsTools.UnitTests.SqsNotificationListener
{
public class WhenThereAreExceptionsInSqsCalling : BaseQueuePollingTest
{
private int _sqsCallCounter;
protected override void Given()
{
TestWaitTime = 50;
base.Given();
Sqs.ReceiveMessage(Arg.Any<ReceiveMessageRequest>())
.Returns(x => { throw new Exception(); })
.AndDoes(x => { _sqsCallCounter++; });
}
[Then]
public void QueueIsPolledMoreThanOnce()
{
Assert.Greater(_sqsCallCounter, 1);
}
}
}```
Test requires longer to run on slower aws build agents | ```c#
using System;
using Amazon.SQS.Model;
using JustEat.Testing;
using NSubstitute;
using NUnit.Framework;
namespace AwsTools.UnitTests.SqsNotificationListener
{
public class WhenThereAreExceptionsInSqsCalling : BaseQueuePollingTest
{
private int _sqsCallCounter;
protected override void Given()
{
TestWaitTime = 1000;
base.Given();
Sqs.ReceiveMessage(Arg.Any<ReceiveMessageRequest>())
.Returns(x => { throw new Exception(); })
.AndDoes(x => { _sqsCallCounter++; });
}
[Then]
public void QueueIsPolledMoreThanOnce()
{
Assert.Greater(_sqsCallCounter, 1);
}
}
}``` |
24b83563-ca29-4bb0-86b1-3b56bd34a97e | {
"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 System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using static osu.Game.Users.User;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class UserHistoryGraph : UserGraph<DateTime, long>
{
private readonly LocalisableString tooltipCounterName;
[CanBeNull]
public UserHistoryCount[] Values
{
set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
}
public UserHistoryGraph(LocalisableString tooltipCounterName)
{
this.tooltipCounterName = tooltipCounterName;
}
protected override float GetDataPointHeight(long playCount) => playCount;
protected override UserGraphTooltipContent GetTooltipContent(DateTime date, long playCount)
{
return new UserGraphTooltipContent(
tooltipCounterName,
playCount.ToLocalisableString("N0"),
date.ToLocalisableString("MMMM yyyy"));
}
}
}
```
Use lambda spec for 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 System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using static osu.Game.Users.User;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class UserHistoryGraph : UserGraph<DateTime, long>
{
private readonly LocalisableString tooltipCounterName;
[CanBeNull]
public UserHistoryCount[] Values
{
set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
}
public UserHistoryGraph(LocalisableString tooltipCounterName)
{
this.tooltipCounterName = tooltipCounterName;
}
protected override float GetDataPointHeight(long playCount) => playCount;
protected override UserGraphTooltipContent GetTooltipContent(DateTime date, long playCount) =>
new UserGraphTooltipContent(
tooltipCounterName,
playCount.ToLocalisableString("N0"),
date.ToLocalisableString("MMMM yyyy"));
}
}
``` |
e4b74041-c12f-41bb-bb1d-78cb37adc8f2 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Mvc;
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class GetApprenticeshipRequest
{
[FromQuery]
public long? AccountId { get; set; }
[FromQuery]
public long? ProviderId { get; set; }
[FromQuery]
public int PageNumber { get; set; }
[FromQuery]
public int PageItemCount { get; set; }
[FromQuery]
public string SortField { get; set; }
[FromQuery]
public bool ReverseSort { get; set; }
}
}```
Remove dot net core dependency | ```c#
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class GetApprenticeshipRequest
{
public long? AccountId { get; set; }
public long? ProviderId { get; set; }
public int PageNumber { get; set; }
public int PageItemCount { get; set; }
public string SortField { get; set; }
public bool ReverseSort { get; set; }
}
}``` |
fa7099de-63f0-49f5-a864-c8d85bf1a25c | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
/// <summary>
/// RectTransforms do not scale 3d objects (such as unit cubes) to fit within their bounds.
/// This helper class will apply a scale to fit a unit cube into the bounds specified by the RectTransform.
/// The Z component is scaled to the min of the X and Y components.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class RectTransformCubeScaler : MonoBehaviour
{
private RectTransform rectTransform;
private Vector2 prevRectSize = default;
private void Start()
{
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
var size = rectTransform.rect.size;
if (prevRectSize != size)
{
prevRectSize = size;
this.transform.localScale = new Vector3(size.x, size.y, Mathf.Min(size.x, size.y));
}
}
}
```
Move REcttransform scaler into mrtk namespace | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// RectTransforms do not scale 3d objects (such as unit cubes) to fit within their bounds.
/// This helper class will apply a scale to fit a unit cube into the bounds specified by the RectTransform.
/// The Z component is scaled to the min of the X and Y components.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class RectTransformCubeScaler : MonoBehaviour
{
private RectTransform rectTransform;
private Vector2 prevRectSize = default;
private void Start()
{
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
var size = rectTransform.rect.size;
if (prevRectSize != size)
{
prevRectSize = size;
this.transform.localScale = new Vector3(size.x, size.y, Mathf.Min(size.x, size.y));
}
}
}
}
``` |
c990649f-1af2-454e-9659-ee6750df8a52 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using ArangoDB.Client;
using EventSourced.Net.ReadModel.Users.Internal.Documents;
namespace EventSourced.Net.ReadModel.Users.Internal.Queries
{
public class UserDocumentByContactChallengeCorrelationId : IQuery<Task<UserDocument>>
{
public Guid CorrelationId { get; }
internal UserDocumentByContactChallengeCorrelationId(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class HandleUserDocumentByContactChallengeCorrelationId : IHandleQuery<UserDocumentByContactChallengeCorrelationId, Task<UserDocument>>
{
private IArangoDatabase Db { get; }
public HandleUserDocumentByContactChallengeCorrelationId(IArangoDatabase db) {
Db = db;
}
public Task<UserDocument> Handle(UserDocumentByContactChallengeCorrelationId query) {
UserDocument user = Db.Query<UserDocument>()
.SingleOrDefault(x => AQL.In(query.CorrelationId, x.ContactChallenges.Select(y => y.CorrelationId)));
return Task.FromResult(user);
}
}
}
```
Fix bug with query after json ignoring user doc contact challenges. | ```c#
using System;
using System.Linq;
using System.Threading.Tasks;
using ArangoDB.Client;
using EventSourced.Net.ReadModel.Users.Internal.Documents;
namespace EventSourced.Net.ReadModel.Users.Internal.Queries
{
public class UserDocumentByContactChallengeCorrelationId : IQuery<Task<UserDocument>>
{
public Guid CorrelationId { get; }
internal UserDocumentByContactChallengeCorrelationId(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class HandleUserDocumentByContactChallengeCorrelationId : IHandleQuery<UserDocumentByContactChallengeCorrelationId, Task<UserDocument>>
{
private IArangoDatabase Db { get; }
public HandleUserDocumentByContactChallengeCorrelationId(IArangoDatabase db) {
Db = db;
}
public Task<UserDocument> Handle(UserDocumentByContactChallengeCorrelationId query) {
UserDocument user = Db.Query<UserDocument>()
.SingleOrDefault(x =>
AQL.In(query.CorrelationId, x.ContactEmailChallenges.Select(y => y.CorrelationId)) ||
AQL.In(query.CorrelationId, x.ContactSmsChallenges.Select(y => y.CorrelationId)));
return Task.FromResult(user);
}
}
}
``` |
d9c8828c-b107-4d35-8137-a571debcc10a | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
namespace SyncTrayzor.Syncthing.ApiClient
{
[JsonConverter(typeof(DefaultingStringEnumConverter))]
public enum EventType
{
Unknown,
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
FolderScanProgress,
DevicePaused,
DeviceResumed,
LoginAttempt,
ListenAddressChanged,
RelayStateChanged,
ExternalPortMappingChanged,
}
}
```
Add a missing event type | ```c#
using Newtonsoft.Json;
namespace SyncTrayzor.Syncthing.ApiClient
{
[JsonConverter(typeof(DefaultingStringEnumConverter))]
public enum EventType
{
Unknown,
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
FolderScanProgress,
DevicePaused,
DeviceResumed,
LoginAttempt,
ListenAddressChanged,
RelayStateChanged,
ExternalPortMappingChanged,
ListenAddressesChanged,
}
}
``` |
f6a397fd-20c3-4ad8-beae-f596ff7bbcf1 | {
"language": "C#"
} | ```c#
namespace Gigobyte.Mockaroo.Fields
{
public partial class JSONArrayField
{
public int Min { get; set; } = 1;
public int Max { get; set; } = 5;
public override string ToJson()
{
return $"{base.BaseJson()},\"minItems\":{Min},\"maxItems\":{Max}}}";
}
}
}```
Add limiter to JsonArrayField min and max properties | ```c#
namespace Gigobyte.Mockaroo.Fields
{
public partial class JSONArrayField
{
public int Min
{
get { return _min; }
set { _min = value.Between(0, 100); }
}
public int Max
{
get { return _max; }
set { _max = value.Between(0, 100); }
}
public override string ToJson()
{
return $"{base.BaseJson()},\"minItems\":{Min},\"maxItems\":{Max}}}";
}
#region Private Members
private int _min = 1, _max = 5;
#endregion Private Members
}
}``` |
40f9624b-c387-4181-9973-abfddb3da9b2 | {
"language": "C#"
} | ```c#
@model Badges.Models.Shared.ExperienceViewModel
<div id="work-container" class="container work">
<div class="row">
@foreach (var work in @Model.SupportingWorks)
{
@* <div class="col-md-4"> *@
<div class="@work.Type work-item-box">
@Html.Partial("_ViewWork", work)
<p>@work.Description</p>
</div>
@* </div> *@
}
</div>
</div>
```
Add edit / remove buttons to each file on experience page | ```c#
@model Badges.Models.Shared.ExperienceViewModel
<div id="work-container" class="container work">
<div class="row">
@foreach (var work in @Model.SupportingWorks)
{
@* <div class="col-md-4"> *@
<div class="@work.Type work-item-box">
@Html.Partial("_ViewWork", work)
<p>@work.Description<br />
<a href="#edit">
<i class="icon-edit"></i>
</a>
<a href="#delete">
<i class="icon-remove"></i>
</a>
</p>
<div></div>
</div>
@* </div> *@
}
</div>
</div>
``` |
ba39b467-eb7d-4833-b129-f284b8866355 | {
"language": "C#"
} | ```c#
//
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
/// </summary>
#else
/// <summary>
/// Defines extension method to shuffle what implements IEnumerable interface.
/// </summary>
#endif
public static class ShuffleExtensions
{
#if JHELP
/// <summary>
/// IEnumerableをシャッフルしたものを返す
/// </summary>
/// <typeparam name="T">IEnumerableの要素の型</typeparam>
/// <param name="s">TのIEnumerable</param>
/// <returns>シャッフルされたIEnumerable</returns>
#else
/// <summary>
/// Returns shuffled IEnumerable of T.
/// </summary>
/// <typeparam name="T">Type of element of IEnumerable.</typeparam>
/// <param name="s">IEnumerable of T.</param>
/// <returns>Shuffled IEnumerable of T.</returns>
#endif
public static IOrderedEnumerable<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid());
}
}
```
Make Shuffle() returns IList to avoid delayed execution. | ```c#
//
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
/// </summary>
#else
/// <summary>
/// Defines extension method to shuffle what implements IEnumerable interface.
/// </summary>
#endif
public static class ShuffleExtensions
{
#if JHELP
/// <summary>
/// IEnumerableをシャッフルしたIListを返す
/// </summary>
/// <typeparam name="T">IEnumerableの要素の型</typeparam>
/// <param name="s">TのIEnumerable</param>
/// <returns>シャッフルされたTのIList</returns>
#else
/// <summary>
/// Returns shuffled IList of T.
/// </summary>
/// <typeparam name="T">Type of element of IEnumerable.</typeparam>
/// <param name="s">IEnumerable of T.</param>
/// <returns>Shuffled IList of T.</returns>
#endif
public static IList<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid()).ToList();
}
}
``` |
32aabb04-36c5-49b2-8b4a-2ec452c6785d | {
"language": "C#"
} | ```c#
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
namespace MsgPack.Serialization
{
/// <summary>
/// Define options of <see cref="SerializationMethodGeneratorManager"/>
/// </summary>
public enum SerializationMethodGeneratorOption
{
#if !SILVERLIGHT
/// <summary>
/// The generated method IL can be dumped to the current directory.
/// </summary>
CanDump,
/// <summary>
/// The entire generated method can be collected by GC when it is no longer used.
/// </summary>
CanCollect,
#endif
/// <summary>
/// Prefer performance. This options is default.
/// </summary>
Fast
}
}
```
Add comments for internal API. | ```c#
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.ComponentModel;
namespace MsgPack.Serialization
{
/// <summary>
/// Define options of <see cref="SerializationMethodGeneratorManager"/>
/// </summary>
public enum SerializationMethodGeneratorOption
{
#if !SILVERLIGHT
/// <summary>
/// The generated method IL can be dumped to the current directory.
/// It is intended for the runtime, you cannot use this option.
/// </summary>
[EditorBrowsable( EditorBrowsableState.Never )]
CanDump,
/// <summary>
/// The entire generated method can be collected by GC when it is no longer used.
/// </summary>
CanCollect,
#endif
/// <summary>
/// Prefer performance. This options is default.
/// </summary>
Fast
}
}
``` |
8e3b7094-a764-4953-a9c5-c04cdf0cb0c7 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Eco;
// 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("Eco")]
[assembly: AssemblyDescription("Yet another configuration library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Eco")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// SettingsComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bfdd8cf1-3e3b-4120-8d3a-68bd506ec4b3")]
// 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.*")]
[assembly:SettingsAssembly("Eco.Elements")]
```
Move all Eco setting types to the Eco namespace | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Eco;
// 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("Eco")]
[assembly: AssemblyDescription("Yet another configuration library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Eco")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// SettingsComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bfdd8cf1-3e3b-4120-8d3a-68bd506ec4b3")]
// 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.*")]
[assembly:SettingsAssembly("Eco")]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.