doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
82b2662a-52e1-4965-be8d-761247418dc1 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
namespace CefSharp.Example
{
public static class CefExample
{
public const string DefaultUrl = "custom://cefsharp/BindingTest.html";
// Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
private const bool debuggingSubProcess = true;
public static void Init()
{
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
//settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
if (debuggingSubProcess)
{
settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe";
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
});
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
}
}
}
```
Add environment check to determine architecture | ```c#
using System;
using System.Linq;
namespace CefSharp.Example
{
public static class CefExample
{
public const string DefaultUrl = "custom://cefsharp/BindingTest.html";
// Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
private const bool debuggingSubProcess = true;
public static void Init()
{
var settings = new CefSettings();
settings.RemoteDebuggingPort = 8088;
//settings.CefCommandLineArgs.Add("renderer-process-limit", "1");
//settings.CefCommandLineArgs.Add("renderer-startup-dialog", "renderer-startup-dialog");
if (debuggingSubProcess)
{
var architecture = Environment.Is64BitProcess ? "x64" : "x86";
settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\" + architecture + "\\Debug\\CefSharp.BrowserSubprocess.exe";
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
});
if (!Cef.Initialize(settings))
{
if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
{
Environment.Exit(0);
}
else
{
return;
}
}
}
}
}
``` |
9c921898-dc4a-4d1b-b01d-a5335b0faead | {
"language": "C#"
} | ```c#
using System.Reflection;
#if DEBUG
[assembly: AssemblyProduct("Ensure.That (Debug)")]
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyProduct("Ensure.That (Release)")]
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyDescription("Yet another guard clause project.")]
[assembly: AssemblyCompany("Daniel Wertheim")]
[assembly: AssemblyCopyright("Copyright © Daniel Wertheim")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]```
Include version to get e.g ReSharper happy. | ```c#
using System.Reflection;
#if DEBUG
[assembly: AssemblyProduct("Ensure.That (Debug)")]
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyProduct("Ensure.That (Release)")]
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyDescription("Yet another guard clause project.")]
[assembly: AssemblyCompany("Daniel Wertheim")]
[assembly: AssemblyCopyright("Copyright © Daniel Wertheim")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.10.1.*")]
[assembly: AssemblyFileVersion("0.10.1")]``` |
54d9e8b1-4bd3-4026-935b-ac3d6621b42a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace Moq.Tests
{
public class ExtensionsFixture
{
[Fact]
public void IsMockeableReturnsFalseForValueType()
{
Assert.False(typeof(int).IsMockeable());
}
// [Fact]
// public void OnceDoesNotThrowOnSecondCallIfCountWasResetBefore()
// {
// var mock = new Mock<IFooReset>();
// mock.Setup(foo => foo.Execute("ping"))
// .Returns("ack")
// .AtMostOnce();
// Assert.Equal("ack", mock.Object.Execute("ping"));
// mock.ResetAllCalls();
// Assert.DoesNotThrow(() => mock.Object.Execute("ping"));
// }
}
public interface IFooReset
{
object Execute(string ping);
}
}
```
Fix poorly written test (sorry). | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace Moq.Tests
{
public class ExtensionsFixture
{
#region Public Methods
[Fact]
public void IsMockeableReturnsFalseForValueType()
{
Assert.False(typeof(int).IsMockeable());
}
[Fact]
public void OnceDoesNotThrowOnSecondCallIfCountWasResetBefore()
{
var mock = new Mock<IFooReset>();
mock.Setup(foo => foo.Execute("ping")).Returns("ack");
mock.Object.Execute("ping");
mock.ResetAllCalls();
mock.Object.Execute("ping");
mock.Verify(o => o.Execute("ping"), Times.Once());
}
#endregion
}
public interface IFooReset
{
#region Public Methods
object Execute(string ping);
#endregion
}
}
``` |
66bfb69d-afde-44ff-9af5-2961eadf7d8e | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Threading.Tasks;
namespace Dotnet.Script.Core
{
public class ScriptDownloader
{
public async Task<string> Download(string uri)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
using (HttpContent content = response.Content)
{
var mediaType = content.Headers.ContentType.MediaType?.ToLowerInvariant().Trim();
switch (mediaType)
{
case null:
case "":
case "text/plain":
return await content.ReadAsStringAsync();
case "application/gzip":
case "application/x-gzip":
using (var stream = await content.ReadAsStreamAsync())
using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzip))
return await reader.ReadToEndAsync();
default:
throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https");
}
}
}
}
}
}
}
```
Support remote scripts with empty/null Content Type | ```c#
using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Threading.Tasks;
namespace Dotnet.Script.Core
{
public class ScriptDownloader
{
public async Task<string> Download(string uri)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
using (HttpContent content = response.Content)
{
var mediaType = content.Headers.ContentType?.MediaType?.ToLowerInvariant().Trim();
switch (mediaType)
{
case null:
case "":
case "text/plain":
return await content.ReadAsStringAsync();
case "application/gzip":
case "application/x-gzip":
using (var stream = await content.ReadAsStreamAsync())
using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzip))
return await reader.ReadToEndAsync();
default:
throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https");
}
}
}
}
}
}
}
``` |
edbd09f4-a7de-4dff-952b-9a590a21484c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class MartijnVanDijk : IAmAMicrosoftMVP, IAmAXamarinMVP
{
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://medium.com/feed/@martijn00"); }
}
public string FirstName => "Martijn";
public string LastName => "Van Dijk";
public string StateOrRegion => "Amsterdam, Netherlands";
public string EmailAddress => "mhvdijk@gmail.com";
public string ShortBioOrTagLine => "";
public Uri WebSite => new Uri("https://medium.com/@martijn00");
public string TwitterHandle => "mhvdijk";
public string GravatarHash => "22155f520ab611cf04f76762556ca3f5";
public string GitHubHandle => string.Empty;
public GeoPosition Position => new GeoPosition(52.3702160, 4.8951680);
}
}
```
Add bio and Github profile | ```c#
using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class MartijnVanDijk : IAmAMicrosoftMVP, IAmAXamarinMVP
{
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://medium.com/feed/@martijn00"); }
}
public string FirstName => "Martijn";
public string LastName => "Van Dijk";
public string StateOrRegion => "Amsterdam, Netherlands";
public string EmailAddress => "mhvdijk@gmail.com";
public string ShortBioOrTagLine => "is a Xamarin and Microsoft MVP working with MvvmCross";
public Uri WebSite => new Uri("https://medium.com/@martijn00");
public string TwitterHandle => "mhvdijk";
public string GravatarHash => "22155f520ab611cf04f76762556ca3f5";
public string GitHubHandle => "martijn00";
public GeoPosition Position => new GeoPosition(52.3702160, 4.8951680);
}
}
``` |
3d35b04e-e519-4ca7-907e-051552059a8f | {
"language": "C#"
} | ```c#
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Internals.Mapping
{
using System;
using Reflection;
public class NullableValueObjectMapper<T, TValue> :
IObjectMapper<T>
where TValue : struct
{
readonly ReadWriteProperty<T> _property;
public NullableValueObjectMapper(ReadWriteProperty<T> property)
{
_property = property;
}
public void ApplyTo(T obj, IObjectValueProvider valueProvider)
{
object value;
if (valueProvider.TryGetValue(_property.Property.Name, out value))
{
TValue? nullableValue = value as TValue?;
if (!nullableValue.HasValue)
nullableValue = (TValue)Convert.ChangeType(value, typeof(TValue));
_property.Set(obj, nullableValue);
}
}
}
}```
Use a type converter to try and convert values | ```c#
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Internals.Mapping
{
using System;
using System.ComponentModel;
using Reflection;
public class NullableValueObjectMapper<T, TValue> :
IObjectMapper<T>
where TValue : struct
{
readonly ReadWriteProperty<T> _property;
public NullableValueObjectMapper(ReadWriteProperty<T> property)
{
_property = property;
}
public void ApplyTo(T obj, IObjectValueProvider valueProvider)
{
object value;
if (valueProvider.TryGetValue(_property.Property.Name, out value))
{
TValue? nullableValue = null;
if (value != null)
{
var converter = TypeDescriptor.GetConverter(typeof(TValue));
nullableValue = converter.CanConvertFrom(value.GetType())
? (TValue)converter.ConvertFrom(value)
: default(TValue?);
}
_property.Set(obj, nullableValue);
}
}
}
}``` |
7b5855b3-b6f8-417e-9e59-18c07634cae3 | {
"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.Runtime.InteropServices;
namespace osu.Framework.Platform.Linux.SDL2
{
public class SDL2Clipboard : Clipboard
{
private const string lib = "libSDL2.so";
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)]
internal static extern void SDL_free(IntPtr ptr);
/// <returns>Returns the clipboard text on success or <see cref="IntPtr.Zero"/> on failure. </returns>
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)]
internal static extern IntPtr SDL_GetClipboardText();
[DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)]
internal static extern int SDL_SetClipboardText(string text);
public override string GetText()
{
IntPtr ptrToText = SDL_GetClipboardText();
string text = Marshal.PtrToStringAnsi(ptrToText);
SDL_free(ptrToText);
return text;
}
public override void SetText(string selectedText)
{
SDL_SetClipboardText(selectedText);
}
}
}
```
Remove no longer required SDL2 P/Invokes in Linux clipboard | ```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 SDL2;
namespace osu.Framework.Platform.Linux.SDL2
{
public class SDL2Clipboard : Clipboard
{
public override string GetText() => SDL.SDL_GetClipboardText();
public override void SetText(string selectedText) => SDL.SDL_SetClipboardText(selectedText);
}
}
``` |
a49f15ec-a641-4548-b8a8-b9ecb095b5ee | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using IdentityServer.Contrib.JsonWebKeyAdapter;
using Microsoft.Azure.KeyVault;
using Microsoft.Extensions.OptionsModel;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.IdentityModel.Protocols;
namespace IdentityServer3.Contrib.AzureKeyVaultTokenSigningService
{
public class AzureKeyVaultPublicKeyProvider : IPublicKeyProvider
{
private readonly AzureKeyVaultTokenSigningServiceOptions _options;
private readonly AzureKeyVaultAuthentication _authentication;
private JsonWebKey _jwk;
/// <summary>
/// Initializes a new instance of the <see cref="AzureKeyVaultTokenSigningService"/> class.
/// </summary>
/// <param name="options">The options.</param>
public AzureKeyVaultPublicKeyProvider(IOptions<AzureKeyVaultTokenSigningServiceOptions> options)
{
_options = options.Value;
_authentication = new AzureKeyVaultAuthentication(_options.ClientId, _options.ClientSecret);
}
public async Task<IEnumerable<JsonWebKey>> GetAsync()
{
if (_jwk == null)
{
var keyVaultClient = new KeyVaultClient(_authentication.KeyVaultClientAuthenticationCallback);
var keyBundle = await keyVaultClient.GetKeyAsync(_options.KeyIdentifier).ConfigureAwait(false);
_jwk = new JsonWebKey(keyBundle.Key.ToString());
}
return new List<JsonWebKey> { _jwk };
}
}
}
```
Tidy up some unused usings | ```c#
using System.Collections.Generic;
using System.Threading.Tasks;
using IdentityServer.Contrib.JsonWebKeyAdapter;
using Microsoft.Azure.KeyVault;
using Microsoft.Extensions.OptionsModel;
using Microsoft.IdentityModel.Protocols;
namespace IdentityServer3.Contrib.AzureKeyVaultTokenSigningService
{
public class AzureKeyVaultPublicKeyProvider : IPublicKeyProvider
{
private readonly AzureKeyVaultTokenSigningServiceOptions _options;
private readonly AzureKeyVaultAuthentication _authentication;
private JsonWebKey _jwk;
/// <summary>
/// Initializes a new instance of the <see cref="AzureKeyVaultTokenSigningService"/> class.
/// </summary>
/// <param name="options">The options.</param>
public AzureKeyVaultPublicKeyProvider(IOptions<AzureKeyVaultTokenSigningServiceOptions> options)
{
_options = options.Value;
_authentication = new AzureKeyVaultAuthentication(_options.ClientId, _options.ClientSecret);
}
public async Task<IEnumerable<JsonWebKey>> GetAsync()
{
if (_jwk == null)
{
var keyVaultClient = new KeyVaultClient(_authentication.KeyVaultClientAuthenticationCallback);
var keyBundle = await keyVaultClient.GetKeyAsync(_options.KeyIdentifier).ConfigureAwait(false);
_jwk = new JsonWebKey(keyBundle.Key.ToString());
}
return new List<JsonWebKey> { _jwk };
}
}
}
``` |
3ef5bb56-4cd6-447b-883f-af6543333727 | {
"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.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Remote.Storage
{
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
[Export(typeof(RemotePersistentStorageLocationService))]
internal class RemotePersistentStorageLocationService : IPersistentStorageLocationService
{
private static readonly object _gate = new object();
private static readonly Dictionary<SolutionId, string> _idToStorageLocation = new Dictionary<SolutionId, string>();
public string GetStorageLocation(Solution solution)
{
string result;
_idToStorageLocation.TryGetValue(solution.Id, out result);
return result;
}
public bool IsSupported(Workspace workspace)
{
lock (_gate)
{
return _idToStorageLocation.ContainsKey(workspace.CurrentSolution.Id);
}
}
public static void UpdateStorageLocation(SolutionId id, string storageLocation)
{
lock (_gate)
{
_idToStorageLocation[id] = storageLocation;
}
}
}
}```
Store OOP server persistence database in a different file. | ```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.Collections.Generic;
using System.Composition;
using System.IO;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Remote.Storage
{
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
[Export(typeof(RemotePersistentStorageLocationService))]
internal class RemotePersistentStorageLocationService : IPersistentStorageLocationService
{
private static readonly object _gate = new object();
private static readonly Dictionary<SolutionId, string> _idToStorageLocation = new Dictionary<SolutionId, string>();
public string GetStorageLocation(Solution solution)
{
string result;
_idToStorageLocation.TryGetValue(solution.Id, out result);
return result;
}
public bool IsSupported(Workspace workspace)
{
lock (_gate)
{
return _idToStorageLocation.ContainsKey(workspace.CurrentSolution.Id);
}
}
public static void UpdateStorageLocation(SolutionId id, string storageLocation)
{
lock (_gate)
{
// Store the esent database in a different location for the out of proc server.
_idToStorageLocation[id] = Path.Combine(storageLocation, "Server");
}
}
}
}``` |
c516300d-91dd-4419-8e5a-962a1910e466 | {
"language": "C#"
} | ```c#
@inherits UmbracoViewPage<IMaster>
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
this.page.url = '@Umbraco.NiceUrlWithDomain(Model.Id)';
this.page.identifier = '@Model.Id';
this.page.title = '@Model.SeoMetadata.Title';
};
(function () {
var d = document,
s = d.createElement('script');
s.src = '//stevenhar-land.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
}());
</script>
```
Update Disqus partial to use node name for the page title configuration variable | ```c#
@inherits UmbracoViewPage<IPublishedContent>
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
this.page.url = '@Umbraco.NiceUrlWithDomain(Model.Id)';
this.page.identifier = '@Model.Id';
this.page.title = '@Model.Name';
};
(function () {
var d = document,
s = d.createElement('script');
s.src = '//stevenhar-land.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
}());
</script>
``` |
9ec9293b-bd46-4689-8e97-ac4bd37aaef2 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.Net.WebSockets")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[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("9a9e41ae-1494-4d87-a66f-a4019ff68ce5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: NeutralResourcesLanguage("en-us")]
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyProduct("Microsoft ASP.NET Core")]
```
Fix assembly metadata to fix package verifier warnings | ```c#
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft.Net.WebSockets")]
[assembly: ComVisible(false)]
[assembly: Guid("9a9e41ae-1494-4d87-a66f-a4019ff68ce5")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: NeutralResourcesLanguage("en-us")]
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyProduct("Microsoft ASP.NET Core")]
``` |
dbbb7b1f-2598-493d-b7a8-dbb07fb998cc | {
"language": "C#"
} | ```c#
namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public char Unknown1;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(Stream f, ref GafFrameData e)
{
BinaryReader b = new BinaryReader(f);
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.Unknown1 = b.ReadChar();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
```
Change char to byte in gaf frame header | ```c#
namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte Unknown1;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(Stream f, ref GafFrameData e)
{
BinaryReader b = new BinaryReader(f);
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.Unknown1 = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
``` |
0186a53f-c301-48e0-b24a-1f1410c07367 | {
"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 questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <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();
}
}
}
```
Update 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 questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <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();
}
}
}
``` |
6a988de7-a4cf-481b-97a6-560b45dc9146 | {
"language": "C#"
} | ```c#
@using StackExchange.Opserver.Data.SQL
@{
Layout = null;
var clusters = SQLModule.Clusters;
var standalone = SQLModule.StandaloneInstances;
}
@helper RenderInstances(IEnumerable<SQLInstance> instances)
{
foreach (var i in instances)
{
var props = i.ServerProperties.SafeData(true);
<a class="list-group-item" href="?node=@i.Name.UrlEncode()">
@i.IconSpan() @i.Name
<span class="badge" title="@props.FullVersion">@props.MajorVersion</span>
</a>
}
}
<h5 class="page-header">Please select a SQL instance.</h5>
<div class="row">
@foreach (var c in clusters)
{
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">@c.Name</div>
<div class="panel-body small list-group">
@RenderInstances(c.Nodes)
</div>
</div>
</div>
}
@if (standalone.Any())
{
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">Standalone</div>
<div class="panel-body small list-group">
@RenderInstances(standalone)
</div>
</div>
</div>
}
</div>```
Add version to SQL instance selector screen | ```c#
@using StackExchange.Opserver.Data.SQL
@{
Layout = null;
var clusters = SQLModule.Clusters;
var standalone = SQLModule.StandaloneInstances;
}
@helper RenderInstances(IEnumerable<SQLInstance> instances, bool showVersion)
{
foreach (var i in instances)
{
var props = i.ServerProperties.SafeData(true);
<a class="list-group-item" href="?node=@i.Name.UrlEncode()">
@i.IconSpan() @i.Name
<span class="badge" title="@props.FullVersion">
@props.MajorVersion
@if (showVersion)
{
<span class="small"> (@i.Version.ToString())</span>
}
</span>
</a>
}
}
@helper RenderList(IEnumerable<SQLInstance> instances, string title)
{
var versions = instances.Select(n => n.Version).Distinct().ToList();
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">
@title
@if (versions.Count == 1)
{
<span class="small text-muted">(Version @versions[0].ToString())</span>
}
</div>
<div class="panel-body small list-group">
@RenderInstances(instances, versions.Count > 1)
</div>
</div>
</div>
}
<h5 class="page-header">Please select a SQL instance.</h5>
<div class="row">
@foreach (var c in clusters)
{
@RenderList(c.Nodes, c.Name)
}
@if (standalone.Any())
{
@RenderList(standalone, "Standalone")
}
</div>``` |
fa8ba843-75d1-4e56-b137-a799fa8e4b6c | {
"language": "C#"
} | ```c#
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
/// <content>
/// Contains the <see cref="NCryptCreatePersistedKeyFlags"/> nested type.
/// </content>
public static partial class NCrypt
{
/// <summary>
/// Flags that may be passed to the <see cref="NCryptCreatePersistedKey(SafeProviderHandle, out SafeKeyHandle, string, string, LegacyKeySpec, NCryptCreatePersistedKeyFlags)"/> method.
/// </summary>
[Flags]
public enum NCryptCreatePersistedKeyFlags
{
/// <summary>
/// No flags.
/// </summary>
None = 0x0,
/// <summary>
/// The key applies to the local computer. If this flag is not present, the key applies to the current user.
/// </summary>
NCRYPT_MACHINE_KEY_FLAG,
/// <summary>
/// If a key already exists in the container with the specified name, the existing key will be overwritten. If this flag is not specified and a key with the specified name already exists, this function will return <see cref="SECURITY_STATUS.NTE_EXISTS"/>.
/// </summary>
NCRYPT_OVERWRITE_KEY_FLAG,
}
}
}
```
Add values for a couple of enum values | ```c#
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
/// <content>
/// Contains the <see cref="NCryptCreatePersistedKeyFlags"/> nested type.
/// </content>
public static partial class NCrypt
{
/// <summary>
/// Flags that may be passed to the <see cref="NCryptCreatePersistedKey(SafeProviderHandle, out SafeKeyHandle, string, string, LegacyKeySpec, NCryptCreatePersistedKeyFlags)"/> method.
/// </summary>
[Flags]
public enum NCryptCreatePersistedKeyFlags
{
/// <summary>
/// No flags.
/// </summary>
None = 0x0,
/// <summary>
/// The key applies to the local computer. If this flag is not present, the key applies to the current user.
/// </summary>
NCRYPT_MACHINE_KEY_FLAG = 0x20,
/// <summary>
/// If a key already exists in the container with the specified name, the existing key will be overwritten. If this flag is not specified and a key with the specified name already exists, this function will return <see cref="SECURITY_STATUS.NTE_EXISTS"/>.
/// </summary>
NCRYPT_OVERWRITE_KEY_FLAG = 0x80,
}
}
}
``` |
7b3f67af-0d04-422a-8a9d-000e9e51bf09 | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace MessageBird.Objects
{
public class Recipient
{
public enum RecipientStatus { Scheduled, Sent, Buffered, Delivered, DeliveryFailed };
[JsonProperty("recipient")]
public long Msisdn {get; set;}
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public RecipientStatus? Status {get; set;}
[JsonProperty("statusDatetime")]
public DateTime? StatusDatetime {get; set;}
public Recipient(long msisdn)
{
Msisdn = msisdn;
}
}
}
```
Fix incorrect serialization of recipient status | ```c#
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
namespace MessageBird.Objects
{
public class Recipient
{
public enum RecipientStatus
{
// Message status
[EnumMember(Value = "scheduled")]
Scheduled,
[EnumMember(Value = "sent")]
Sent,
[EnumMember(Value = "buffered")]
Buffered,
[EnumMember(Value = "delivered")]
Delivered,
[EnumMember(Value = "delivery_failed")]
DeliveryFailed,
};
[JsonProperty("recipient")]
public long Msisdn {get; set;}
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public RecipientStatus? Status {get; set;}
[JsonProperty("statusDatetime")]
public DateTime? StatusDatetime {get; set;}
public Recipient(long msisdn)
{
Msisdn = msisdn;
}
}
}
``` |
27d3776a-6246-4948-b86f-d85e541817b7 | {
"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;
using System.IO;
namespace Microsoft.DotNet.Execute
{
internal class Interop
{
public static bool GetUnixVersion(out string result)
{
result = null;
const string OSReleaseFileName = @"/etc/os-release";
if (File.Exists(OSReleaseFileName))
{
string content = File.ReadAllText(OSReleaseFileName);
int idIndex = content.IndexOf("ID");
int versionIndex = content.IndexOf("VERSION_ID");
if (idIndex != -1 && versionIndex != -1)
{
string id = content.Substring(idIndex + 3, content.IndexOf(Environment.NewLine, idIndex + 3) - idIndex - 3);
string version = content.Substring(versionIndex + 12, content.IndexOf('"', versionIndex + 12) - versionIndex - 12);
result = $"{id}.{version}";
}
}
return result != null;
}
}
}
```
Improve parsing /etc/os-release, handle more cases. | ```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;
using System.IO;
namespace Microsoft.DotNet.Execute
{
internal class Interop
{
public static bool GetUnixVersion(out string result)
{
const string OSId = "ID=";
const string OSVersionId = "VERSION_ID=";
result = null;
const string OSReleaseFileName = @"/etc/os-release";
if (File.Exists(OSReleaseFileName))
{
string[] content = File.ReadAllLines(OSReleaseFileName);
string id = null, version = null;
foreach (string line in content)
{
if (line.StartsWith(OSId))
{
id = line.Substring(OSId.Length, line.Length - OSId.Length);
}
else if (line.StartsWith(OSVersionId))
{
int startOfVersion = line.IndexOf('"', OSVersionId.Length) + 1;
int endOfVersion = startOfVersion == 0 ? line.Length : line.IndexOf('"', startOfVersion);
if (startOfVersion == 0)
startOfVersion = OSVersionId.Length;
version = line.Substring(startOfVersion, endOfVersion - startOfVersion);
}
// Skip parsing rest of the file contents.
if (id != null && version != null)
break;
}
result = $"{id}.{version}";
}
return result != null;
}
}
}
``` |
0a545cf3-1f78-45dc-b050-92b745eeccd5 | {
"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.
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils
{
public abstract class Identity
{
public string Name { get; protected set; }
}
public class Project : Identity
{
public Project(string name, string relativePath = null)
{
Name = name;
RelativePath = relativePath;
}
public string RelativePath { get; }
}
public class ProjectReference : Identity
{
public ProjectReference(string name)
{
Name = name;
}
}
public class AssemblyReference : Identity
{
public AssemblyReference(string name)
{
Name = name;
}
}
public class PackageReference : Identity
{
public string Version { get; }
public PackageReference(string name, string version)
{
Name = name;
Version = version;
}
}
}
```
Set default relative path for Project Identity in Integration tests | ```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.IO;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils
{
public abstract class Identity
{
public string Name { get; protected set; }
}
public class Project : Identity
{
public Project(string name, string projectExtension = ".csproj", string relativePath = null)
{
Name = name;
if (string.IsNullOrWhiteSpace(relativePath))
{
RelativePath = Path.Combine(name, name + projectExtension);
}
else
{
RelativePath = relativePath;
}
}
/// <summary>
/// This path is relative to the Solution file. Default value is set to ProjectName\ProjectName.csproj
/// </summary>
public string RelativePath { get; }
}
public class ProjectReference : Identity
{
public ProjectReference(string name)
{
Name = name;
}
}
public class AssemblyReference : Identity
{
public AssemblyReference(string name)
{
Name = name;
}
}
public class PackageReference : Identity
{
public string Version { get; }
public PackageReference(string name, string version)
{
Name = name;
Version = version;
}
}
}
``` |
1c0afcbb-3d5b-443d-80a9-0a911e849d20 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Legacy;
using osu.Game.Rulesets.Replays.Types;
namespace osu.Game.Rulesets.Catch.Replays
{
public class CatchReplayFrame : ReplayFrame, IConvertibleReplayFrame
{
public float Position;
public bool Dashing;
public CatchReplayFrame()
{
}
public CatchReplayFrame(double time, float? position = null, bool dashing = false)
: base(time)
{
Position = position ?? -1;
Dashing = dashing;
}
public void ConvertFrom(LegacyReplayFrame legacyFrame, Beatmap beatmap)
{
// Todo: This needs to be re-scaled
Position = legacyFrame.Position.X;
Dashing = legacyFrame.ButtonState == ReplayButtonState.Left1;
}
}
}
```
Fix catch legacy replay positions not being relative to playfield size | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Legacy;
using osu.Game.Rulesets.Replays.Types;
namespace osu.Game.Rulesets.Catch.Replays
{
public class CatchReplayFrame : ReplayFrame, IConvertibleReplayFrame
{
public float Position;
public bool Dashing;
public CatchReplayFrame()
{
}
public CatchReplayFrame(double time, float? position = null, bool dashing = false)
: base(time)
{
Position = position ?? -1;
Dashing = dashing;
}
public void ConvertFrom(LegacyReplayFrame legacyFrame, Beatmap beatmap)
{
Position = legacyFrame.Position.X / CatchPlayfield.BASE_WIDTH;
Dashing = legacyFrame.ButtonState == ReplayButtonState.Left1;
}
}
}
``` |
e4e63416-1d17-4615-836a-322774d8d945 | {
"language": "C#"
} | ```c#
#region
using System.Net;
using Tabster.Core.Data.Processing;
using Tabster.Core.Types;
#endregion
namespace Tabster.Core.Searching
{
/// <summary>
/// Tab service which enables searching.
/// </summary>
public interface ISearchService
{
/// <summary>
/// Service name.
/// </summary>
string Name { get; }
/// <summary>
/// Associated parser.
/// </summary>
ITablatureWebpageImporter Parser { get; }
/// <summary>
/// Service flags.
/// </summary>
SearchServiceFlags Flags { get; }
/// <summary>
/// Proxy settings.
/// </summary>
WebProxy Proxy { get; }
/// <summary>
/// Determines whether the service supports ratings.
/// </summary>
bool SupportsRatings { get; }
/// <summary>
/// Queries service and returns results based on search parameters.
/// </summary>
/// <param name="query"> Search query. </param>
SearchResult[] Search(SearchQuery query);
///<summary>
/// Determines whether a specific TabType is supported by the service.
///</summary>
///<param name="type"> The type to check. </param>
///<returns> True if the type is supported by the service; otherwise, False. </returns>
bool SupportsTabType(TabType type);
}
}```
Add setter to Proxy property. | ```c#
#region
using System.Net;
using Tabster.Core.Data.Processing;
using Tabster.Core.Types;
#endregion
namespace Tabster.Core.Searching
{
/// <summary>
/// Tab service which enables searching.
/// </summary>
public interface ISearchService
{
/// <summary>
/// Service name.
/// </summary>
string Name { get; }
/// <summary>
/// Associated parser.
/// </summary>
ITablatureWebpageImporter Parser { get; }
/// <summary>
/// Service flags.
/// </summary>
SearchServiceFlags Flags { get; }
/// <summary>
/// Proxy settings.
/// </summary>
WebProxy Proxy { get; set; }
/// <summary>
/// Determines whether the service supports ratings.
/// </summary>
bool SupportsRatings { get; }
/// <summary>
/// Queries service and returns results based on search parameters.
/// </summary>
/// <param name="query"> Search query. </param>
SearchResult[] Search(SearchQuery query);
///<summary>
/// Determines whether a specific TabType is supported by the service.
///</summary>
///<param name="type"> The type to check. </param>
///<returns> True if the type is supported by the service; otherwise, False. </returns>
bool SupportsTabType(TabType type);
}
}``` |
86b52b30-8dd6-4b84-b90f-c515d82a14ef | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BTDB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BTDB")]
[assembly: AssemblyCopyright("Copyright Boris Letocha 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. 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("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("2.13.0.0")]
[assembly: AssemblyFileVersion("2.13.0.0")]
[assembly: InternalsVisibleTo("BTDBTest")]
```
Bump it even more to follow semver | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BTDB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BTDB")]
[assembly: AssemblyCopyright("Copyright Boris Letocha 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. 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("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: InternalsVisibleTo("BTDBTest")]
``` |
45b5b0d5-aeae-47aa-8869-76109304921b | {
"language": "C#"
} | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.5.0.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.5.0.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif```
Upgrade version from 5.5.0 to 5.5.1 | ```c#
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.5.1.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.5.1.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif``` |
c0a8e088-79d2-4db2-924d-b153958606bb | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
namespace XtabFileOpener.TableContainer.SpreadsheetTableContainer.ExcelTableContainer
{
/// <summary>
/// Implementation of Table, that manages an Excel table
/// </summary>
internal class ExcelTable : Table
{
internal ExcelTable(string name, Range cells) : base(name)
{
/*
* "The only difference between this property and the Value property is that the Value2 property
* doesn’t use the Currency and Date data types. You can return values formatted with these
* data types as floating-point numbers by using the Double data type."
* */
tableArray = cells.Value;
firstRowContainsColumnNames = true;
}
}
}
```
Convert DateTime objects to ISO format that is understood by DBUnit. DateTime objects are returned by Excel if cell is formatted for date display. | ```c#
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("XtabFileOpenerTest")]
namespace XtabFileOpener.TableContainer.SpreadsheetTableContainer.ExcelTableContainer
{
/// <summary>
/// Implementation of Table, that manages an Excel table.
/// Cells that are date formatted in Excel will be converted to ISO strings.
/// </summary>
internal class ExcelTable : Table
{
internal ExcelTable(string name, Range cells) : base(name)
{
tableArray = cells.Value;
firstRowContainsColumnNames = true;
ConvertDateTimesToIsoFormat();
}
private void ConvertDateTimesToIsoFormat()
{
string iso_time_format = "{0:yyyy-MM-dd HH:mm:ss}";
string iso_time_format_with_miliseconds = "{0:yyyy-MM-dd HH:mm:ss.ffffff}00";
for (int i = tableArray.GetLowerBound(0); i <= tableArray.GetUpperBound(0); i++)
{
for (int j = tableArray.GetLowerBound(1); j <= tableArray.GetUpperBound(1); j++)
{
object cell = tableArray[i, j];
if (cell is DateTime && cell != null)
{
DateTime dt = (DateTime) cell;
string format = (dt.Millisecond > 0) ? iso_time_format_with_miliseconds : iso_time_format;
tableArray[i, j] = String.Format(format, dt);
}
}
}
}
}
}
``` |
bc064523-6e9e-41bc-bdf6-454a13a16da4 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.NHibernate")]
[assembly: AssemblyDescription("Autofac Integration for NHibernate")]
[assembly: ComVisible(false)]```
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | ```c#
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Extras.NHibernate")]
[assembly: ComVisible(false)]
``` |
a89084c3-0b5d-43c1-8d44-34bb267f9dc9 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
namespace Example1
{
public class Program
{
public static void Main (string [] args)
{
using (var streamer = new AudioStreamer ("ws://agektmr.node-ninja.com:3000/socket"))
//using (var streamer = new AudioStreamer ("ws://localhost:3000/socket"))
{
string name;
do {
Console.Write ("Input your name> ");
name = Console.ReadLine ();
}
while (name.Length == 0);
streamer.Connect (name);
Console.WriteLine ("\nType \"exit\" to exit.\n");
while (true) {
Thread.Sleep (1000);
Console.Write ("> ");
var msg = Console.ReadLine ();
if (msg == "exit")
break;
streamer.Write (msg);
}
}
}
}
}
```
Fix a few for Example1 | ```c#
using System;
using System.Threading;
namespace Example1
{
public class Program
{
public static void Main (string [] args)
{
using (var streamer = new AudioStreamer ("ws://agektmr.node-ninja.com:3000/socket"))
//using (var streamer = new AudioStreamer ("ws://localhost:3000/socket"))
{
string name;
do {
Console.Write ("Input your name> ");
name = Console.ReadLine ();
}
while (name.Length == 0);
streamer.Connect (name);
Console.WriteLine ("\nType 'exit' to exit.\n");
while (true) {
Thread.Sleep (1000);
Console.Write ("> ");
var msg = Console.ReadLine ();
if (msg == "exit")
break;
streamer.Write (msg);
}
}
}
}
}
``` |
190ed903-cca7-4211-90f0-428547472e97 | {
"language": "C#"
} | ```c#
using System;
using NUnit.Framework;
namespace Google.Apis.Tools.CodeGen.Tests
{
[TestFixture()]
public class NewtonsoftObjectToJsonTest
{
[Test()]
public void TestCase ()
{
Assert.Fail("Not tested yet");
}
}
}
```
Correct the namespace and add copyright message. | ```c#
/*
Copyright 2010 Google Inc
Licensed under the Apache License, Version 2.0 (the ""License"");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an ""AS IS"" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using NUnit.Framework;
namespace Google.Apis.Tools.CodeGen.Tests.Decorator.ServiceDecorator
{
[TestFixture()]
public class NewtonsoftObjectToJsonTest
{
[Test()]
public void TestCase ()
{
Assert.Fail("Not tested yet");
}
}
}
``` |
75a653bc-f209-44cb-8e99-046e057d05f3 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SiliconStudio.Core.Mathematics;
using SiliconStudio.Xenko.Input;
using SiliconStudio.Xenko.Engine;
using SiliconStudio.Xenko.UI.Controls;
using XenkoToolkit.Samples.Core;
namespace XenkoToolkit.Samples.Core
{
public class NavigationButtonHandler : SyncScript
{
public UIPage Page { get; set; }
public string ButtonName { get; set; }
public INavigationButtonAction ButtonAction { get; set; } = new NavigateToScreen();
public override void Start()
{
Page = Page ?? this.Entity.Get<UIComponent>()?.Page;
if (string.IsNullOrEmpty(ButtonName) || ButtonAction == null) return;
// Initialization of the script.
if (Page?.RootElement.FindName(ButtonName) is Button button)
{
button.Click += Button_Click;
}
}
private async void Button_Click(object sender, SiliconStudio.Xenko.UI.Events.RoutedEventArgs e)
{
var navService = Game.Services.GetService<ISceneNavigationService>();
await ButtonAction?.Handle(navService);
}
public override void Update()
{
// Do stuff every new frame
}
}
}
```
Remove button handler on Cancel. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SiliconStudio.Core.Mathematics;
using SiliconStudio.Xenko.Input;
using SiliconStudio.Xenko.Engine;
using SiliconStudio.Xenko.UI.Controls;
using XenkoToolkit.Samples.Core;
namespace XenkoToolkit.Samples.Core
{
public class NavigationButtonHandler : SyncScript
{
public UIPage Page { get; set; }
public string ButtonName { get; set; }
public INavigationButtonAction ButtonAction { get; set; } = new NavigateToScreen();
public override void Start()
{
Page = Page ?? this.Entity.Get<UIComponent>()?.Page;
if (string.IsNullOrEmpty(ButtonName) || ButtonAction == null) return;
// Initialization of the script.
if (Page?.RootElement.FindName(ButtonName) is Button button)
{
button.Click += Button_Click;
}
}
private async void Button_Click(object sender, SiliconStudio.Xenko.UI.Events.RoutedEventArgs e)
{
var navService = Game.Services.GetService<ISceneNavigationService>();
await ButtonAction?.Handle(navService);
}
public override void Update()
{
// Do stuff every new frame
}
public override void Cancel()
{
if (Page?.RootElement.FindName(ButtonName) is Button button)
{
button.Click -= Button_Click;
}
}
}
}
``` |
73b906bb-0fe6-47c0-bb37-0d3eca0d1d2b | {
"language": "C#"
} | ```c#
using System;
using Xunit;
namespace SparkPost.Tests
{
public partial class ClientTests
{
public partial class UserAgentTests
{
private readonly Client.Settings settings;
public UserAgentTests()
{
settings = new Client.Settings();
}
[Fact]
public void It_should_default_to_the_library_version()
{
Assert.Equal($"csharp-sparkpost/2.0.0", settings.UserAgent);
}
[Fact]
public void It_should_allow_the_user_agent_to_be_changed()
{
var userAgent = Guid.NewGuid().ToString();
settings.UserAgent = userAgent;
Assert.Equal(userAgent, settings.UserAgent);
}
}
}
}
```
Make agent test less brittle | ```c#
using System;
using Xunit;
namespace SparkPost.Tests
{
public partial class ClientTests
{
public partial class UserAgentTests
{
private readonly Client.Settings settings;
public UserAgentTests()
{
settings = new Client.Settings();
}
[Fact]
public void It_should_default_to_the_library_version()
{
Assert.StartsWith($"csharp-sparkpost/2.", settings.UserAgent);
}
[Fact]
public void It_should_allow_the_user_agent_to_be_changed()
{
var userAgent = Guid.NewGuid().ToString();
settings.UserAgent = userAgent;
Assert.Equal(userAgent, settings.UserAgent);
}
}
}
}
``` |
e111036d-819a-431f-9086-1c7f19d03755 | {
"language": "C#"
} | ```c#
using Flood.Tools.RPCGen;
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;
namespace RPCGen.Tests
{
[TestFixture]
class RPCGenTests
{
[Test]
public void MainTest()
{
string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests");
Directory.CreateDirectory(genDirectory);
var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll");
var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll");
var sourcePdbPath = Path.GetFullPath("RPCGen.Tests.Services.pdb");
var destPdbPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.pdb");
System.IO.File.Copy(sourceDllPath, destDllPath, true);
if (File.Exists(sourcePdbPath))
System.IO.File.Copy(sourcePdbPath, destPdbPath, true);
var args = new string[]
{
String.Format("-o={0}", genDirectory),
destDllPath
};
var ret = Flood.Tools.RPCGen.Program.Main(args);
Assert.AreEqual(0, ret);
}
}
}
```
Refactor assembly name in MainTests. | ```c#
using NUnit.Framework;
using System;
using System.IO;
namespace RPCGen.Tests
{
[TestFixture]
class RPCGenTests
{
[Test]
public void MainTest()
{
string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests");
Directory.CreateDirectory(genDirectory);
var assemblyName = "RPCGen.Tests.Services";
var assemblyDll = assemblyName + ".dll";
var assemblyPdb = assemblyName + ".pdb";
var sourceDllPath = Path.GetFullPath(assemblyDll);
var destDllPath = Path.Combine(genDirectory, assemblyDll);
var sourcePdbPath = Path.GetFullPath(assemblyPdb);
var destPdbPath = Path.Combine(genDirectory, assemblyPdb);
File.Copy(sourceDllPath, destDllPath, true);
if (File.Exists(sourcePdbPath))
File.Copy(sourcePdbPath, destPdbPath, true);
var args = new string[]
{
String.Format("-o={0}", genDirectory),
destDllPath
};
var ret = Flood.Tools.RPCGen.Program.Main(args);
Assert.AreEqual(0, ret);
}
}
}
``` |
1d3d0d43-d6f0-4eb6-9eea-1041eaeebcac | {
"language": "C#"
} | ```c#
@inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" @AccordionHelper() href="#collapse-@Model.UniqueId">@Model.Header </a>
</h4>
</div>
<div id="collapse-@Model.UniqueId" class="panel-collapse collapse">
<div class="panel-body">
@Html.Raw(@Model.Body)
</div>
@if (Model.Footer != null && !String.IsNullOrEmpty(Convert.ToString(Model.Footer)))
{
<div class="panel-footer">
@Model.Footer
</div>
}
</div>
</div>
@helper AccordionHelper()
{
if (Model != null && Model.AccordionParent != null)
{
@:data-parent="@Model.AccordionParent"
}
}
```
Set accordion panels to be default collapsed | ```c#
@inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" @AccordionHelper() href="#collapse-@Model.UniqueId">@Model.Header </a>
</h4>
</div>
<div id="collapse-@Model.UniqueId" class="panel-collapse collapse">
<div class="panel-body">
@Html.Raw(@Model.Body)
</div>
@if (Model.Footer != null && !String.IsNullOrEmpty(Convert.ToString(Model.Footer)))
{
<div class="panel-footer">
@Model.Footer
</div>
}
</div>
</div>
@helper AccordionHelper()
{
if (Model != null && Model.AccordionParent != null)
{
@:data-parent="@Model.AccordionParent" class="collapsed"
}
}
``` |
4314288a-5281-415d-9094-cf82bf2c788b | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ValueUtilsTest {
class SampleClass {
public SampleEnum AnEnum;
public string AutoPropWithPrivateBackingField { get; set; }
}
}
```
Add tricky cases to test class: - nullable primitives - non-nullable custom structs - nullable structs | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ValueUtilsTest {
struct CustomStruct {
public int Bla;
}
class SampleClass {
public SampleEnum AnEnum;
public int? NullableField;
public CustomStruct PlainStruct;
public CustomStruct? NullableStruct;
public string AutoPropWithPrivateBackingField { get; set; }
}
}
``` |
833b8151-8ca7-4209-b083-80836c110c08 | {
"language": "C#"
} | ```c#
#if NETCOREAPP2_1
using System.Runtime.InteropServices;
#endif
namespace XSharp.Launch
{
internal static class RuntimeHelper
{
public static bool IsWindows
{
get
{
#if NETCOREAPP2_1
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#elif NET471
return true;
#endif
}
}
public static bool IsOSX
{
get
{
#if NETCOREAPP2_1
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
#elif NET471
return false;
#endif
}
}
public static bool IsLinux
{
get
{
#if NETCOREAPP2_1
return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
#elif NET471
return false;
#endif
}
}
}
}
```
Update conditional code blocks with new versions | ```c#
#if NETCOREAPP2_0
using System.Runtime.InteropServices;
#endif
namespace XSharp.Launch
{
internal static class RuntimeHelper
{
public static bool IsWindows
{
get
{
#if NETCOREAPP2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#elif NET472
return true;
#endif
}
}
public static bool IsOSX
{
get
{
#if NETCOREAPP2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
#elif NET472
return false;
#endif
}
}
public static bool IsLinux
{
get
{
#if NETCOREAPP2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
#elif NET472
return false;
#endif
}
}
}
}
``` |
4267923e-e41c-48c1-a5eb-0969a1b6d4d8 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Post.Users.Responses;
[TestClass]
public class TraktUserFollowUserRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserFollowUserRequestIsNotAbstract()
{
typeof(TraktUserFollowUserRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserFollowUserRequestIsSealed()
{
typeof(TraktUserFollowUserRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserFollowUserRequestIsSubclassOfATraktSingleItemBodylessPostRequest()
{
typeof(TraktUserFollowUserRequest).IsSubclassOf(typeof(ATraktSingleItemBodylessPostRequest<TraktUserFollowUserPostResponse>)).Should().BeTrue();
}
}
}
```
Add test for authorization requirement in TraktUserFollowUserRequest | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post.Bodyless;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Post.Users.Responses;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserFollowUserRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserFollowUserRequestIsNotAbstract()
{
typeof(TraktUserFollowUserRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserFollowUserRequestIsSealed()
{
typeof(TraktUserFollowUserRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserFollowUserRequestIsSubclassOfATraktSingleItemBodylessPostRequest()
{
typeof(TraktUserFollowUserRequest).IsSubclassOf(typeof(ATraktSingleItemBodylessPostRequest<TraktUserFollowUserPostResponse>)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserFollowUserRequestHasAuthorizationRequired()
{
var request = new TraktUserFollowUserRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
``` |
39f65390-0ae3-479a-9655-8570c0779f33 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using OpenQA.Selenium;
namespace Protractor
{
internal class JavaScriptBy : By
{
private string script;
private object[] args;
public JavaScriptBy(string script, params object[] args)
{
this.script = script;
this.args = args;
}
public IWebElement RootElement { get; set; }
public override IWebElement FindElement(ISearchContext context)
{
ReadOnlyCollection<IWebElement> elements = this.FindElements(context);
return elements.Count > 0 ? elements[0] : null;
}
public override ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
{
// Create script arguments
object[] scriptArgs = new object[this.args.Length + 1];
scriptArgs[0] = this.RootElement;
Array.Copy(this.args, 0, scriptArgs, 1, this.args.Length);
ReadOnlyCollection<IWebElement> elements = ((IJavaScriptExecutor)context).ExecuteScript(this.script, scriptArgs) as ReadOnlyCollection<IWebElement>;
if (elements == null)
{
elements = new ReadOnlyCollection<IWebElement>(new List<IWebElement>(0));
}
return elements;
}
}
}```
Fix NgBy when used with IWebElement | ```c#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using OpenQA.Selenium;
using OpenQA.Selenium.Internal;
namespace Protractor
{
internal class JavaScriptBy : By
{
private string script;
private object[] args;
public JavaScriptBy(string script, params object[] args)
{
this.script = script;
this.args = args;
}
public IWebElement RootElement { get; set; }
public override IWebElement FindElement(ISearchContext context)
{
ReadOnlyCollection<IWebElement> elements = this.FindElements(context);
return elements.Count > 0 ? elements[0] : null;
}
public override ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
{
// Create script arguments
object[] scriptArgs = new object[this.args.Length + 1];
scriptArgs[0] = this.RootElement;
Array.Copy(this.args, 0, scriptArgs, 1, this.args.Length);
// Get JS executor
IJavaScriptExecutor jsExecutor = context as IJavaScriptExecutor;
if (jsExecutor == null)
{
IWrapsDriver wrapsDriver = context as IWrapsDriver;
if (wrapsDriver != null)
{
jsExecutor = wrapsDriver.WrappedDriver as IJavaScriptExecutor;
}
}
if (jsExecutor == null)
{
throw new NotSupportedException("Could not get an IJavaScriptExecutor instance from the context.");
}
ReadOnlyCollection<IWebElement> elements = jsExecutor.ExecuteScript(this.script, scriptArgs) as ReadOnlyCollection<IWebElement>;
if (elements == null)
{
elements = new ReadOnlyCollection<IWebElement>(new List<IWebElement>(0));
}
return elements;
}
}
}``` |
4cb4a8f2-00fe-478c-92cf-84aa22722fc6 | {
"language": "C#"
} | ```c#
using System;
using DHT.Utils.Logging;
namespace DHT.Desktop {
sealed class Arguments {
private static readonly Log Log = Log.ForType<Arguments>();
public static Arguments Empty => new(Array.Empty<string>());
public string? DatabaseFile { get; }
public ushort? ServerPort { get; }
public string? ServerToken { get; }
public Arguments(string[] args) {
for (int i = 0; i < args.Length; i++) {
string key = args[i];
if (i >= args.Length - 1) {
Log.Warn("Missing value for command line argument: " + key);
continue;
}
string value = args[++i];
switch (key) {
case "-db":
DatabaseFile = value;
continue;
case "-port": {
if (ushort.TryParse(value, out var port)) {
ServerPort = port;
}
else {
Log.Warn("Invalid port number: " + value);
}
continue;
}
case "-token":
ServerToken = value;
continue;
default:
Log.Warn("Unknown command line argument: " + key);
break;
}
}
}
}
}
```
Allow database file path to be passed as the first command line argument to the app | ```c#
using System;
using DHT.Utils.Logging;
namespace DHT.Desktop {
sealed class Arguments {
private static readonly Log Log = Log.ForType<Arguments>();
public static Arguments Empty => new(Array.Empty<string>());
public string? DatabaseFile { get; }
public ushort? ServerPort { get; }
public string? ServerToken { get; }
public Arguments(string[] args) {
for (int i = 0; i < args.Length; i++) {
string key = args[i];
string value;
if (i == 0 && !key.StartsWith('-')) {
value = key;
key = "-db";
}
else if (i >= args.Length - 1) {
Log.Warn("Missing value for command line argument: " + key);
continue;
}
else {
value = args[++i];
}
switch (key) {
case "-db":
DatabaseFile = value;
continue;
case "-port": {
if (ushort.TryParse(value, out var port)) {
ServerPort = port;
}
else {
Log.Warn("Invalid port number: " + value);
}
continue;
}
case "-token":
ServerToken = value;
continue;
default:
Log.Warn("Unknown command line argument: " + key);
break;
}
}
}
}
}
``` |
ac1ac961-b960-4f70-92c7-da3d064958a7 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Diagnostics;
using Xp.Cert;
namespace Xp.Cert.Commands
{
public partial class Update : Command
{
const string SECURITY_EXECUTABLE = "/usr/bin/security";
const string SECURITY_ARGUMENTS = "find-certificate -a -p";
const string SECURITY_KEYCHAIN = "/System/Library/Keychains/SystemRootCertificates.keychain";
/// <summary>Execute this command</summary>
public void MacOSX(FileInfo bundle)
{
var proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = SECURITY_EXECUTABLE;
proc.StartInfo.Arguments = SECURITY_ARGUMENTS + " " + SECURITY_KEYCHAIN;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = false;
try {
Console.Write("> From {0}: [", SECURITY_KEYCHAIN);
proc.Start();
using (var writer = new StreamWriter(bundle.Open(FileMode.Create)))
{
var count = 0;
proc.OutputDataReceived += (sender, e) => {
if (e.Data.StartsWith(BEGIN_CERT))
{
count++;
Console.Write('.');
}
writer.WriteLine(e.Data);
};
proc.BeginOutputReadLine();
proc.WaitForExit();
Console.WriteLine("]");
Console.WriteLine(" {0} certificates", count);
}
}
finally
{
proc.Close();
}
}
}
}```
Add a newline to Mac OS X output | ```c#
using System;
using System.IO;
using System.Diagnostics;
using Xp.Cert;
namespace Xp.Cert.Commands
{
public partial class Update : Command
{
const string SECURITY_EXECUTABLE = "/usr/bin/security";
const string SECURITY_ARGUMENTS = "find-certificate -a -p";
const string SECURITY_KEYCHAIN = "/System/Library/Keychains/SystemRootCertificates.keychain";
/// <summary>Execute this command</summary>
public void MacOSX(FileInfo bundle)
{
var proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = SECURITY_EXECUTABLE;
proc.StartInfo.Arguments = SECURITY_ARGUMENTS + " " + SECURITY_KEYCHAIN;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = false;
try {
Console.Write("> From {0}: [", SECURITY_KEYCHAIN);
proc.Start();
using (var writer = new StreamWriter(bundle.Open(FileMode.Create)))
{
var count = 0;
proc.OutputDataReceived += (sender, e) => {
if (e.Data.StartsWith(BEGIN_CERT))
{
count++;
Console.Write('.');
}
writer.WriteLine(e.Data);
};
proc.BeginOutputReadLine();
proc.WaitForExit();
Console.WriteLine("]");
Console.WriteLine(" {0} certificates", count);
Console.WriteLine();
}
}
finally
{
proc.Close();
}
}
}
}``` |
2982b231-4d6c-4c6b-accc-0f5a2c7b2b4a | {
"language": "C#"
} | ```c#
using System;
using Android.App;
using AndroidHUD;
namespace XHUD
{
public enum MaskType
{
// None = 1,
Clear,
Black,
// Gradient
}
public static class HUD
{
public static Activity MyActivity;
public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black)
{
AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType);
}
public static void Dismiss()
{
AndHUD.Shared.Dismiss(HUD.MyActivity);
}
public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
public static void ShowToast (string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
}
}
```
Format change to match other methods; | ```c#
using System;
using Android.App;
using AndroidHUD;
namespace XHUD
{
public enum MaskType
{
// None = 1,
Clear,
Black,
// Gradient
}
public static class HUD
{
public static Activity MyActivity;
public static void Show(string message, int progress = -1, MaskType maskType = MaskType.Black)
{
AndHUD.Shared.Show(HUD.MyActivity, message, progress,(AndroidHUD.MaskType)maskType);
}
public static void Dismiss()
{
AndHUD.Shared.Dismiss(HUD.MyActivity);
}
public static void ShowToast(string message, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)MaskType.Black, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
public static void ShowToast(string message, MaskType maskType, bool showToastCentered = true, double timeoutMs = 1000)
{
AndHUD.Shared.ShowToast(HUD.MyActivity, message, (AndroidHUD.MaskType)maskType, TimeSpan.FromSeconds(timeoutMs/1000), showToastCentered);
}
}
}
``` |
7ca53123-f7d8-4d73-98ad-04f377d3a3d3 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base.Get;
using Enums;
using Objects.Basic;
using Objects.Get.Movies.Common;
using System.Collections.Generic;
internal class TraktMoviesMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedMovie>, TraktMostPlayedMovie>
{
internal TraktMoviesMostPlayedRequest(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 => "movies/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 movies request. | ```c#
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base;
using Base.Get;
using Enums;
using Objects.Basic;
using Objects.Get.Movies.Common;
using System.Collections.Generic;
internal class TraktMoviesMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedMovie>, TraktMostPlayedMovie>
{
internal TraktMoviesMostPlayedRequest(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 => "movies/played{/period}{?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;
}
}
``` |
f4af7627-d096-4960-a13a-b7dcd7f5582e | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
using System.Windows.Data;
namespace GoldenAnvil.Utility.Windows
{
public static class CommonConverters
{
public static readonly IValueConverter BooleanNot = new BooleanNotConverter();
private sealed class BooleanNotConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException(@"The target must be a boolean.");
return !((bool) value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
}
```
Add BooleanToVisibility, IsEqual, and IsEqualToVisbility converters | ```c#
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace GoldenAnvil.Utility.Windows
{
public static class CommonConverters
{
public static readonly IValueConverter BooleanNot = new BooleanNotConverter();
public static readonly IValueConverter BooleanToVisibility = new BooleanToVisibilityConverter();
public static readonly IValueConverter IsEqual = new IsEqualConverter();
public static readonly IValueConverter IsEqualToVisibility = new IsEqualToVisibilityConverter();
private sealed class BooleanNotConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!targetType.IsAssignableFrom(typeof(bool)))
throw new InvalidOperationException(@"The target must be assignable from a boolean.");
return !((bool) value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
private sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!targetType.IsAssignableFrom(typeof(Visibility)))
throw new InvalidOperationException(@"The target must be assignable from a Visibility.");
return (bool) value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
private sealed class IsEqualConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!targetType.IsAssignableFrom(typeof(bool)))
throw new InvalidOperationException(@"The target must be assignable from a boolean.");
return object.Equals(value, parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
private sealed class IsEqualToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!targetType.IsAssignableFrom(typeof(Visibility)))
throw new InvalidOperationException(@"The target must be assignable from a Visibility.");
return object.Equals(value, parameter) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
}
``` |
2f4a07a9-0b0a-4c6f-a384-1bf2179c3686 | {
"language": "C#"
} | ```c#
using System;
using System.Xml;
using System.Xml.Linq;
namespace openvassharp
{
public class OpenVASManager : IDisposable
{
private OpenVASSession _session;
public OpenVASManager ()
{
_session = null;
}
public OpenVASManager(OpenVASSession session)
{
if (session != null)
_session = session;
}
public XDocument GetVersion() {
return _session.ExecuteCommand (XDocument.Parse ("<get_version />"));
}
private bool CheckSession()
{
if (!_session.Stream.CanRead)
throw new Exception("Bad session");
return true;
}
public void Dispose()
{
_session = null;
}
}
}
```
Remove un-needed ctor and other methods | ```c#
using System;
using System.Xml;
using System.Xml.Linq;
namespace openvassharp
{
public class OpenVASManager : IDisposable
{
private OpenVASSession _session;
public OpenVASManager(OpenVASSession session)
{
if (session != null)
_session = session;
}
public XDocument GetVersion() {
return _session.ExecuteCommand (XDocument.Parse ("<get_version />"));
}
public void Dispose()
{
_session = null;
}
}
}
``` |
c1d22fb1-d42d-401d-a529-f15b4280fae3 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Delete;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
[TestClass]
public class TraktUserUnfollowUserRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserUnfollowUserRequestIsNotAbstract()
{
typeof(TraktUserUnfollowUserRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserUnfollowUserRequestIsSealed()
{
typeof(TraktUserUnfollowUserRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserUnfollowUserRequestIsSubclassOfATraktNoContentDeleteRequest()
{
typeof(TraktUserUnfollowUserRequest).IsSubclassOf(typeof(ATraktNoContentDeleteRequest)).Should().BeTrue();
}
}
}
```
Add test for authorization requirement in TraktUserUnfollowUserRequest | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Delete;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserUnfollowUserRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserUnfollowUserRequestIsNotAbstract()
{
typeof(TraktUserUnfollowUserRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserUnfollowUserRequestIsSealed()
{
typeof(TraktUserUnfollowUserRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserUnfollowUserRequestIsSubclassOfATraktNoContentDeleteRequest()
{
typeof(TraktUserUnfollowUserRequest).IsSubclassOf(typeof(ATraktNoContentDeleteRequest)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserUnfollowUserRequestHasAuthorizationRequired()
{
var request = new TraktUserUnfollowUserRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
``` |
0e4b3867-0e63-4e85-8f5d-7517625afdb1 | {
"language": "C#"
} | ```c#
namespace Fixie
{
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
public static class ReflectionExtensions
{
public static string TypeName(this object o)
{
return o?.GetType().FullName;
}
public static bool IsVoid(this MethodInfo method)
{
return method.ReturnType == typeof(void);
}
public static bool IsStatic(this Type type)
{
return type.IsAbstract && type.IsSealed;
}
public static bool Has<TAttribute>(this Type type) where TAttribute : Attribute
{
return type.GetTypeInfo().GetCustomAttributes<TAttribute>(false).Any();
}
public static bool HasOrInherits<TAttribute>(this Type type) where TAttribute : Attribute
{
return type.GetTypeInfo().GetCustomAttributes<TAttribute>(true).Any();
}
public static bool Has<TAttribute>(this MethodInfo method) where TAttribute : Attribute
{
return method.GetCustomAttributes<TAttribute>(false).Any();
}
public static bool HasOrInherits<TAttribute>(this MethodInfo method) where TAttribute : Attribute
{
return method.GetCustomAttributes<TAttribute>(true).Any();
}
public static bool IsAsync(this MethodInfo method)
{
return method.Has<AsyncStateMachineAttribute>();
}
public static bool IsInNamespace(this Type type, string ns)
{
var actual = type.Namespace;
if (ns == null)
return actual == null;
if (actual == null)
return false;
return actual == ns || actual.StartsWith(ns + ".");
}
public static void Dispose(this object o)
{
(o as IDisposable)?.Dispose();
}
}
}```
Remove calls to GetTypeInfo() now that they are no longer necessary for our minimum netcoreapp version of 2.0. | ```c#
namespace Fixie
{
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
public static class ReflectionExtensions
{
public static string TypeName(this object o)
{
return o?.GetType().FullName;
}
public static bool IsVoid(this MethodInfo method)
{
return method.ReturnType == typeof(void);
}
public static bool IsStatic(this Type type)
{
return type.IsAbstract && type.IsSealed;
}
public static bool Has<TAttribute>(this Type type) where TAttribute : Attribute
{
return type.GetCustomAttributes<TAttribute>(false).Any();
}
public static bool HasOrInherits<TAttribute>(this Type type) where TAttribute : Attribute
{
return type.GetCustomAttributes<TAttribute>(true).Any();
}
public static bool Has<TAttribute>(this MethodInfo method) where TAttribute : Attribute
{
return method.GetCustomAttributes<TAttribute>(false).Any();
}
public static bool HasOrInherits<TAttribute>(this MethodInfo method) where TAttribute : Attribute
{
return method.GetCustomAttributes<TAttribute>(true).Any();
}
public static bool IsAsync(this MethodInfo method)
{
return method.Has<AsyncStateMachineAttribute>();
}
public static bool IsInNamespace(this Type type, string ns)
{
var actual = type.Namespace;
if (ns == null)
return actual == null;
if (actual == null)
return false;
return actual == ns || actual.StartsWith(ns + ".");
}
public static void Dispose(this object o)
{
(o as IDisposable)?.Dispose();
}
}
}``` |
a17f221d-b28d-45d5-89c9-5a838b668d6a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using Xunit;
namespace CSharpViaTest.Collections._20_YieldPractices
{
[Medium]
public class TakeUntilCatchingAnException
{
readonly int indexThatWillThrow = new Random().Next(2, 10);
IEnumerable<int> GetSequenceOfData()
{
for (int i = 0;; ++i)
{
if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); }
yield return i;
}
}
#region Please modifies the code to pass the test
static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_get_sequence_until_an_exception_is_thrown()
{
IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData());
Assert.Equal(Enumerable.Range(0, indexThatWillThrow + 1), sequence);
}
[Fact]
public void should_get_sequence_given_normal_collection()
{
var sequence = new[] { 1, 2, 3 };
IEnumerable<int> result = TakeUntilError(sequence);
Assert.Equal(sequence, result);
}
}
}```
Fix take until exception error. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using Xunit;
namespace CSharpViaTest.Collections._20_YieldPractices
{
[Medium]
public class TakeUntilCatchingAnException
{
readonly int indexThatWillThrow = new Random().Next(2, 10);
IEnumerable<int> GetSequenceOfData()
{
for (int i = 0;; ++i)
{
if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); }
yield return i;
}
}
#region Please modifies the code to pass the test
static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_get_sequence_until_an_exception_is_thrown()
{
IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData());
Assert.Equal(Enumerable.Range(0, indexThatWillThrow), sequence);
}
[Fact]
public void should_get_sequence_given_normal_collection()
{
var sequence = new[] { 1, 2, 3 };
IEnumerable<int> result = TakeUntilError(sequence);
Assert.Equal(sequence, result);
}
}
}``` |
539596ab-5d24-4e93-b0be-e106d006acdb | {
"language": "C#"
} | ```c#
using AbpCompanyName.AbpProjectName.Authorization;
using AbpCompanyName.AbpProjectName.Authorization.Roles;
using AbpCompanyName.AbpProjectName.Authorization.Users;
using AbpCompanyName.AbpProjectName.Editions;
using AbpCompanyName.AbpProjectName.MultiTenancy;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
namespace AbpCompanyName.AbpProjectName.Identity
{
public static class IdentityRegistrar
{
public static void Register(IServiceCollection services)
{
services.AddLogging();
services.AddAbpIdentity<Tenant, User, Role>()
.AddAbpTenantManager<TenantManager>()
.AddAbpUserManager<UserManager>()
.AddAbpRoleManager<RoleManager>()
.AddAbpEditionManager<EditionManager>()
.AddAbpUserStore<UserStore>()
.AddAbpRoleStore<RoleStore>()
.AddAbpLogInManager<LogInManager>()
.AddAbpSignInManager<SignInManager>()
.AddAbpSecurityStampValidator<SecurityStampValidator>()
.AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>()
.AddDefaultTokenProviders();
}
}
}
```
Add PermissionChecker for Identity registration. | ```c#
using AbpCompanyName.AbpProjectName.Authorization;
using AbpCompanyName.AbpProjectName.Authorization.Roles;
using AbpCompanyName.AbpProjectName.Authorization.Users;
using AbpCompanyName.AbpProjectName.Editions;
using AbpCompanyName.AbpProjectName.MultiTenancy;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
namespace AbpCompanyName.AbpProjectName.Identity
{
public static class IdentityRegistrar
{
public static void Register(IServiceCollection services)
{
services.AddLogging();
services.AddAbpIdentity<Tenant, User, Role>()
.AddAbpTenantManager<TenantManager>()
.AddAbpUserManager<UserManager>()
.AddAbpRoleManager<RoleManager>()
.AddAbpEditionManager<EditionManager>()
.AddAbpUserStore<UserStore>()
.AddAbpRoleStore<RoleStore>()
.AddAbpLogInManager<LogInManager>()
.AddAbpSignInManager<SignInManager>()
.AddAbpSecurityStampValidator<SecurityStampValidator>()
.AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>()
.AddPermissionChecker<PermissionChecker>()
.AddDefaultTokenProviders();
}
}
}
``` |
aad4a0ff-3b4d-415c-9a77-cb1561747eab | {
"language": "C#"
} | ```c#
using System;
namespace kgrep {
public class WriteStdout : IHandleOutput {
public void Write(string line) {
if (line.EndsWith("\n"))
Console.Write(line);
else
Console.Write(line);
}
public string Close() {
return "";
}
}
}
```
Use newline when writing to stdout. | ```c#
using System;
namespace kgrep {
public class WriteStdout : IHandleOutput {
public void Write(string line) {
Console.WriteLine(line);
}
public string Close() {
return "";
}
}
}
``` |
5a8b9766-3a60-4c60-ab00-3d3d9e36ce0f | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using RestRPC.Framework.Messages.Inputs;
namespace RestRPC.Framework.Messages.Outputs
{
/// <summary>
/// This message is sent to server as a response to a request
/// </summary>
class WebReturn : WebOutput
{
const char HEADER_RETURN = 'r';
[JsonConstructor]
public WebReturn(object Data, WebInput input)
: base(HEADER_RETURN, new object[] { Data }, input.UID, input.CID)
{ }
}
}
```
Return a single value in procedure return message | ```c#
using Newtonsoft.Json;
using RestRPC.Framework.Messages.Inputs;
namespace RestRPC.Framework.Messages.Outputs
{
/// <summary>
/// This message is sent to server as a response to a request
/// </summary>
class WebReturn : WebOutput
{
const char HEADER_RETURN = 'r';
[JsonConstructor]
public WebReturn(object Data, WebInput input)
: base(HEADER_RETURN, Data, input.UID, input.CID)
{ }
}
}
``` |
ff90daec-6943-409a-8a9e-34f8a4aff210 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
namespace Alexa.NET.Response
{
public class Reprompt
{
public Reprompt()
{
}
public Reprompt(string text)
{
OutputSpeech = new PlainTextOutputSpeech {Text = text};
}
public Reprompt(Ssml.Speech speech)
{
OutputSpeech = new SsmlOutputSpeech {Ssml = speech.ToXml()};
}
[JsonProperty("outputSpeech", NullValueHandling=NullValueHandling.Ignore)]
public IOutputSpeech OutputSpeech { get; set; }
}
}```
Add directives to reprompt object | ```c#
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Alexa.NET.Response
{
public class Reprompt
{
public Reprompt()
{
}
public Reprompt(string text)
{
OutputSpeech = new PlainTextOutputSpeech {Text = text};
}
public Reprompt(Ssml.Speech speech)
{
OutputSpeech = new SsmlOutputSpeech {Ssml = speech.ToXml()};
}
[JsonProperty("outputSpeech", NullValueHandling=NullValueHandling.Ignore)]
public IOutputSpeech OutputSpeech { get; set; }
[JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)]
public IList<IDirective> Directives { get; set; } = new List<IDirective>();
public bool ShouldSerializeDirectives()
{
return Directives.Count > 0;
}
}
}``` |
08b9dc3b-ecb4-4ccb-a301-75923a48a5b5 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Dynamic;
namespace CouchTrafficClient
{
class QueryException : Exception
{
}
class QueryBase
{
public string Run()
{
return "Query Client Not Implemented";
}
public string Server { get { return "http://52.10.252.48:5984/traffic/"; } }
protected ExpandoObject Query(string designDocumentName, string viewName)
{
try
{
var url = Server + "_design/" + designDocumentName + "/_view/" + viewName;
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
string str = wc.DownloadString(url);
return JsonConvert.DeserializeObject<ExpandoObject>(str);
}
}
catch (Exception e)
{
MessageBox.Show("Error in WebClient: " + e.ToString());
throw new QueryException();
}
}
}
}
```
Add support for optional list of keys to limit view queries | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Dynamic;
namespace CouchTrafficClient
{
class QueryException : Exception
{
}
class QueryBase
{
public string Run()
{
return "Query Client Not Implemented";
}
public string Server { get { return "http://52.10.252.48:5984/traffic/"; } }
protected ExpandoObject Query(string designDocumentName, string viewName, IList<object> keys = null)
{
try
{
var keyString = "";
if (keys != null)
{
keyString = string.Format("?keys={0}", Uri.EscapeDataString(JsonConvert.SerializeObject(keys)));
}
var url = Server + "_design/" + designDocumentName + "/_view/" + viewName + keyString;
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
string str = wc.DownloadString(url);
return JsonConvert.DeserializeObject<ExpandoObject>(str);
}
}
catch (Exception e)
{
MessageBox.Show("Error in WebClient: " + e.ToString());
throw new QueryException();
}
}
}
}
``` |
8f989efd-61b1-4b68-8bb6-cca99ba62378 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace Glimpse
{
public class DefaultMessageConverter : IMessageConverter
{
private readonly JsonSerializer _jsonSerializer;
public DefaultMessageConverter(JsonSerializer jsonSerializer)
{
_jsonSerializer = jsonSerializer;
}
public IMessageEnvelope ConvertMessage(IMessage message)
{
var newMessage = new MessageEnvelope();
newMessage.Type = message.GetType().FullName;
newMessage.Payload = Serialize(message);
return newMessage;
}
protected string Serialize(object data)
{
// Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635
var stringBuilder = new StringBuilder(256);
using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
using (var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = _jsonSerializer.Formatting })
{
_jsonSerializer.Serialize(jsonWriter, data, data.GetType());
return stringWriter.ToString();
}
}
}
}```
Remove unneeded property carry over for jsonwritter | ```c#
using Newtonsoft.Json;
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace Glimpse
{
public class DefaultMessageConverter : IMessageConverter
{
private readonly JsonSerializer _jsonSerializer;
public DefaultMessageConverter(JsonSerializer jsonSerializer)
{
_jsonSerializer = jsonSerializer;
}
public IMessageEnvelope ConvertMessage(IMessage message)
{
var newMessage = new MessageEnvelope();
newMessage.Type = message.GetType().FullName;
newMessage.Payload = Serialize(message);
return newMessage;
}
protected string Serialize(object data)
{
// Brought across from - https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConvert.cs#L635
var stringBuilder = new StringBuilder(256);
using (var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
using (var jsonWriter = new JsonTextWriter(stringWriter))
{
_jsonSerializer.Serialize(jsonWriter, data, data.GetType());
return stringWriter.ToString();
}
}
}
}``` |
095101b0-f730-4288-9d40-57f6c141c601 | {
"language": "C#"
} | ```c#
using System.Windows.Forms;
namespace IronAHK.Scripting
{
partial class Script
{
public static void Init()
{
Application.EnableVisualStyles();
}
public static void Run()
{
Application.Run();
}
}
}
```
Enable GTK theming on Mono. | ```c#
using System;
using System.Windows.Forms;
namespace IronAHK.Scripting
{
partial class Script
{
public static void Init()
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
Environment.SetEnvironmentVariable("MONO_VISUAL_STYLES", "gtkplus");
Application.EnableVisualStyles();
}
public static void Run()
{
Application.Run();
}
}
}
``` |
6bb16a88-e561-4934-b49c-0d71ad32089e | {
"language": "C#"
} | ```c#
using System;
namespace Scheme.Storage
{
internal abstract class Atom : Object
{
public static Atom Parse(string input)
{
double number;
bool isNumber = Double.TryParse(input, out number);
if (isNumber)
return new Number(number);
bool isString = input[0] == '"' && input[input.Length - 1] == '"';
if (isString)
return new String(input.Substring(1, input.Length - 2));
bool isValidSymbol = true;
// TODO: validate.
if (isValidSymbol)
return Symbol.FromString(input);
throw new FormatException();
}
}
}```
Fix a bug with parsing. | ```c#
using System;
namespace Scheme.Storage
{
internal abstract class Atom : Object
{
public static Atom Parse(string input)
{
double number;
bool isNumber = Double.TryParse(input, out number);
if (isNumber)
return new Number(number);
bool isString = input.Length > 2 && input[0] == '"' && input[input.Length - 1] == '"';
if (isString)
return new String(input.Substring(1, input.Length - 2));
bool isValidSymbol = true;
// TODO: validate.
if (isValidSymbol)
return Symbol.FromString(input);
throw new FormatException();
}
}
}``` |
3604d127-41c8-4c8d-b03a-7743cfe280f9 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Diagnostics;
using System.Threading.Tasks;
using osu.Framework.Platform;
using osu.Game.Database;
namespace osu.Game.IPC
{
public class BeatmapImporter
{
private IpcChannel<BeatmapImportMessage> channel;
private BeatmapDatabase beatmaps;
public BeatmapImporter(GameHost host, BeatmapDatabase beatmaps = null)
{
this.beatmaps = beatmaps;
channel = new IpcChannel<BeatmapImportMessage>(host);
channel.MessageReceived += messageReceived;
}
public async Task ImportAsync(string path)
{
if (beatmaps != null)
beatmaps.Import(path);
else
{
await channel.SendMessageAsync(new BeatmapImportMessage { Path = path });
}
}
private void messageReceived(BeatmapImportMessage msg)
{
Debug.Assert(beatmaps != null);
ImportAsync(msg.Path);
}
}
public class BeatmapImportMessage
{
public string Path;
}
}
```
Add error handling to import process (resolves await warning). | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Diagnostics;
using System.Threading.Tasks;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Game.Database;
namespace osu.Game.IPC
{
public class BeatmapImporter
{
private IpcChannel<BeatmapImportMessage> channel;
private BeatmapDatabase beatmaps;
public BeatmapImporter(GameHost host, BeatmapDatabase beatmaps = null)
{
this.beatmaps = beatmaps;
channel = new IpcChannel<BeatmapImportMessage>(host);
channel.MessageReceived += messageReceived;
}
public async Task ImportAsync(string path)
{
if (beatmaps != null)
beatmaps.Import(path);
else
{
await channel.SendMessageAsync(new BeatmapImportMessage { Path = path });
}
}
private void messageReceived(BeatmapImportMessage msg)
{
Debug.Assert(beatmaps != null);
ImportAsync(msg.Path).ContinueWith(t => Logger.Error(t.Exception, @"error during async import"), TaskContinuationOptions.OnlyOnFaulted);
}
}
public class BeatmapImportMessage
{
public string Path;
}
}
``` |
f7f6b612-e02c-410f-a7ec-b74617b5abf1 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
namespace Mos6510
{
public class Register
{
public Register(int numberOfBits)
{
bits = new BitArray(numberOfBits);
}
public int Length
{
get { return bits.Length; }
}
public int GetValue()
{
return ToInt();
}
public void SetValue(int value)
{
FromInt(value);
}
private int ToInt()
{
int[] array = new int[1];
bits.CopyTo(array, 0);
return array[0];
}
private void FromInt(int value)
{
var inputBits = new BitArray(new[]{ value });
for (var i = 0; i < bits.Length; ++i)
bits[i] = inputBits[i];
}
private BitArray bits;
}
}
```
Move the private member to the top of the class | ```c#
using System;
using System.Collections;
namespace Mos6510
{
public class Register
{
private BitArray bits;
public Register(int numberOfBits)
{
bits = new BitArray(numberOfBits);
}
public int Length
{
get { return bits.Length; }
}
public int GetValue()
{
return ToInt();
}
public void SetValue(int value)
{
FromInt(value);
}
private int ToInt()
{
int[] array = new int[1];
bits.CopyTo(array, 0);
return array[0];
}
private void FromInt(int value)
{
var inputBits = new BitArray(new[]{ value });
for (var i = 0; i < bits.Length; ++i)
bits[i] = inputBits[i];
}
}
}
``` |
568155d1-0c2a-4eb4-b3b0-049e365b05e6 | {
"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.Sprites;
using osu.Game.Overlays.Dialog;
namespace osu.Game.Screens.Edit
{
public class PromptForSaveDialog : PopupDialog
{
public PromptForSaveDialog(Action exit, Action saveAndExit, Action cancel)
{
HeaderText = "Did you want to save your changes?";
Icon = FontAwesome.Regular.Save;
Buttons = new PopupDialogButton[]
{
new PopupDialogCancelButton
{
Text = @"Save my masterpiece!",
Action = saveAndExit
},
new PopupDialogOkButton
{
Text = @"Forget all changes",
Action = exit
},
new PopupDialogCancelButton
{
Text = @"Oops, continue editing",
Action = cancel
},
};
}
}
}
```
Change button types on editor exit dialog to match purpose | ```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.Sprites;
using osu.Game.Overlays.Dialog;
namespace osu.Game.Screens.Edit
{
public class PromptForSaveDialog : PopupDialog
{
public PromptForSaveDialog(Action exit, Action saveAndExit, Action cancel)
{
HeaderText = "Did you want to save your changes?";
Icon = FontAwesome.Regular.Save;
Buttons = new PopupDialogButton[]
{
new PopupDialogOkButton
{
Text = @"Save my masterpiece!",
Action = saveAndExit
},
new PopupDialogDangerousButton
{
Text = @"Forget all changes",
Action = exit
},
new PopupDialogCancelButton
{
Text = @"Oops, continue editing",
Action = cancel
},
};
}
}
}
``` |
3688d261-a782-494c-8ca6-e0bbcf7e349c | {
"language": "C#"
} | ```c#
using System.Web.Mvc;
using Orchard.Environment.Configuration;
namespace Orchard.MultiTenancy.Extensions {
public static class UrlHelperExtensions {
public static string Tenant(this UrlHelper urlHelper, ShellSettings tenantShellSettings) {
//info: (heskew) might not keep the port insertion around beyond...
var port = string.Empty;
string host = urlHelper.RequestContext.HttpContext.Request.Headers["Host"];
if(host.Contains(":"))
port = host.Substring(host.IndexOf(":"));
return string.Format(
"http://{0}/{1}",
!string.IsNullOrEmpty(tenantShellSettings.RequestUrlHost)
? tenantShellSettings.RequestUrlHost + port : host,
tenantShellSettings.RequestUrlPrefix);
}
}
}```
Add "ApplicationPath" in tenant URL | ```c#
using System.Web.Mvc;
using Orchard.Environment.Configuration;
namespace Orchard.MultiTenancy.Extensions {
public static class UrlHelperExtensions {
public static string Tenant(this UrlHelper urlHelper, ShellSettings tenantShellSettings) {
//info: (heskew) might not keep the port/vdir insertion around beyond...
var port = string.Empty;
string host = urlHelper.RequestContext.HttpContext.Request.Headers["Host"];
if (host.Contains(":"))
port = host.Substring(host.IndexOf(":"));
var result = string.Format("http://{0}",
!string.IsNullOrEmpty(tenantShellSettings.RequestUrlHost)
? tenantShellSettings.RequestUrlHost + port : host);
if (!string.IsNullOrEmpty(tenantShellSettings.RequestUrlPrefix))
result += "/" + tenantShellSettings.RequestUrlPrefix;
if (!string.IsNullOrEmpty(urlHelper.RequestContext.HttpContext.Request.ApplicationPath))
result += urlHelper.RequestContext.HttpContext.Request.ApplicationPath;
return result;
}
}
}``` |
8b494123-e165-4003-8958-4bb72ed03db6 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using System.Linq;
using Kudu.Core.Deployment;
using Kudu.SignalR.ViewModels;
using SignalR.Hubs;
namespace Kudu.SignalR.Hubs
{
public class Deployment : Hub
{
private readonly IDeploymentManager _deploymentManager;
public Deployment(IDeploymentManager deploymentManager)
{
_deploymentManager = deploymentManager;
}
public IEnumerable<DeployResultViewModel> GetDeployments()
{
string active = _deploymentManager.ActiveDeploymentId;
Caller.id = active;
return _deploymentManager.GetResults().Select(d => new DeployResultViewModel(d)
{
Active = active == d.Id
});
}
public IEnumerable<LogEntryViewModel> GetDeployLog(string id)
{
return from entry in _deploymentManager.GetLogEntries(id)
select new LogEntryViewModel(entry);
}
public void Deploy(string id)
{
_deploymentManager.Deploy(id);
}
}
}
```
Order the list of deployments by start time. | ```c#
using System.Collections.Generic;
using System.Linq;
using Kudu.Core.Deployment;
using Kudu.SignalR.ViewModels;
using SignalR.Hubs;
namespace Kudu.SignalR.Hubs
{
public class Deployment : Hub
{
private readonly IDeploymentManager _deploymentManager;
public Deployment(IDeploymentManager deploymentManager)
{
_deploymentManager = deploymentManager;
}
public IEnumerable<DeployResultViewModel> GetDeployments()
{
string active = _deploymentManager.ActiveDeploymentId;
Caller.id = active;
return _deploymentManager.GetResults()
.OrderByDescending(d => d.DeployStartTime)
.Select(d => new DeployResultViewModel(d)
{
Active = active == d.Id
});
}
public IEnumerable<LogEntryViewModel> GetDeployLog(string id)
{
return from entry in _deploymentManager.GetLogEntries(id)
select new LogEntryViewModel(entry);
}
public void Deploy(string id)
{
_deploymentManager.Deploy(id);
}
}
}
``` |
ebf9e9f5-53c0-4306-9cc8-8e960e895dd7 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Net;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.MSBuild;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace HearthDb.EnumsGenerator
{
internal class Program
{
private const string File = "../../../HearthDb/Enums/Enums.cs";
static void Main()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
string enums;
using(var wc = new WebClient())
enums = wc.DownloadString("https://api.hearthstonejson.com/v1/enums.cs");
var header = ParseLeadingTrivia(@"/* THIS FILE WAS GENERATED BY HearthDb.EnumsGenerator. DO NOT EDIT. */" + Environment.NewLine + Environment.NewLine);
var members = ParseCompilationUnit(enums).Members;
var first = members.First().WithLeadingTrivia(header);
var @namespace = NamespaceDeclaration(IdentifierName("HearthDb.Enums")).AddMembers(new [] {first}.Concat(members.Skip(1)).ToArray());
var root = Formatter.Format(@namespace, MSBuildWorkspace.Create());
using(var sr = new StreamWriter(File))
sr.Write(root.ToString());
}
}
}
```
Add random param to enums url | ```c#
using System;
using System.Linq;
using System.Net;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.MSBuild;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace HearthDb.EnumsGenerator
{
internal class Program
{
private const string File = "../../../HearthDb/Enums/Enums.cs";
static void Main()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
string enums;
using(var wc = new WebClient())
enums = wc.DownloadString("https://api.hearthstonejson.com/v1/enums.cs?" + DateTime.Now.Ticks);
var header = ParseLeadingTrivia(@"/* THIS FILE WAS GENERATED BY HearthDb.EnumsGenerator. DO NOT EDIT. */" + Environment.NewLine + Environment.NewLine);
var members = ParseCompilationUnit(enums).Members;
var first = members.First().WithLeadingTrivia(header);
var @namespace = NamespaceDeclaration(IdentifierName("HearthDb.Enums")).AddMembers(new [] {first}.Concat(members.Skip(1)).ToArray());
var root = Formatter.Format(@namespace, MSBuildWorkspace.Create());
using(var sr = new StreamWriter(File))
sr.Write(root.ToString());
}
}
}
``` |
7bffbcf5-943f-4f26-b1c0-330915ed15ed | {
"language": "C#"
} | ```c#
using System.Reflection;
[assembly: AssemblyVersion("2.10.7.0")]
[assembly: AssemblyFileVersion("2.10.7.0")]
[assembly: AssemblyInformationalVersion("2.10.7")]
```
Update version number to 2.11.0. | ```c#
using System.Reflection;
[assembly: AssemblyVersion("2.11.0.0")]
[assembly: AssemblyFileVersion("2.11.0.0")]
[assembly: AssemblyInformationalVersion("2.11.0")]
``` |
3cde177a-6f51-45a5-b5ad-34a7a4fe515a | {
"language": "C#"
} | ```c#
using System;
#if __UNIFIED__
using Foundation;
using UIKit;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
#endif
namespace Plugin.Messaging
{
internal class PhoneCallTask : IPhoneCallTask
{
public PhoneCallTask()
{
}
#region IPhoneCallTask Members
public bool CanMakePhoneCall
{
get
{
// UIApplication.SharedApplication.CanOpenUrl does not validate the URL, it merely checks whether a handler for
// the URL has been installed on the system. Therefore string.Empty can be used as phone number.
var nsurl = CreateNsUrl(string.Empty);
return UIApplication.SharedApplication.CanOpenUrl(nsurl);
}
}
public void MakePhoneCall(string number, string name = null)
{
if (string.IsNullOrWhiteSpace(number))
throw new ArgumentNullException(nameof(number));
if (CanMakePhoneCall)
{
var nsurl = CreateNsUrl(number);
UIApplication.SharedApplication.OpenUrl(nsurl);
}
}
private NSUrl CreateNsUrl(string number)
{
return new NSUrl(new Uri($"tel:{number}").AbsoluteUri);
}
#endregion
}
}```
Improve CanMakePhoneCall on iOS to check support of url and link to a carrier | ```c#
using System;
#if __UNIFIED__
using Foundation;
using UIKit;
using CoreTelephony;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreTelephony;
#endif
namespace Plugin.Messaging
{
internal class PhoneCallTask : IPhoneCallTask
{
public PhoneCallTask()
{
}
#region IPhoneCallTask Members
public bool CanMakePhoneCall
{
get
{
var nsurl = CreateNsUrl("0000000000");
bool canCall = UIApplication.SharedApplication.CanOpenUrl(nsurl);
if (canCall)
{
using (CTTelephonyNetworkInfo netInfo = new CTTelephonyNetworkInfo())
{
string mnc = netInfo.SubscriberCellularProvider?.MobileNetworkCode;
return !string.IsNullOrEmpty(mnc) && mnc != "65535"; //65535 stands for NoNetwordProvider
}
}
return false;
}
}
public void MakePhoneCall(string number, string name = null)
{
if (string.IsNullOrWhiteSpace(number))
throw new ArgumentNullException(nameof(number));
if (CanMakePhoneCall)
{
var nsurl = CreateNsUrl(number);
UIApplication.SharedApplication.OpenUrl(nsurl);
}
}
private NSUrl CreateNsUrl(string number)
{
return new NSUrl(new Uri($"tel:{number}").AbsoluteUri);
}
#endregion
}
}``` |
ab9e010c-6a9f-4d73-b04d-fda63a543fc0 | {
"language": "C#"
} | ```c#
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;
using Kudu.Client.Deployment;
using Kudu.Client.Infrastructure;
using Kudu.Client.SourceControl;
using Kudu.Core.SourceControl;
using Kudu.Web.Models;
namespace Kudu.Web.Infrastructure
{
public static class ApplicationExtensions
{
public static Task<RepositoryInfo> GetRepositoryInfo(this IApplication application, ICredentials credentials)
{
var repositoryManager = new RemoteRepositoryManager(application.ServiceUrl + "live/scm", credentials);
return repositoryManager.GetRepositoryInfo();
}
public static RemoteDeploymentManager GetDeploymentManager(this IApplication application, ICredentials credentials)
{
var deploymentManager = new RemoteDeploymentManager(application.ServiceUrl + "/deployments", credentials);
return deploymentManager;
}
public static RemoteDeploymentSettingsManager GetSettingsManager(this IApplication application, ICredentials credentials)
{
var deploymentSettingsManager = new RemoteDeploymentSettingsManager(application.ServiceUrl + "/settings", credentials);
return deploymentSettingsManager;
}
public static Task<XDocument> DownloadTrace(this IApplication application, ICredentials credentials)
{
var clientHandler = HttpClientHelper.CreateClientHandler(application.ServiceUrl, credentials);
var client = new HttpClient(clientHandler);
return client.GetAsync(application.ServiceUrl + "dump").Then(response =>
{
return response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync().Then(stream =>
{
return ZipHelper.ExtractTrace(stream);
});
});
}
}
}```
Fix a few service paths in portal | ```c#
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;
using Kudu.Client.Deployment;
using Kudu.Client.Infrastructure;
using Kudu.Client.SourceControl;
using Kudu.Core.SourceControl;
using Kudu.Web.Models;
namespace Kudu.Web.Infrastructure
{
public static class ApplicationExtensions
{
public static Task<RepositoryInfo> GetRepositoryInfo(this IApplication application, ICredentials credentials)
{
var repositoryManager = new RemoteRepositoryManager(application.ServiceUrl + "scm", credentials);
return repositoryManager.GetRepositoryInfo();
}
public static RemoteDeploymentManager GetDeploymentManager(this IApplication application, ICredentials credentials)
{
var deploymentManager = new RemoteDeploymentManager(application.ServiceUrl + "deployments", credentials);
return deploymentManager;
}
public static RemoteDeploymentSettingsManager GetSettingsManager(this IApplication application, ICredentials credentials)
{
var deploymentSettingsManager = new RemoteDeploymentSettingsManager(application.ServiceUrl + "settings", credentials);
return deploymentSettingsManager;
}
public static Task<XDocument> DownloadTrace(this IApplication application, ICredentials credentials)
{
var clientHandler = HttpClientHelper.CreateClientHandler(application.ServiceUrl, credentials);
var client = new HttpClient(clientHandler);
return client.GetAsync(application.ServiceUrl + "dump").Then(response =>
{
return response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync().Then(stream =>
{
return ZipHelper.ExtractTrace(stream);
});
});
}
}
}``` |
5e6430a1-73e6-44c7-8c64-c390b4bca93b | {
"language": "C#"
} | ```c#
using System;
using System.Drawing;
using System.Windows.Forms;
using Linking.Controls;
using Linking.Core;
using Linking.Core.Blocks;
namespace Linking
{
public partial class Form1 : Form
{
public Form1()
{
//이것도 커밋해 보시지!!
InitializeComponent();
Board board = new Board();
BoardControl boardCtrl = new BoardControl(board);
boardCtrl.Dock = DockStyle.Fill;
this.Controls.Add(boardCtrl);
EntryBlock entry = new EntryBlock(board);
BlockControl b = new BlockControl(entry);
b.Location = new Point(50, 50);
boardCtrl.AddBlock(entry);
}
}
}
```
Remove useless code in blockcontrol test | ```c#
using System;
using System.Drawing;
using System.Windows.Forms;
using Linking.Controls;
using Linking.Core;
using Linking.Core.Blocks;
namespace Linking
{
public partial class Form1 : Form
{
public Form1()
{
//이것도 커밋해 보시지!!
InitializeComponent();
Board board = new Board();
BoardControl boardCtrl = new BoardControl(board);
boardCtrl.Dock = DockStyle.Fill;
this.Controls.Add(boardCtrl);
EntryBlock entry = new EntryBlock(board);
boardCtrl.AddBlock(entry);
}
}
}
``` |
4d2b5134-6420-46d0-9b5a-eb1b8e0593ec | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
public static class TypeExtensions
{
public static IEnumerable<PropertyInfo> GetSortedProperties(this Type t)
{
return from pi in t.GetProperties()
let da = (DisplayAttribute)pi.GetCustomAttributes(typeof(DisplayAttribute), false).SingleOrDefault()
let order = ((da != null && da.Order != 0) ? da.Order : int.MaxValue)
orderby order
select pi;
}
public static IEnumerable<PropertyInfo> GetSortedProperties<T>()
{
return typeof(T).GetSortedProperties();
}
public static IEnumerable<PropertyInfo> GetProperties(this Type t)
{
return from pi in t.GetProperties()
select pi;
}
public static IEnumerable<PropertyInfo> GetProperties<T>()
{
return typeof(T).GetSortedProperties();
}
}```
Add namespace and fix DisplayAttribute.Order evaluation to avoid exception when Order is not set. | ```c#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
namespace Mvc.JQuery.Datatables
{
public static class TypeExtensions
{
public static IEnumerable<PropertyInfo> GetSortedProperties(this Type t)
{
return from pi in t.GetProperties()
let da = (DisplayAttribute)pi.GetCustomAttributes(typeof(DisplayAttribute), false).SingleOrDefault()
let order = ((da != null && da.GetOrder() != null && da.GetOrder() >= 0) ? da.Order : int.MaxValue)
orderby order
select pi;
}
public static IEnumerable<PropertyInfo> GetSortedProperties<T>()
{
return typeof(T).GetSortedProperties();
}
public static IEnumerable<PropertyInfo> GetProperties(this Type t)
{
return from pi in t.GetProperties()
select pi;
}
public static IEnumerable<PropertyInfo> GetProperties<T>()
{
return typeof(T).GetSortedProperties();
}
}
}``` |
a725a3d9-cd87-4373-b84a-cd5b0e964a7f | {
"language": "C#"
} | ```c#
using LibPixelPet;
using System;
namespace PixelPet.CLI.Commands {
internal class PadPalettesCmd : CliCommand {
public PadPalettesCmd()
: base("Pad-Palettes",
new Parameter(true, new ParameterValue("width", "0"))
) { }
public override void Run(Workbench workbench, ILogger logger) {
int width = FindUnnamedParameter(0).Values[0].ToInt32();
if (width < 1) {
logger?.Log("Invalid palette width.", LogLevel.Error);
return;
}
if (workbench.PaletteSet.Count == 0) {
logger?.Log("No palettes to pad. Creating 1 palette based on current bitmap format.", LogLevel.Information);
Palette pal = new Palette(workbench.BitmapFormat, -1);
workbench.PaletteSet.Add(pal);
}
int addedColors = 0;
foreach (PaletteEntry pe in workbench.PaletteSet) {
while (pe.Palette.Count < width) {
pe.Palette.Add(0);
addedColors++;
}
}
logger?.Log("Padded palettes to width " + width + " (added " + addedColors + " colors).", LogLevel.Information);
}
}
}
```
Add parameter specifying color to pad with. | ```c#
using LibPixelPet;
using System;
namespace PixelPet.CLI.Commands {
internal class PadPalettesCmd : CliCommand {
public PadPalettesCmd()
: base("Pad-Palettes",
new Parameter(true, new ParameterValue("width", "0")),
new Parameter("color", "c", false, new ParameterValue("value", "0"))
) { }
public override void Run(Workbench workbench, ILogger logger) {
int width = FindUnnamedParameter(0).Values[0].ToInt32();
int color = FindNamedParameter("--color").Values[0].ToInt32();
if (width < 1) {
logger?.Log("Invalid palette width.", LogLevel.Error);
return;
}
if (workbench.PaletteSet.Count == 0) {
logger?.Log("No palettes to pad. Creating 1 palette based on current bitmap format.", LogLevel.Information);
Palette pal = new Palette(workbench.BitmapFormat, -1);
workbench.PaletteSet.Add(pal);
}
int addedColors = 0;
foreach (PaletteEntry pe in workbench.PaletteSet) {
while (pe.Palette.Count < width) {
pe.Palette.Add(color);
addedColors++;
}
}
logger?.Log("Padded palettes to width " + width + " (added " + addedColors + " colors).", LogLevel.Information);
}
}
}
``` |
8eeeb475-1e59-48d6-abfb-f70b9738374a | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
[assembly: CLSCompliant(true)]
namespace IronAHK.Setup
{
static partial class Program
{
static void Main(string[] args)
{
TransformDocs();
PackageZip();
AppBundle();
BuildMsi();
}
[Conditional("DEBUG")]
static void Cleanup()
{
Console.Read();
}
}
}
```
Build MSI only on Windows. | ```c#
using System;
using System.Diagnostics;
[assembly: CLSCompliant(true)]
namespace IronAHK.Setup
{
static partial class Program
{
static void Main(string[] args)
{
TransformDocs();
PackageZip();
AppBundle();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
BuildMsi();
Cleanup();
}
[Conditional("DEBUG")]
static void Cleanup()
{
Console.Read();
}
}
}
``` |
585f60d0-84d0-4dc6-868e-b85d1f602757 | {
"language": "C#"
} | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
```
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning. | ```c#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
``` |
7b1828cd-011a-4c79-ad6b-c98d7d93e50f | {
"language": "C#"
} | ```c#
using System;
using System.Windows.Controls;
using static System.Reactive.Linq.Observable;
namespace cardio.Ext
{
/// <summary>
/// Represents Button Extension
/// </summary>
static class ButtonExt
{
/// <summary>
/// Disables the button
/// </summary>
/// <param name="button">Given button to be disbaled</param>
/// <returns>button</returns>
internal static Button Disable (this Button button)
{
if ( !button.IsEnabled ) return button;
button.IsEnabled = false;
return button;
}
/// <summary>
/// Enables the button
/// </summary>
/// <param name="button">Given button to enabled</param>
/// <returns>button</returns>
internal static Button Enable (this Button button)
{
if ( button.IsEnabled ) return button;
button.IsEnabled = true;
return button;
}
/// <summary>
/// Converts Button Click to Stream of Button
/// </summary>
/// <param name="button">The given button</param>
/// <returns>The sender button</returns>
internal static IObservable<Button> StreamButtonClick(this Button button)
{
return from evt in FromEventPattern(button, "Click") select evt.Sender as Button;
}
}
}
```
Add Code Contracts in ButonExt | ```c#
using System;
using System.Windows.Controls;
using static System.Reactive.Linq.Observable;
using static System.Diagnostics.Contracts.Contract;
namespace cardio.Ext
{
/// <summary>
/// Represents Button Extension
/// </summary>
static class ButtonExt
{
/// <summary>
/// Disables the button
/// </summary>
/// <param name="button">Given button to be disbaled</param>
/// <returns>button</returns>
internal static Button Disable (this Button button)
{
Requires(button != null);
if ( !button.IsEnabled ) return button;
button.IsEnabled = false;
return button;
}
/// <summary>
/// Enables the button
/// </summary>
/// <param name="button">Given button to enabled</param>
/// <returns>button</returns>
internal static Button Enable (this Button button)
{
Requires(button != null);
if ( button.IsEnabled ) return button;
button.IsEnabled = true;
return button;
}
/// <summary>
/// Converts Button Click to Stream of Button
/// </summary>
/// <param name="button">The given button</param>
/// <returns>The sender button</returns>
internal static IObservable<Button> StreamButtonClick(this Button button)
{
Requires(button != null);
return from evt in FromEventPattern(button, "Click") select evt.Sender as Button;
}
}
}
``` |
c4dd464a-bfae-4ba3-a554-4042819cbe8a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using ManyConsole;
namespace TeamCityBuildChanges
{
class Program
{
static int Main(string[] args)
{
var commands = GetCommands();
return ConsoleCommandDispatcher.DispatchCommand(commands, args, Console.Out);
}
static IEnumerable<ConsoleCommand> GetCommands()
{
return ConsoleCommandDispatcher.FindCommandsInSameAssemblyAs(typeof(Program));
}
}
}
```
Fix for base command being shown as command on command line. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using ManyConsole;
namespace TeamCityBuildChanges
{
class Program
{
static int Main(string[] args)
{
var commands = GetCommands();
return ConsoleCommandDispatcher.DispatchCommand(commands, args, Console.Out);
}
static IEnumerable<ConsoleCommand> GetCommands()
{
return ConsoleCommandDispatcher.FindCommandsInSameAssemblyAs(typeof(Program)).Where(c => !string.IsNullOrEmpty(c.Command));
}
}
}
``` |
3037455d-84c7-43f5-899d-ff045c31345c | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class HelloWorldProgram : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
// Run the program while the window is open.
while (Display.CurrentWindow.IsClosed == false &&
Keyboard.Keys[KeyCode.Escape] == false)
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
}
}```
Correct full screen test class name. | ```c#
using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;
namespace Tests.DisplayTests
{
class FullscreenTest : IAgateTest
{
public string Name
{
get { return "Full Screen"; }
}
public string Category
{
get { return "Display"; }
}
public void Main(string[] args)
{
using (AgateSetup setup = new AgateSetup(args))
{
setup.InitializeAll();
if (setup.WasCanceled)
return;
DisplayWindow wind = DisplayWindow.CreateFullScreen("Hello World", 640, 480);
Surface mySurface = new Surface("jellybean.png");
// Run the program while the window is open.
while (Display.CurrentWindow.IsClosed == false &&
Keyboard.Keys[KeyCode.Escape] == false)
{
Display.BeginFrame();
Display.Clear(Color.DarkGreen);
mySurface.Draw(Mouse.X, Mouse.Y);
Display.EndFrame();
Core.KeepAlive();
}
}
}
}
}``` |
41f92f7b-1967-4304-9506-904b3f00d50a | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace PluginLoader
{
public static class Plugins<T> where T : class
{
/// <summary>
/// Loads interface plugins from the specified location.
/// </summary>
/// <param name="path">Load path</param>
/// <returns></returns>
public static ICollection<T> Load(string path)
{
var plugins = new List<T>();
if (Directory.Exists(path))
{
Type pluginType = typeof(T);
// All interface plugins have "if_" prefix
var assemblies = Directory.GetFiles(path, "if_*.dll");
foreach (var assemblyPath in assemblies)
{
var assembly = Assembly.LoadFrom(assemblyPath);
foreach (var type in assembly.GetTypes())
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.GetInterface(pluginType.FullName) != null)
{
T plugin = Activator.CreateInstance(type) as T;
plugins.Add(plugin);
}
}
}
}
return plugins;
}
}
}
```
Add possibility to customize plugin search pattern | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace PluginLoader
{
public static class Plugins<T> where T : class
{
/// <summary>
/// Loads interface plugins from the specified location.
/// </summary>
/// <param name="path">Load path</param>
/// <param name="searchPattern">Plugin file search pattern, default "if_*.dll"</param>
/// <returns></returns>
public static ICollection<T> Load(string path, string searchPattern = "if_*.dll")
{
var plugins = new List<T>();
if (Directory.Exists(path))
{
Type pluginType = typeof(T);
var assemblies = Directory.GetFiles(path, searchPattern);
foreach (var assemblyPath in assemblies)
{
var assembly = Assembly.LoadFrom(assemblyPath);
foreach (var type in assembly.GetTypes())
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.GetInterface(pluginType.FullName) != null)
{
T plugin = Activator.CreateInstance(type) as T;
plugins.Add(plugin);
}
}
}
}
return plugins;
}
}
}
``` |
27ab69e0-414b-4c83-aff0-77a746dba67a | {
"language": "C#"
} | ```c#
using System.IO;
using ClrSpy.CliSupport;
using ClrSpy.Debugger;
using Microsoft.Diagnostics.Runtime.Interop;
namespace ClrSpy.Jobs
{
public class DumpMemoryJob : IDebugJob
{
private readonly DebugRunningProcess target;
public int Pid => target.Process.Pid;
public string DumpFilePath { get; }
public bool OverwriteDumpFileIfExists { get; set; }
public DumpMemoryJob(DebugRunningProcess target, string dumpFilePath)
{
DumpFilePath = dumpFilePath;
this.target = target;
}
public void Run(TextWriter output, ConsoleLog console)
{
using (var session = target.CreateSession())
{
if (File.Exists(DumpFilePath))
{
if (!OverwriteDumpFileIfExists) throw new IOException($"File already exists: {DumpFilePath}");
File.Delete(DumpFilePath);
}
var clientInterface = session.DataTarget.DebuggerInterface as IDebugClient2;
if (clientInterface == null)
{
console.WriteLine("WARNING: API only supports old-style dump? Recording minidump instead.");
session.DataTarget.DebuggerInterface.WriteDumpFile(DumpFilePath, DEBUG_DUMP.SMALL);
return;
}
clientInterface.WriteDumpFile2(DumpFilePath, DEBUG_DUMP.SMALL, DEBUG_FORMAT.USER_SMALL_FULL_MEMORY, "");
}
}
}
}
```
Include symbols, etc in the memory dump | ```c#
using System.IO;
using ClrSpy.CliSupport;
using ClrSpy.Debugger;
using Microsoft.Diagnostics.Runtime.Interop;
namespace ClrSpy.Jobs
{
public class DumpMemoryJob : IDebugJob
{
private readonly DebugRunningProcess target;
public int Pid => target.Process.Pid;
public string DumpFilePath { get; }
public bool OverwriteDumpFileIfExists { get; set; }
public DumpMemoryJob(DebugRunningProcess target, string dumpFilePath)
{
DumpFilePath = dumpFilePath;
this.target = target;
}
public void Run(TextWriter output, ConsoleLog console)
{
using (var session = target.CreateSession())
{
if (File.Exists(DumpFilePath))
{
if (!OverwriteDumpFileIfExists) throw new IOException($"File already exists: {DumpFilePath}");
File.Delete(DumpFilePath);
}
var clientInterface = session.DataTarget.DebuggerInterface as IDebugClient2;
if (clientInterface == null)
{
console.WriteLine("WARNING: API only supports old-style dump? Recording minidump instead.");
session.DataTarget.DebuggerInterface.WriteDumpFile(DumpFilePath, DEBUG_DUMP.SMALL);
return;
}
clientInterface.WriteDumpFile2(DumpFilePath, DEBUG_DUMP.SMALL, DEBUG_FORMAT.USER_SMALL_FULL_MEMORY | DEBUG_FORMAT.CAB_SECONDARY_ALL_IMAGES, "");
}
}
}
}
``` |
5d157ded-dd5a-405c-8ac3-2ca8f6d172b6 | {
"language": "C#"
} | ```c#
@model IEnumerable<Soldier>
<h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
<td>@Html.DisplayFor(s => soldier.Rank)</td>
<td>@Html.DisplayFor(s => soldier.LastName)</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>
@Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
@Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
</td>
</tr>
}
</tbody>
</table>```
Change list display for soldiers | ```c#
@model IEnumerable<Soldier>
<h2>Soldiers @Html.ActionLink("Add New", "New", "Soldiers", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Unit)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.ActionLink("Details", "Details", new { soldier.Id })</td>
<td>@Html.DisplayFor(s => soldier)</td>
<td>@Html.DisplayFor(s => soldier.Unit)</td>
<td>
@Html.ActionLink("Add ABCP", "New", "ABCP", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
@Html.ActionLink("Add APFT", "New", "APFT", new { soldier = soldier.Id }, new { @class = "btn btn-default" })
</td>
</tr>
}
</tbody>
</table>``` |
83840063-d453-49a8-b1f6-c89b6d1b0a43 | {
"language": "C#"
} | ```c#
using System;
using MessageBird.Utilities;
using Newtonsoft.Json;
using System.Globalization;
namespace MessageBird.Json.Converters
{
public class RFC3339DateTimeConverter : JsonConverter
{
private const string format = "Y-m-d\\TH:i:sP";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTime)
{
DateTime dateTime = (DateTime)value;
writer.WriteValue(dateTime.ToString(format));
}
else
{
throw new JsonSerializationException("Expected value of type 'DateTime'.");
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type t = (ReflectionUtils.IsNullable(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (reader.TokenType == JsonToken.Date)
{
return reader.Value;
}
else
{
throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType));
}
}
public override bool CanConvert(Type objectType)
{
Type t = (ReflectionUtils.IsNullable(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
return t == typeof(DateTime);
}
}
}
```
Use expected, but incorrect, truncated RFC3339 format | ```c#
using System;
using MessageBird.Utilities;
using Newtonsoft.Json;
using System.Globalization;
namespace MessageBird.Json.Converters
{
public class RFC3339DateTimeConverter : JsonConverter
{
// XXX: Format should be "yyyy-MM-dd'T'THH:mm:ssK".
// However, due to bug the endpoint expects the current used format.
// Need to be changed when the endpoint is updated!
private const string format = "yyyy-MM-dd'T'HH:mm";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTime)
{
DateTime dateTime = (DateTime)value;
writer.WriteValue(dateTime.ToString(format));
}
else
{
throw new JsonSerializationException("Expected value of type 'DateTime'.");
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type t = (ReflectionUtils.IsNullable(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (reader.TokenType == JsonToken.Date)
{
return reader.Value;
}
else
{
throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType));
}
}
public override bool CanConvert(Type objectType)
{
Type t = (ReflectionUtils.IsNullable(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
return t == typeof(DateTime);
}
}
}
``` |
bc099706-5152-4cd0-ba98-8bb750b41e50 | {
"language": "C#"
} | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUD_Manager : MonoBehaviour
{
// The names of the GUI objects we're editing
public string amountXPElementName;
public string playerHealthElementName;
public string equippedWeaponIconElementName;
// Equipped weapon icons to use
public Sprite equippedMeleeSprite;
public Sprite equippedRangedSprite;
public Sprite equippedMagicSprite;
// The GUI objects we're editing
GUIText amountXPText;
Slider playerHealthSlider;
Image equippedWeaponIcon;
// Use this for initialization
void Start ()
{
// Find and store the things we'll be modifying
amountXPText = GameObject.Find(amountXPElementName).GetComponent<GUIText>();
playerHealthSlider = GameObject.Find(playerHealthElementName).GetComponent<Slider>();
equippedWeaponIcon = GameObject.Find(equippedWeaponIconElementName).GetComponent<Image>();
}
// Update is called once per frame
void Update ()
{
// Update player XP, health and equipped weapon icon
amountXPText.text = Game.thePlayer.XP.ToString();
playerHealthSlider.value = Game.thePlayer.health / Game.thePlayer.maxHealth;
// TODO: equipped weapon
}
}
```
Fix XP text not displaying | ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUD_Manager : MonoBehaviour
{
// The names of the GUI objects we're editing
public string amountXPElementName;
public string playerHealthElementName;
public string equippedWeaponIconElementName;
// Equipped weapon icons to use
public Sprite equippedMeleeSprite;
public Sprite equippedRangedSprite;
public Sprite equippedMagicSprite;
// The GUI objects we're editing
Text amountXPText;
Slider playerHealthSlider;
Image equippedWeaponIcon;
// Use this for initialization
void Start ()
{
// Find and store the things we'll be modifying
amountXPText = GameObject.Find(amountXPElementName).GetComponent<Text>();
playerHealthSlider = GameObject.Find(playerHealthElementName).GetComponent<Slider>();
equippedWeaponIcon = GameObject.Find(equippedWeaponIconElementName).GetComponent<Image>();
}
// Update is called once per frame
void Update ()
{
// Update player XP, health and equipped weapon icon
amountXPText.text = Game.thePlayer.XP.ToString();
playerHealthSlider.value = Game.thePlayer.health / Game.thePlayer.maxHealth;
// TODO: equipped weapon
}
}
``` |
0ba8c76c-b0ec-487a-b246-de5ee8c2a844 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
namespace ConsoleProgressBar
{
/// <summary>
/// Simple program with sample usage of ConsoleProgressBar.
/// </summary>
class Program
{
public static void Main(string[] args)
{
using (var progressBar = new ConsoleProgressBar(totalUnitsOfWork: 3500))
{
for (uint i = 0; i < 3500; ++i)
{
progressBar.Draw(i + 1);
Thread.Sleep(1);
}
}
using (var progressBar = new ConsoleProgressBar(
totalUnitsOfWork: 2000,
startingPosition: 10,
widthInCharacters: 65,
completedColor: ConsoleColor.DarkBlue,
remainingColor: ConsoleColor.DarkGray))
{
for (uint i = 0; i < 2000; ++i)
{
progressBar.Draw(i + 1);
Thread.Sleep(1);
}
}
}
}
}
```
Adjust sample to fit on default Windows cmd console. | ```c#
using System;
using System.Threading;
namespace ConsoleProgressBar
{
/// <summary>
/// Simple program with sample usage of ConsoleProgressBar.
/// </summary>
class Program
{
public static void Main(string[] args)
{
using (var progressBar = new ConsoleProgressBar(totalUnitsOfWork: 3500))
{
for (uint i = 0; i < 3500; ++i)
{
progressBar.Draw(i + 1);
Thread.Sleep(1);
}
}
using (var progressBar = new ConsoleProgressBar(
totalUnitsOfWork: 2000,
startingPosition: 3,
widthInCharacters: 48,
completedColor: ConsoleColor.DarkBlue,
remainingColor: ConsoleColor.DarkGray))
{
for (uint i = 0; i < 2000; ++i)
{
progressBar.Draw(i + 1);
Thread.Sleep(1);
}
}
}
}
}
``` |
24f7871a-9d21-4ae7-b5b2-fcaa6decfc3e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
namespace KryptPadWebApp.Email
{
public class EmailHelper
{
/// <summary>
/// Sends an email
/// </summary>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="to"></param>
/// <returns></returns>
public static Task SendAsync(string subject, string body, string to)
{
// Credentials
var credentialUserName = ConfigurationManager.AppSettings["SmtpUserName"];
var sentFrom = ConfigurationManager.AppSettings["SmtpSendFrom"];
var pwd = ConfigurationManager.AppSettings["SmtpPassword"];
var server = ConfigurationManager.AppSettings["SmtpHostName"];
var port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]);
// Configure the client
var client = new SmtpClient(server);
client.Port = port;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
// Create the credentials
var credentials = new NetworkCredential(credentialUserName, pwd);
client.EnableSsl = false;
client.Credentials = credentials;
// Create the message
var mail = new MailMessage(sentFrom, to);
mail.IsBodyHtml = true;
mail.Subject = subject;
mail.Body = body;
// Send
return client.SendMailAsync(mail);
}
}
}
```
Update to send mail function | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web;
namespace KryptPadWebApp.Email
{
public class EmailHelper
{
/// <summary>
/// Sends an email
/// </summary>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="to"></param>
/// <returns></returns>
public static Task SendAsync(string subject, string body, string to)
{
// Credentials
var credentialUserName = ConfigurationManager.AppSettings["SmtpUserName"];
var sentFrom = ConfigurationManager.AppSettings["SmtpSendFrom"];
var pwd = ConfigurationManager.AppSettings["SmtpPassword"];
var server = ConfigurationManager.AppSettings["SmtpHostName"];
var port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]);
// Configure the client
var client = new SmtpClient(server);
client.Port = port;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = false;
// Create the credentials
client.Credentials = new NetworkCredential(credentialUserName, pwd);
// Create the message
var mail = new MailMessage(sentFrom, to);
mail.IsBodyHtml = true;
mail.Subject = subject;
mail.Body = body;
// Send
return client.SendMailAsync(mail);
}
}
}
``` |
f5b18667-54ad-49cc-b926-038cb45a6c5e | {
"language": "C#"
} | ```c#
using System;
using System.Windows;
namespace CefSharp.MinimalExample.Wpf
{
public partial class App : Application
{
public App()
{
//Perform dependency check to make sure all relevant resources are in our output directory.
var settings = new CefSettings();
settings.EnableInternalPdfViewerOffScreen();
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
}
}
}
```
Remove call to EnableInternalPdfViewerOffScreen as it's been removed as Chromium no longer supports disabling of surfaces | ```c#
using System;
using System.Windows;
namespace CefSharp.MinimalExample.Wpf
{
public partial class App : Application
{
public App()
{
//Perform dependency check to make sure all relevant resources are in our output directory.
var settings = new CefSettings();
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
}
}
}
``` |
27cabab0-b75e-479e-9d68-b67fda1916a0 | {
"language": "C#"
} | ```c#
using SPAD.neXt.Interfaces.Profile;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace SPAD.neXt.Interfaces.Configuration
{
public interface ISettingsProvider : IProfileOptionsProvider, IWindowPlacementProvider
{ }
public interface IProfileOptionsProvider
{
IProfileOption AddOption(string key, Interfaces.Profile.ProfileOptionTypes type, string defaultValue, bool needrestart = false, bool editable = false, bool hidden = false);
IProfileOption GetOption(string key);
void SetOption(string key, string value);
}
public interface IWindowPlacementProvider
{
IWindowPlacement GetWindowPlacement(string key);
void SetWindowPlacement(IWindowPlacement placement);
}
public interface IWindowPlacement
{
string Key { get; }
double Top { get; set; }
double Left { get; set; }
double Height { get; set; }
double Width { get; set; }
bool HasValues { get; }
void ApplyPlacement(Window w);
bool SavePlacement(Window w);
T GetOption<T>(string key, T defaultValue = default(T));
void SetOption(string key, object value);
}
}
```
Add option for groupname to group options by groups | ```c#
using SPAD.neXt.Interfaces.Profile;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace SPAD.neXt.Interfaces.Configuration
{
public interface ISettingsProvider : IProfileOptionsProvider, IWindowPlacementProvider
{ }
public interface IProfileOptionsProvider
{
IProfileOption AddOption(string key, Interfaces.Profile.ProfileOptionTypes type, string defaultValue, bool needrestart = false, bool editable = false, bool hidden = false,string groupName="Other");
IProfileOption GetOption(string key);
void SetOption(string key, string value);
}
public interface IWindowPlacementProvider
{
IWindowPlacement GetWindowPlacement(string key);
void SetWindowPlacement(IWindowPlacement placement);
}
public interface IWindowPlacement
{
string Key { get; }
double Top { get; set; }
double Left { get; set; }
double Height { get; set; }
double Width { get; set; }
bool HasValues { get; }
void ApplyPlacement(Window w);
bool SavePlacement(Window w);
T GetOption<T>(string key, T defaultValue = default(T));
void SetOption(string key, object value);
}
}
``` |
9374b05c-0c07-432b-8929-b792e6b18174 | {
"language": "C#"
} | ```c#
using System;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors.SqlServer;
namespace BroadbandStats.Database.Migrations
{
public sealed class Migrator
{
private readonly string connectionString;
public Migrator(string connectionString)
{
if (connectionString == null)
{
throw new ArgumentNullException(nameof(connectionString));
}
this.connectionString = connectionString;
}
public void MigrateToLatestSchema()
{
var todaysDate = DateTime.Today.ToString("yyyyMMdd");
var todaysSchemaVersion = long.Parse(todaysDate);
MigrateTo(todaysSchemaVersion);
}
private void MigrateTo(long targetVersion)
{
var options = new MigrationOptions { PreviewOnly = false, Timeout = 60 };
var announcer = new NullAnnouncer();
var processor = new SqlServer2012ProcessorFactory().Create(connectionString, announcer, options);
var migrationContext = new RunnerContext(announcer) { Namespace = "BroadbandSpeedTests.Database.Migrations.Migrations" };
var runner = new MigrationRunner(GetType().Assembly, migrationContext, processor);
runner.MigrateUp(targetVersion, true);
}
}
}
```
Fix the namespace following an earlier rename | ```c#
using System;
using BroadbandStats.Database.Migrations.Migrations;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors.SqlServer;
namespace BroadbandStats.Database.Migrations
{
public sealed class Migrator
{
private readonly string connectionString;
public Migrator(string connectionString)
{
if (connectionString == null)
{
throw new ArgumentNullException(nameof(connectionString));
}
this.connectionString = connectionString;
}
public void MigrateToLatestSchema()
{
var todaysDate = DateTime.Today.ToString("yyyyMMdd");
var todaysSchemaVersion = long.Parse(todaysDate);
MigrateTo(todaysSchemaVersion);
}
private void MigrateTo(long targetVersion)
{
var options = new MigrationOptions { PreviewOnly = false, Timeout = 60 };
var announcer = new NullAnnouncer();
var processor = new SqlServer2012ProcessorFactory().Create(connectionString, announcer, options);
var migrationContext = new RunnerContext(announcer) { Namespace = typeof(InitialDatabase).Namespace };
var runner = new MigrationRunner(GetType().Assembly, migrationContext, processor);
runner.MigrateUp(targetVersion, true);
}
}
}
``` |
4abefca7-5a17-4a16-bebf-453fad7ea727 | {
"language": "C#"
} | ```c#
namespace Tabster.Core.Plugins
{
public interface ITabsterPlugin
{
string Name { get; }
string Description { get; }
string Author { get; }
string Version { get; }
string[] PluginClasses { get; }
}
}
```
Use types instead of fully qualified names. | ```c#
using System;
namespace Tabster.Core.Plugins
{
public interface ITabsterPlugin
{
string Name { get; }
string Description { get; }
string Author { get; }
string Version { get; }
Type[] Types { get; }
}
}
``` |
233a9c9b-742c-4e43-9d0b-8cd28af11529 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Data
{
public class OnionState
{
public bool Enabled { get; set; } = true;
public bool CustomWorldSize { get; set; } = false;
public int Width { get; set; } = 256;
public int Height { get; set; } = 384;
public bool Debug { get; set; } = false;
public bool FreeCamera { get; set; } = true;
public bool CustomMaxCameraDistance { get; set; } = true;
public float MaxCameraDistance { get; set; } = 300;
public bool LogSeed { get; set; } = true;
public bool CustomSeeds { get; set; } = false;
public int WorldSeed { get; set; } = 0;
public int LayoutSeed { get; set; } = 0;
public int TerrainSeed { get; set; } = 0;
public int NoiseSeed { get; set; } = 0;
}
}
```
Change default world size to compensate for use of chunks | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Data
{
public class OnionState
{
public bool Enabled { get; set; } = true;
public bool CustomWorldSize { get; set; } = false;
public int Width { get; set; } = 8;
public int Height { get; set; } = 12;
public bool Debug { get; set; } = false;
public bool FreeCamera { get; set; } = true;
public bool CustomMaxCameraDistance { get; set; } = true;
public float MaxCameraDistance { get; set; } = 300;
public bool LogSeed { get; set; } = true;
public bool CustomSeeds { get; set; } = false;
public int WorldSeed { get; set; } = 0;
public int LayoutSeed { get; set; } = 0;
public int TerrainSeed { get; set; } = 0;
public int NoiseSeed { get; set; } = 0;
}
}
``` |
37799073-da89-4ae2-94d7-98c7f274fbc8 | {
"language": "C#"
} | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Collections.Specialized;
namespace CefSharp
{
public interface IRequest
{
string Url { get; set; }
string Method { get; }
string Body { get; }
NameValueCollection Headers { get; set; }
TransitionType TransitionType { get; }
}
}
```
Add xml comment to TransitionType | ```c#
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Collections.Specialized;
namespace CefSharp
{
public interface IRequest
{
string Url { get; set; }
string Method { get; }
string Body { get; }
NameValueCollection Headers { get; set; }
/// <summary>
/// Get the transition type for this request.
/// Applies to requests that represent a main frame or sub-frame navigation.
/// </summary>
TransitionType TransitionType { get; }
}
}
``` |
347014f6-d65b-4600-98ef-d68b40e18758 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModHardRock : ModHardRock
{
public override double ScoreMultiplier => 1.12;
public override bool Ranked => true;
}
}
```
Add HardRock position mangling for CatchTheBeat | ```c#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.MathUtils;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Mods;
using System;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModHardRock : ModHardRock, IApplicableToHitObject<CatchHitObject>
{
public override double ScoreMultiplier => 1.12;
public override bool Ranked => true;
private float lastStartX;
private int lastStartTime;
public void ApplyToHitObject(CatchHitObject hitObject)
{
// Code from Stable, we keep calculation on a scale of 0 to 512
float position = hitObject.X * 512;
int startTime = (int)hitObject.StartTime;
if (lastStartX == 0)
{
lastStartX = position;
lastStartTime = startTime;
return;
}
float diff = lastStartX - position;
int timeDiff = startTime - lastStartTime;
if (timeDiff > 1000)
{
lastStartX = position;
lastStartTime = startTime;
return;
}
if (diff == 0)
{
bool right = RNG.NextBool();
float rand = Math.Min(20, (float)RNG.NextDouble(0, timeDiff / 4));
if (right)
{
if (position + rand <= 512)
position += rand;
else
position -= rand;
}
else
{
if (position - rand >= 0)
position -= rand;
else
position += rand;
}
hitObject.X = position / 512;
return;
}
if (Math.Abs(diff) < timeDiff / 3)
{
if (diff > 0)
{
if (position - diff > 0)
position -= diff;
}
else
{
if (position - diff < 512)
position -= diff;
}
}
hitObject.X = position / 512;
lastStartX = position;
lastStartTime = startTime;
}
}
}
``` |
0bf08a43-f3c2-40cb-8d76-36adf96e948f | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Raven.Client.Document;
namespace RavenDBBlogConsole
{
class Program
{
static void Main(string[] args)
{
var docStore = new DocumentStore()
{
Url = "http://localhost:8080"
};
docStore.Initialize();
using (var session = docStore.OpenSession())
{
var blog = session.Load<Blog>("blogs/1");
Console.WriteLine("Name: {0}, Author: {1}", blog.Name, blog.Author);
}
}
}
public class Blog
{
public string Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
}
}
```
Add object with collection properties | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Raven.Client.Document;
namespace RavenDBBlogConsole
{
class Program
{
static void Main(string[] args)
{
var docStore = new DocumentStore()
{
Url = "http://localhost:8080"
};
docStore.Initialize();
using (var session = docStore.OpenSession())
{
var post = new Post()
{
BlogId = "blogs/33",
Comments = new List<Comment>() { new Comment() { CommenterName = "Bob", Text = "Hello!" } },
Content = "Some text",
Tags = new List<string>() { "tech" },
Title = "First post",
};
session.Store(post);
session.SaveChanges();
}
}
}
public class Blog
{
public string Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
}
public class Post
{
public string Id { get; set; }
public string BlogId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public List<Comment> Comments { get; set; }
public List<string> Tags { get; set; }
}
public class Comment
{
public string CommenterName { get; set; }
public string Text { get; set; }
}
}
``` |
11023570-cbc3-4761-8f37-ec16c332ff62 | {
"language": "C#"
} | ```c#
using System;
namespace BmpListener.Bmp
{
public class BmpInitiation : BmpMessage
{
public BmpInitiation(BmpHeader bmpHeader)
: base(bmpHeader)
{ }
}
}```
Add BMP version to initiation message | ```c#
using System;
namespace BmpListener.Bmp
{
public class BmpInitiation : BmpMessage
{
public BmpInitiation(BmpHeader bmpHeader)
: base(bmpHeader)
{
BmpVersion = BmpHeader.Version;
}
public int BmpVersion { get; }
}
}``` |
156b9b1d-2de6-45e7-b592-59e1a47f9cf4 | {
"language": "C#"
} | ```c#
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
namespace TimesheetParser
{
class MainViewModel
{
public ICommand CopyCommand { get; set; }
public MainViewModel()
{
CopyCommand = new DelegateCommand<string>(CopyCommand_Executed);
}
void CopyCommand_Executed(string param)
{
}
}
}
```
Implement text copying to Clipboard. | ```c#
using System.Windows;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
namespace TimesheetParser
{
class MainViewModel
{
public ICommand CopyCommand { get; set; }
public MainViewModel()
{
CopyCommand = new DelegateCommand<string>(CopyCommand_Executed);
}
void CopyCommand_Executed(string param)
{
Clipboard.SetData(DataFormats.UnicodeText, param);
}
}
}
``` |
dd967f0a-70b3-448d-9ada-d8191614fabb | {
"language": "C#"
} | ```c#
@using DataAccess
@using Localization
@using WebApplication.Helpers
@using WebGrease
@model IEnumerable<DataAccess.Site>
@{
ViewBag.Title = Resources.LabelSitesList;
}
@Html.Partial("_PageTitlePartial")
<table class="table">
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th class="hidden-sm">Postcode</th>
<th class="hidden-xs">Features</th>
<th style="font-weight:normal;">@Html.ActionLink("Create a New Site", "Create")</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.ActionLink("Delete Site", "Delete", new { id = item.Id })
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td class="hidden-sm" style="text-transform:uppercase;">@Html.DisplayFor(modelItem => item.Postcode)</td>
<td class="hidden-xs">
@Html.SiteSummaryIconsFor(item)
</td>
<td>
@Html.ActionLink("Site Report", "Report", new { id = item.Id }) |
@Html.ActionLink("Edit Site", "Edit", new { id = item.Id }) |
@Html.ActionLink(Resources.LabelPerformanceData, "Index", "Months", new { id = item.Id }, null)
</td>
</tr>
}
</table>
```
Hide the site report on really small screens. | ```c#
@using DataAccess
@using Localization
@using WebApplication.Helpers
@using WebGrease
@model IEnumerable<DataAccess.Site>
@{
ViewBag.Title = Resources.LabelSitesList;
}
@Html.Partial("_PageTitlePartial")
<table class="table">
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th class="hidden-sm hidden-xs">Postcode</th>
<th class="hidden-xs">Features</th>
<th style="font-weight:normal;">@Html.ActionLink("Create a New Site", "Create")</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.ActionLink("Delete Site", "Delete", new { id = item.Id })
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td class="hidden-sm hidden-xs" style="text-transform:uppercase;">@Html.DisplayFor(modelItem => item.Postcode)</td>
<td class="hidden-xs">
@Html.SiteSummaryIconsFor(item)
</td>
<td>
<span class="hidden-xs">@Html.ActionLink("Site Report", "Report", new { id = item.Id }) | </span>
@Html.ActionLink("Edit Site", "Edit", new { id = item.Id }) |
@Html.ActionLink(Resources.LabelPerformanceData, "Index", "Months", new { id = item.Id }, null)
</td>
</tr>
}
</table>
``` |
5b12c078-d6f8-452a-b10a-8e024286955f | {
"language": "C#"
} | ```c#
//
// Copyright 2014 luke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace WolfyBot.Core
{
public class IRCMessage
{
public IRCMessage ()
{
}
}
}
```
Implement basic IRC Message without parsing IRC format yet | ```c#
//
// Copyright 2014 luke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace WolfyBot.Core
{
public class IRCMessage
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WolfyBot.Core.IRCMessage"/> class.
/// </summary>
/// <param name="ircMessage">A Message formatted in the IRC Protocol</param>
public IRCMessage (String ircMessage)
{
TimeStamp = DateTime.Now;
//TODO: write IRC Parser
}
//Copy Constructor
public IRCMessage (IRCMessage other)
{
TimeStamp = other.TimeStamp;
Prefix = new String (other.Prefix);
Command = new String (other.Command);
Parameters = new String (other.Parameters);
TrailingParameters = new String (other.TrailingParameters);
}
#endregion
#region Methods
public String ToIRCString ()
{
//TODO: Implement Serialization to IRC Protocol
}
public String ToLogString ()
{
//TODO: Implement Serialization to logging format
}
#endregion
#region Properties
public String Prefix {
get;
set;
}
public String Command {
get;
set;
}
public String Parameters {
get;
set;
}
public String TrailingParameters {
get;
set;
}
public DateTime TimeStamp {
get;
set;
}
#endregion
}
}
``` |
3d15883d-40ae-44df-b16b-22514eaac8d0 | {
"language": "C#"
} | ```c#
using System.Linq;
using OdjfsScraper.Database;
namespace OdjfsScraper.Tool.Support
{
public class DaemonEventLoop
{
private readonly Entities _ctx;
public DaemonEventLoop(Entities ctx)
{
_ctx = ctx;
UpdateCounts();
CurrentStep = 0;
IsRunning = true;
}
public bool IsRunning { get; set; }
public int CurrentStep { get; private set; }
public int CountyCount { get; private set; }
public int ChildCareCount { get; private set; }
private int StepCount
{
get { return CountyCount + ChildCareCount; }
}
public int ChildCaresPerCounty
{
get
{
if (CountyCount == 0)
{
return 0;
}
return ChildCareCount/CountyCount;
}
}
public bool IsCountyStep
{
get
{
if (ChildCaresPerCounty == 0)
{
return true;
}
return CurrentStep%ChildCaresPerCounty == 1;
}
}
public bool IsChildCareStep
{
get { return !IsCountyStep; }
}
private void UpdateCounts()
{
CountyCount = _ctx.Counties.Count();
ChildCareCount = _ctx.ChildCares.Count();
}
public bool NextStep()
{
CurrentStep = (CurrentStep + 1)%StepCount;
if (CurrentStep == 0)
{
UpdateCounts();
}
return IsRunning;
}
}
}```
Fix daemon event loop bugs | ```c#
using System.Linq;
using OdjfsScraper.Database;
namespace OdjfsScraper.Tool.Support
{
public class DaemonEventLoop
{
private readonly Entities _ctx;
public DaemonEventLoop(Entities ctx)
{
_ctx = ctx;
UpdateCounts();
CurrentStep = -1;
IsRunning = true;
}
public bool IsRunning { get; set; }
public int CurrentStep { get; private set; }
public int CountyCount { get; private set; }
public int ChildCareCount { get; private set; }
private int StepCount
{
get { return CountyCount + ChildCareCount; }
}
public int ChildCaresPerCounty
{
get
{
if (CountyCount == 0)
{
return 0;
}
return ChildCareCount/CountyCount;
}
}
public bool IsCountyStep
{
get
{
if (ChildCaresPerCounty == 0)
{
return true;
}
return CurrentStep%ChildCaresPerCounty == 1;
}
}
public bool IsChildCareStep
{
get { return !IsCountyStep; }
}
private void UpdateCounts()
{
CountyCount = _ctx.Counties.Count();
ChildCareCount = _ctx.ChildCares.Count() + _ctx.ChildCareStubs.Count();
}
public bool NextStep()
{
CurrentStep = (CurrentStep + 1)%StepCount;
if (CurrentStep == 0)
{
UpdateCounts();
}
return IsRunning;
}
}
}``` |
bcece5d9-9efa-42c1-9d17-d37b9e3f7407 | {
"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 Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Android
{
[Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullUser, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)]
public class OsuGameActivity : AndroidGameActivity
{
protected override Framework.Game CreateGame() => new OsuGameAndroid(this);
protected override void OnCreate(Bundle savedInstanceState)
{
// The default current directory on android is '/'.
// On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage.
// In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory.
System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
}
}
```
Add an IntentFilter to handle osu! files. | ```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 Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Android
{
[Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullUser, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)]
[IntentFilter(new[] { Intent.ActionDefault }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable, Intent.CategoryAppFiles }, DataSchemes = new[] { "content" }, DataPathPatterns = new[] { ".*\\.osz", ".*\\.osk" }, DataMimeType = "application/*")]
public class OsuGameActivity : AndroidGameActivity
{
protected override Framework.Game CreateGame() => new OsuGameAndroid(this);
protected override void OnCreate(Bundle savedInstanceState)
{
// The default current directory on android is '/'.
// On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage.
// In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory.
System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
}
}
``` |
812465de-1795-4c99-9b32-da756b42b111 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace ActorTestingFramework
{
public class RandomScheduler : IScheduler
{
private readonly Random rand;
public RandomScheduler(int seed)
{
rand = new Random(seed);
}
private static bool IsProgressOp(OpType op)
{
switch (op)
{
case OpType.INVALID:
case OpType.START:
case OpType.END:
case OpType.CREATE:
case OpType.JOIN:
case OpType.WaitForDeadlock:
case OpType.Yield:
return false;
case OpType.SEND:
case OpType.RECEIVE:
return true;
default:
throw new ArgumentOutOfRangeException(nameof(op), op, null);
}
}
#region Implementation of IScheduler
public ActorInfo GetNext(List<ActorInfo> actorList, ActorInfo currentActor)
{
if (currentActor.currentOp == OpType.Yield)
{
currentActor.enabled = false;
}
if (IsProgressOp(currentActor.currentOp))
{
foreach (var actorInfo in
actorList.Where(info => info.currentOp == OpType.Yield && !info.enabled))
{
actorInfo.enabled = true;
}
}
var enabled = actorList.Where(info => info.enabled).ToList();
if (enabled.Count == 0)
{
return null;
}
int nextIndex = rand.Next(enabled.Count - 1);
return enabled[nextIndex];
}
public void NextSchedule()
{
}
#endregion
}
}```
Change how yield works: treat more op types as "progress". | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
namespace ActorTestingFramework
{
public class RandomScheduler : IScheduler
{
private readonly Random rand;
public RandomScheduler(int seed)
{
rand = new Random(seed);
}
private static bool IsProgressOp(OpType op)
{
switch (op)
{
case OpType.INVALID:
case OpType.WaitForDeadlock:
case OpType.Yield:
return false;
case OpType.START:
case OpType.END:
case OpType.CREATE:
case OpType.JOIN:
case OpType.SEND:
case OpType.RECEIVE:
return true;
default:
throw new ArgumentOutOfRangeException(nameof(op), op, null);
}
}
#region Implementation of IScheduler
public ActorInfo GetNext(List<ActorInfo> actorList, ActorInfo currentActor)
{
if (currentActor.currentOp == OpType.Yield)
{
currentActor.enabled = false;
}
if (IsProgressOp(currentActor.currentOp))
{
foreach (var actorInfo in
actorList.Where(info => info.currentOp == OpType.Yield && !info.enabled))
{
actorInfo.enabled = true;
}
}
var enabled = actorList.Where(info => info.enabled).ToList();
if (enabled.Count == 0)
{
return null;
}
int nextIndex = rand.Next(enabled.Count - 1);
return enabled[nextIndex];
}
public void NextSchedule()
{
}
#endregion
}
}``` |
2bd05acd-ece0-4723-a2a7-d458a4419910 | {
"language": "C#"
} | ```c#
using System.Reflection;
#if !NETCORE
using System.Runtime.Serialization;
#endif
namespace Moq
{
/// <summary>
/// A <see cref="IDefaultValueProvider"/> that returns an empty default value
/// for serializable types that do not implement <see cref="ISerializable"/> properly,
/// and returns the value provided by the decorated provider otherwise.
/// </summary>
internal class SerializableTypesValueProvider : IDefaultValueProvider
{
private readonly IDefaultValueProvider decorated;
private readonly EmptyDefaultValueProvider emptyDefaultValueProvider = new EmptyDefaultValueProvider();
public SerializableTypesValueProvider(IDefaultValueProvider decorated)
{
this.decorated = decorated;
}
public void DefineDefault<T>(T value)
{
decorated.DefineDefault(value);
}
public object ProvideDefault(MethodInfo member)
{
return !member.ReturnType.GetTypeInfo().IsSerializable || member.ReturnType.IsSerializableMockable()
? decorated.ProvideDefault(member)
: emptyDefaultValueProvider.ProvideDefault(member);
}
}
}```
Fix an issue where ISerializable is not available on .NET Core | ```c#
using System.Reflection;
#if !NETCORE
using System.Runtime.Serialization;
#endif
namespace Moq
{
#if !NETCORE
/// <summary>
/// A <see cref="IDefaultValueProvider"/> that returns an empty default value
/// for serializable types that do not implement <see cref="ISerializable"/> properly,
/// and returns the value provided by the decorated provider otherwise.
/// </summary>
#else
/// <summary>
/// A <see cref="IDefaultValueProvider"/> that returns an empty default value
/// for serializable types that do not implement ISerializable properly,
/// and returns the value provided by the decorated provider otherwise.
/// </summary>
#endif
internal class SerializableTypesValueProvider : IDefaultValueProvider
{
private readonly IDefaultValueProvider decorated;
private readonly EmptyDefaultValueProvider emptyDefaultValueProvider = new EmptyDefaultValueProvider();
public SerializableTypesValueProvider(IDefaultValueProvider decorated)
{
this.decorated = decorated;
}
public void DefineDefault<T>(T value)
{
decorated.DefineDefault(value);
}
public object ProvideDefault(MethodInfo member)
{
return !member.ReturnType.GetTypeInfo().IsSerializable || member.ReturnType.IsSerializableMockable()
? decorated.ProvideDefault(member)
: emptyDefaultValueProvider.ProvideDefault(member);
}
}
}``` |
4f66b107-1d73-49cd-ba1e-8c24ea6ae950 | {
"language": "C#"
} | ```c#
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;
using Resonance.Common.Web;
using System.Diagnostics;
using System.Linq;
namespace Resonance.Windows
{
public class Program
{
public static void Main(string[] args)
{
var isService = !(Debugger.IsAttached || args.Contains("--console"));
var host = ResonanceWebHostBuilderExtensions.GetWebHostBuilder()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
if (isService)
{
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
host.RunAsService();
}
else
{
host.Run();
}
}
}
}```
Fix execution of windows app | ```c#
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;
using Resonance.Common.Web;
using System.Diagnostics;
using System.Linq;
namespace Resonance.Windows
{
public class Program
{
public static void Main(string[] args)
{
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
var isService = !(Debugger.IsAttached || args.Contains("--console"));
var host = ResonanceWebHostBuilderExtensions.GetWebHostBuilder()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
if (isService)
{
host.RunAsService();
}
else
{
host.Run();
}
}
}
}``` |
a47e3a10-921c-4fc0-865b-ffa033a773e9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
namespace RimDev.Supurlative
{
public class SupurlativeOptions
{
public static readonly SupurlativeOptions Defaults =
new SupurlativeOptions();
public UriKind UriKind { get; set; }
public string PropertyNameSeperator { get; set; }
public bool LowercaseKeys { get; set; }
public SupurlativeOptions()
{
UriKind = UriKind.Absolute;
PropertyNameSeperator = ".";
Formatters = new List<BaseFormatterAttribute>();
LowercaseKeys = true;
}
public void Validate()
{
if (UriKind == UriKind.RelativeOrAbsolute) throw new ArgumentException("must choose between relative or absolute", "UriKind");
if (PropertyNameSeperator == null) throw new ArgumentNullException("PropertyNameSeperator", "seperator must not be null");
}
public IList<BaseFormatterAttribute> Formatters { get; protected set; }
public SupurlativeOptions AddFormatter(BaseFormatterAttribute formatter)
{
if (formatter == null) throw new ArgumentNullException("formatter");
Formatters.Add(formatter);
return this;
}
public SupurlativeOptions AddFormatter<T>()
where T : BaseFormatterAttribute
{
return AddFormatter(Activator.CreateInstance<T>());
}
public SupurlativeOptions AddFormatter<T>(Func<T, string> func)
{
return AddFormatter(new LambdaFormatter(typeof(T), (x) => func((T)x)));
}
}
}
```
Fix issue of singleton causing false-positives during running of full test-suite | ```c#
using System;
using System.Collections.Generic;
namespace RimDev.Supurlative
{
public class SupurlativeOptions
{
public static SupurlativeOptions Defaults
{
get
{
return new SupurlativeOptions();
}
}
public UriKind UriKind { get; set; }
public string PropertyNameSeperator { get; set; }
public bool LowercaseKeys { get; set; }
public SupurlativeOptions()
{
UriKind = UriKind.Absolute;
PropertyNameSeperator = ".";
Formatters = new List<BaseFormatterAttribute>();
LowercaseKeys = true;
}
public void Validate()
{
if (UriKind == UriKind.RelativeOrAbsolute) throw new ArgumentException("must choose between relative or absolute", "UriKind");
if (PropertyNameSeperator == null) throw new ArgumentNullException("PropertyNameSeperator", "seperator must not be null");
}
public IList<BaseFormatterAttribute> Formatters { get; protected set; }
public SupurlativeOptions AddFormatter(BaseFormatterAttribute formatter)
{
if (formatter == null) throw new ArgumentNullException("formatter");
Formatters.Add(formatter);
return this;
}
public SupurlativeOptions AddFormatter<T>()
where T : BaseFormatterAttribute
{
return AddFormatter(Activator.CreateInstance<T>());
}
public SupurlativeOptions AddFormatter<T>(Func<T, string> func)
{
return AddFormatter(new LambdaFormatter(typeof(T), (x) => func((T)x)));
}
}
}
``` |
009c65d1-d376-45d1-a0f8-8a44994bac0d | {
"language": "C#"
} | ```c#
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GifWin.Data
{
class GifWinDatabaseHelper : IDisposable
{
GifWinContext db;
public GifWinDatabaseHelper()
{
db = new GifWinContext();
}
public async Task<int> ConvertGifWitLibraryAsync(GifWitLibrary librarySource)
{
foreach (var entry in librarySource) {
var newGif = new GifEntry {
Url = entry.Url.ToString(),
AddedAt = DateTimeOffset.UtcNow,
};
foreach (var tag in entry.KeywordString.Split(' ')) {
newGif.Tags.Add(new GifTag { Tag = tag });
}
db.Gifs.Add(newGif);
}
return await db.SaveChangesAsync().ConfigureAwait(false);
}
public async Task<IEnumerable<GifEntry>> LoadAllGifsAsync()
{
return await db.Gifs.Include(ge => ge.Tags).ToArrayAsync().ConfigureAwait(false);
}
private bool disposedValue = false;
protected virtual void Dispose(bool disposing)
{
if (!disposedValue) {
if (disposing) {
db.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}
```
Add way to record usage, fix LoadAllGifsAsync | ```c#
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GifWin.Data
{
class GifWinDatabaseHelper : IDisposable
{
GifWinContext db;
public GifWinDatabaseHelper()
{
db = new GifWinContext();
}
public async Task<int> ConvertGifWitLibraryAsync(GifWitLibrary librarySource)
{
foreach (var entry in librarySource) {
var newGif = new GifEntry {
Url = entry.Url.ToString(),
AddedAt = DateTimeOffset.UtcNow,
};
foreach (var tag in entry.KeywordString.Split(' ')) {
newGif.Tags.Add(new GifTag { Tag = tag });
}
db.Gifs.Add(newGif);
}
return await db.SaveChangesAsync().ConfigureAwait(false);
}
public async Task RecordGifUsageAsync(int gifId)
{
var gif = await db.Gifs.SingleOrDefaultAsync(ge => ge.Id == gifId).ConfigureAwait(false);
if (gif != null) {
var ts = DateTimeOffset.UtcNow;
var usage = new GifUsage();
gif.LastUsed = usage.UsedAt = ts;
gif.Usages.Add(usage);
await db.SaveChangesAsync().ConfigureAwait(false);
}
}
public async Task<IQueryable<GifEntry>> LoadAllGifsAsync()
{
var query = db.Gifs.Include(ge => ge.Tags);
await query.LoadAsync().ConfigureAwait(false);
return query;
}
private bool disposedValue = false;
protected virtual void Dispose(bool disposing)
{
if (!disposedValue) {
if (disposing) {
db.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}
``` |
9b545f3f-3d1d-4304-8ff2-9a74e58a4542 | {
"language": "C#"
} | ```c#
using System;
using System.Threading.Tasks;
namespace MicroFlow
{
public abstract class SyncActivity<TResult> : Activity<TResult>
{
public sealed override Task<TResult> Execute()
{
var tcs = new TaskCompletionSource<TResult>();
try
{
TResult result = ExecuteActivity();
tcs.TrySetResult(result);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
return tcs.Task;
}
protected abstract TResult ExecuteActivity();
}
public abstract class SyncActivity : Activity
{
protected sealed override Task ExecuteCore()
{
var tcs = new TaskCompletionSource<Null>();
try
{
ExecuteActivity();
tcs.TrySetResult(null);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
return tcs.Task;
}
protected abstract void ExecuteActivity();
}
}```
Use `TaskHelper` instead of TCS | ```c#
using System;
using System.Threading.Tasks;
namespace MicroFlow
{
public abstract class SyncActivity<TResult> : Activity<TResult>
{
public sealed override Task<TResult> Execute()
{
try
{
TResult result = ExecuteActivity();
return TaskHelper.FromResult(result);
}
catch (Exception ex)
{
return TaskHelper.FromException<TResult>(ex);
}
}
protected abstract TResult ExecuteActivity();
}
public abstract class SyncActivity : Activity
{
protected sealed override Task ExecuteCore()
{
try
{
ExecuteActivity();
return TaskHelper.CompletedTask;
}
catch (Exception ex)
{
return TaskHelper.FromException(ex);
}
}
protected abstract void ExecuteActivity();
}
}``` |
a960465c-5ec7-45a4-b9a1-2760eaf243b1 | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
using ReactiveUI.Mobile;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Akavache.Mobile
{
public class Registrations : IWantsToRegisterStuff
{
public void Register(Action<Func<object>, Type, string> registerFunction)
{
registerFunction(() => new JsonSerializerSettings()
{
ObjectCreationHandling = ObjectCreationHandling.Replace,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameHandling = TypeNameHandling.All,
}, typeof(JsonSerializerSettings), null);
var akavacheDriver = new AkavacheDriver();
registerFunction(() => akavacheDriver, typeof(ISuspensionDriver), null);
#if APPKIT || UIKIT
registerFunction(() => new MacFilesystemProvider(), typeof(IFilesystemProvider), null);
#endif
#if ANDROID
registerFunction(() => new AndroidFilesystemProvider(), typeof(IFilesystemProvider), null);
#endif
}
}
}```
Bring back setting the app name based on the package info | ```c#
using Newtonsoft.Json;
using ReactiveUI.Mobile;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if UIKIT
using MonoTouch.Foundation;
using ReactiveUI.Mobile;
#endif
#if APPKIT
using MonoMac.Foundation;
#endif
#if ANDROID
using Android.App;
#endif
#if APPKIT
namespace Akavache.Mac
#else
namespace Akavache.Mobile
#endif
{
public class Registrations : IWantsToRegisterStuff
{
public void Register(Action<Func<object>, Type, string> registerFunction)
{
registerFunction(() => new JsonSerializerSettings()
{
ObjectCreationHandling = ObjectCreationHandling.Replace,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameHandling = TypeNameHandling.All,
}, typeof(JsonSerializerSettings), null);
var akavacheDriver = new AkavacheDriver();
registerFunction(() => akavacheDriver, typeof(ISuspensionDriver), null);
#if APPKIT || UIKIT
BlobCache.ApplicationName = NSBundle.MainBundle.BundleIdentifier;
registerFunction(() => new MacFilesystemProvider(), typeof(IFilesystemProvider), null);
#endif
#if ANDROID
var ai = Application.Context.PackageManager.GetApplicationInfo(Application.Context.PackageName, 0);
BlobCache.ApplicationName = ai.LoadLabel(Application.Context.PackageManager);
registerFunction(() => new AndroidFilesystemProvider(), typeof(IFilesystemProvider), null);
#endif
}
}
}``` |
04a1b308-364d-476b-bc49-2f2d89d1c783 | {
"language": "C#"
} | ```c#
namespace HtmlLogger.Model
{
public enum LogCategory
{
Info,
Error
}
}```
Add Warning value to the enumeration. | ```c#
namespace HtmlLogger.Model
{
public enum LogCategory
{
Info,
Warning,
Error
}
}``` |
9806f7da-9f39-4fb3-a310-466a8b63bae5 | {
"language": "C#"
} | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LibPhoneNumber.Contrib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LibPhoneNumber.Contrib")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ea084a1-6add-4b90-97fe-5ec441b8cb76")]
[assembly: AssemblyVersion(AssemblyMeta.Version)]
[assembly: AssemblyFileVersion(AssemblyMeta.Version)]
[assembly: AssemblyInformationalVersion(AssemblyMeta.Version)]
internal static class AssemblyMeta
{
public const string Version = "1.1.2";
}
```
Update the assembly version for LibPhoneNumber.Contrib since we added a new extension method. | ```c#
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LibPhoneNumber.Contrib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LibPhoneNumber.Contrib")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ea084a1-6add-4b90-97fe-5ec441b8cb76")]
[assembly: AssemblyVersion(AssemblyMeta.Version)]
[assembly: AssemblyFileVersion(AssemblyMeta.Version)]
[assembly: AssemblyInformationalVersion(AssemblyMeta.Version)]
internal static class AssemblyMeta
{
public const string Version = "1.2.0";
}
``` |
2604e715-810a-4b8c-bec2-c6a9ea9dd7c3 | {
"language": "C#"
} | ```c#
using ServiceStack.OrmLite;
namespace Nonagon.Modular
{
/// <summary>
/// Data module interface base class.
/// </summary>
public abstract class DataModuleInterface : ModuleInterface, IDataModuleInterface
{
/// <summary>
/// Gets or sets the db connection factory.
/// </summary>
/// <value>The db connection factory.</value>
public IDbConnectionFactory DbConnectionFactory { get; private set; }
public DataModuleInterface(IDbConnectionFactory dbConnectionFactory)
{
DbConnectionFactory = dbConnectionFactory;
}
/// <summary>
/// Resolve the instance of operation from type parameter.
/// </summary>
/// <typeparam name="TOperation">The IDataModuleOperation to be instantiated.</typeparam>
protected override TOperation Resolve<TOperation>()
{
TOperation opt = base.Resolve<TOperation>();
if(opt is IDataModuleOperation)
(opt as IDataModuleOperation).DbConnectionFactory = DbConnectionFactory;
return opt;
}
}
}
```
Fix code as suggested by compiler. | ```c#
using ServiceStack.OrmLite;
namespace Nonagon.Modular
{
/// <summary>
/// Data module interface base class.
/// </summary>
public abstract class DataModuleInterface : ModuleInterface, IDataModuleInterface
{
/// <summary>
/// Gets or sets the db connection factory.
/// </summary>
/// <value>The db connection factory.</value>
public IDbConnectionFactory DbConnectionFactory { get; private set; }
protected DataModuleInterface(IDbConnectionFactory dbConnectionFactory)
{
DbConnectionFactory = dbConnectionFactory;
}
/// <summary>
/// Resolve the instance of operation from type parameter.
/// </summary>
/// <typeparam name="TOperation">The IDataModuleOperation to be instantiated.</typeparam>
protected override TOperation Resolve<TOperation>()
{
TOperation opt = base.Resolve<TOperation>();
var iDataModuleOperation = opt as IDataModuleOperation;
if(iDataModuleOperation != null)
iDataModuleOperation.DbConnectionFactory = DbConnectionFactory;
return opt;
}
}
}
``` |
27687c11-1d77-430d-ab62-a58111696ba7 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;
namespace dotnet_setversion
{
public class Options
{
[Option('r', "recursive", Default = false, HelpText =
"Recursively search the current directory for csproj files and apply the given version to all files found. " +
"Mutually exclusive to the csprojFile argument.")]
public bool Recursive { get; set; }
[Value(0, MetaName = "version", HelpText = "The version to apply to the given csproj file(s).",
Required = true)]
public string Version { get; set; }
[Value(1, MetaName = "csprojFile", Required = false, HelpText =
"Path to a csproj file to apply the given version. Mutually exclusive to the --recursive option.")]
public string CsprojFile { get; set; }
[Usage(ApplicationAlias = "dotnet setversion")]
public static IEnumerable<Example> Examples
{
get
{
yield return new Example("Directory with a single csproj file", new Options {Version = "1.2.3"});
yield return new Example("Explicitly specifying a csproj file",
new Options {Version = "1.2.3", CsprojFile = "MyProject.csproj"});
yield return new Example("Large repo with multiple csproj files in nested directories",
new UnParserSettings {PreferShortName = true}, new Options {Version = "1.2.3", Recursive = true});
}
}
}
}```
Update alias in usage examples | ```c#
using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;
namespace dotnet_setversion
{
public class Options
{
[Option('r', "recursive", Default = false, HelpText =
"Recursively search the current directory for csproj files and apply the given version to all files found. " +
"Mutually exclusive to the csprojFile argument.")]
public bool Recursive { get; set; }
[Value(0, MetaName = "version", HelpText = "The version to apply to the given csproj file(s).",
Required = true)]
public string Version { get; set; }
[Value(1, MetaName = "csprojFile", Required = false, HelpText =
"Path to a csproj file to apply the given version. Mutually exclusive to the --recursive option.")]
public string CsprojFile { get; set; }
[Usage(ApplicationAlias = "setversion")]
public static IEnumerable<Example> Examples
{
get
{
yield return new Example("Directory with a single csproj file", new Options {Version = "1.2.3"});
yield return new Example("Explicitly specifying a csproj file",
new Options {Version = "1.2.3", CsprojFile = "MyProject.csproj"});
yield return new Example("Large repo with multiple csproj files in nested directories",
new UnParserSettings {PreferShortName = true}, new Options {Version = "1.2.3", Recursive = true});
}
}
}
}``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.