Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Allow reading certificates from local files | using System.Configuration;
using System.IdentityModel.Tokens;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Web.Hosting;
namespace Dragon.SecurityServer.Common
{
public class SecurityHelper
{
public static X509SigningCredentials CreateSignupCredentialsFromConfig()
{
return new X509SigningCredentials(new X509Certificate2(X509Certificate.CreateFromCertFile(
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, ConfigurationManager.AppSettings["SigningCertificateName"]))));
}
}
}
| using System.Configuration;
using System.IdentityModel.Tokens;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Web.Hosting;
namespace Dragon.SecurityServer.Common
{
public class SecurityHelper
{
public static X509SigningCredentials CreateSignupCredentialsFromConfig()
{
var certificateFilePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, ConfigurationManager.AppSettings["SigningCertificateName"]);
var data = File.ReadAllBytes(certificateFilePath);
var certificate = new X509Certificate2(data, string.Empty, X509KeyStorageFlags.MachineKeySet);
return new X509SigningCredentials(certificate);
}
}
}
|
Fix error in unit test from changing the ToString | using compiler.middleend.ir;
using NUnit.Framework;
namespace NUnit.Tests.MiddleEnd
{
[TestFixture]
public class InstructionTests
{
[Test]
public void ToStringTest()
{
var inst1 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 10),
new Operand(Operand.OpType.Identifier, 10));
var inst2 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 05),
new Operand(inst1));
Assert.AreEqual( inst2.Num.ToString() + " Add #5 (" + inst1.Num.ToString() + ")",inst2.ToString());
}
}
}
| using compiler.middleend.ir;
using NUnit.Framework;
namespace NUnit.Tests.MiddleEnd
{
[TestFixture]
public class InstructionTests
{
[Test]
public void ToStringTest()
{
var inst1 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 10),
new Operand(Operand.OpType.Identifier, 10));
var inst2 = new Instruction(IrOps.Add, new Operand(Operand.OpType.Constant, 05),
new Operand(inst1));
Assert.AreEqual( inst2.Num.ToString() + ": Add #5 (" + inst1.Num.ToString() + ")",inst2.ToString());
}
}
}
|
Update copyright statement to 2014 | 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("Tomato")]
[assembly: AssemblyDescription("Pomodoro Timer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Software Punt")]
[assembly: AssemblyProduct("Tomato")]
[assembly: AssemblyCopyright("Copyright © Software Punt 2013")]
[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("e5f59157-7a01-4616-86e3-c9a924d8a218")]
// 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")]
| 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("Tomato")]
[assembly: AssemblyDescription("Pomodoro Timer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Software Punt")]
[assembly: AssemblyProduct("Tomato")]
[assembly: AssemblyCopyright("Copyright © Software Punt 2014")]
[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("e5f59157-7a01-4616-86e3-c9a924d8a218")]
// 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")]
|
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. | using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.Mef")]
[assembly: AssemblyDescription("")]
| using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.Mef")]
|
Fix a build error of UnityPackage | using System;
using EntityNetwork;
using EntityNetwork.Unity3D;
using UnityEngine;
public class ClientEntityFactory : IClientEntityFactory
{
private static ClientEntityFactory _default;
public static ClientEntityFactory Default
{
get { return _default ?? (_default = new ClientEntityFactory()); }
}
public Transform RootTransform { get; set; }
IClientEntity IClientEntityFactory.Create(Type protoTypeType)
{
var resource = Resources.Load("Client" + protoTypeType.Name.Substring(1));
var go = (GameObject)GameObject.Instantiate(resource);
if (RootTransform != null)
go.transform.SetParent(RootTransform, false);
return go.GetComponent<IClientEntity>();
}
void IClientEntityFactory.Delete(IClientEntity entity)
{
var enb = ((EntityNetworkBehaviour)entity);
GameObject.Destroy(enb.gameObject);
}
}
| using System;
using System.Collections.Concurrent;
using EntityNetwork;
using EntityNetwork.Unity3D;
using UnityEngine;
public class ClientEntityFactory : IClientEntityFactory
{
private static ClientEntityFactory _default;
public static ClientEntityFactory Default
{
get { return _default ?? (_default = new ClientEntityFactory()); }
}
public Transform RootTransform { get; set; }
private readonly ConcurrentDictionary<Type, Type> _clientEntityToProtoTypeMap =
new ConcurrentDictionary<Type, Type>();
Type IClientEntityFactory.GetProtoType(Type entityType)
{
return _clientEntityToProtoTypeMap.GetOrAdd(entityType, t =>
{
var type = entityType;
while (type != null && type != typeof(object))
{
if (type.Name.EndsWith("ClientBase"))
{
var typePrefix = type.Namespace.Length > 0 ? type.Namespace + "." : "";
var protoType = type.Assembly.GetType(typePrefix + "I" +
type.Name.Substring(0, type.Name.Length - 10));
if (protoType != null && typeof(IEntityPrototype).IsAssignableFrom(protoType))
{
return protoType;
}
}
type = type.BaseType;
}
return null;
});
}
IClientEntity IClientEntityFactory.Create(Type protoType)
{
var resourceName = "Client" + protoType.Name.Substring(1);
var resource = Resources.Load(resourceName);
if (resource == null)
throw new InvalidOperationException("Failed to load resource(" + resourceName + ")");
var go = (GameObject)GameObject.Instantiate(resource);
if (go == null)
throw new InvalidOperationException("Failed to instantiate resource(" + resourceName + ")");
if (RootTransform != null)
go.transform.SetParent(RootTransform, false);
return go.GetComponent<IClientEntity>();
}
void IClientEntityFactory.Delete(IClientEntity entity)
{
var enb = ((EntityNetworkBehaviour)entity);
GameObject.Destroy(enb.gameObject);
}
}
|
Unify namespace placement with the .Overloads partial class | namespace Moq
{
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Runtime.CompilerServices;
using Moq.Sdk;
/// <summary>
/// Instantiates mocks for the specified types.
/// </summary>
[GeneratedCode("Moq", "5.0")]
[CompilerGenerated]
partial class Mock
{
/// <summary>
/// Creates the mock instance by using the specified types to
/// lookup the mock type in the assembly defining this class.
/// </summary>
private static T Create<T>(MockBehavior behavior, object[] constructorArgs, params Type[] interfaces)
{
var mocked = (IMocked)MockFactory.Default.CreateMock(typeof(Mock).GetTypeInfo().Assembly, typeof(T), interfaces, constructorArgs);
mocked.Initialize(behavior);
return (T)mocked;
}
}
} | using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Runtime.CompilerServices;
using Moq.Sdk;
namespace Moq
{
/// <summary>
/// Instantiates mocks for the specified types.
/// </summary>
[GeneratedCode("Moq", "5.0")]
[CompilerGenerated]
partial class Mock
{
/// <summary>
/// Creates the mock instance by using the specified types to
/// lookup the mock type in the assembly defining this class.
/// </summary>
private static T Create<T>(MockBehavior behavior, object[] constructorArgs, params Type[] interfaces)
{
var mocked = (IMocked)MockFactory.Default.CreateMock(typeof(Mock).GetTypeInfo().Assembly, typeof(T), interfaces, constructorArgs);
mocked.Initialize(behavior);
return (T)mocked;
}
}
} |
Revert "Removing 'zzz' from method name" | using System;
using System.Linq;
namespace Smartrak.Collections.Paging
{
public static class PagingHelpers
{
/// <summary>
/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
/// </summary>
/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
/// <param name="entities">A queryable of entities</param>
/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
/// <returns>A queryable of the page of entities with counts appended.</returns>
public static IQueryable<EntityWithCount<T>> GetPageWithTotal<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
if (entities == null)
{
throw new ArgumentNullException("entities");
}
if (page < 1)
{
throw new ArgumentException("Must be positive", "page");
}
if (pageSize < 1)
{
throw new ArgumentException("Must be positive", "pageSize");
}
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip(page - 1 * pageSize)
.Take(pageSize);
}
}
}
| using System;
using System.Linq;
namespace Smartrak.Collections.Paging
{
public static class PagingHelpers
{
/// <summary>
/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
/// </summary>
/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
/// <param name="entities">A queryable of entities</param>
/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
/// <returns>A queryable of the page of entities with counts appended.</returns>
public static IQueryable<EntityWithCount<T>> GetPageWithTotalzzz<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
if (entities == null)
{
throw new ArgumentNullException("entities");
}
if (page < 1)
{
throw new ArgumentException("Must be positive", "page");
}
if (pageSize < 1)
{
throw new ArgumentException("Must be positive", "pageSize");
}
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip(page - 1 * pageSize)
.Take(pageSize);
}
}
}
|
Reduce noise in json output and handle the case the file doesn't exist | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;
namespace osu.Game.Tournament.Tests
{
public class TestCaseLadderManager : OsuTestCase
{
[Cached]
private readonly LadderManager manager;
public TestCaseLadderManager()
{
var teams = JsonConvert.DeserializeObject<List<TournamentTeam>>(File.ReadAllText(@"teams.json"));
var ladder = JsonConvert.DeserializeObject<LadderInfo>(File.ReadAllText(@"bracket.json")) ?? new LadderInfo();
Child = manager = new LadderManager(ladder, teams);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
File.WriteAllText(@"bracket.json", JsonConvert.SerializeObject(manager.Info));
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;
namespace osu.Game.Tournament.Tests
{
public class TestCaseLadderManager : OsuTestCase
{
[Cached]
private readonly LadderManager manager;
public TestCaseLadderManager()
{
var teams = JsonConvert.DeserializeObject<List<TournamentTeam>>(File.ReadAllText(@"teams.json"));
var ladder = File.Exists(@"bracket.json") ? JsonConvert.DeserializeObject<LadderInfo>(File.ReadAllText(@"bracket.json")) : new LadderInfo();
Child = manager = new LadderManager(ladder, teams);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
File.WriteAllText(@"bracket.json", JsonConvert.SerializeObject(manager.Info,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
}));
}
}
}
|
Add restrictions when creating the movie collection | using MoviesSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfMovieSystem.Views
{
/// <summary>
/// Interaction logic for InsertWindowView.xaml
/// </summary>
public partial class InsertWindowView : Window
{
public InsertWindowView()
{
InitializeComponent();
}
private void CreateButton_Click(object sender, RoutedEventArgs e)
{
using (MoviesSystemDbContext context = new MoviesSystemDbContext())
{
var firstName = FirstNameTextBox.Text;
var lastName = LastNameTextBox.Text;
var movies = MoviesTextBox.Text.Split(',');
var newActor = new Actor
{
FirstName = firstName,
LastName = lastName,
Movies = new List<Movie>()
};
foreach (var movie in movies)
{
newActor.Movies.Add(new Movie { Title = movie });
}
context.Actors.Add(newActor);
context.SaveChanges();
}
FirstNameTextBox.Text = "";
LastNameTextBox.Text = "";
MoviesTextBox.Text = "";
}
}
}
| using MoviesSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfMovieSystem.Views
{
/// <summary>
/// Interaction logic for InsertWindowView.xaml
/// </summary>
public partial class InsertWindowView : Window
{
public InsertWindowView()
{
InitializeComponent();
}
private void CreateButton_Click(object sender, RoutedEventArgs e)
{
using (MoviesSystemDbContext context = new MoviesSystemDbContext())
{
var firstName = FirstNameTextBox.Text;
var lastName = LastNameTextBox.Text;
var movies = MoviesTextBox.Text.Split(',');
var newActor = new Actor
{
FirstName = firstName,
LastName = lastName,
Movies = new List<Movie>()
};
foreach (var movie in movies)
{
newActor.Movies.Add(LoadOrCreateMovie(context, movie));
}
context.Actors.Add(newActor);
context.SaveChanges();
}
FirstNameTextBox.Text = "";
LastNameTextBox.Text = "";
MoviesTextBox.Text = "";
}
private static Movie LoadOrCreateMovie(MoviesSystemDbContext context, string movieTitle)
{
var movie = context.Movies
.FirstOrDefault(m => m.Title.ToLower() == movieTitle.ToLower());
if (movie == null)
{
movie = new Movie
{
Title = movieTitle
};
}
return movie;
}
}
}
|
Add documentation for show ids. | namespace TraktApiSharp.Objects.Get.Shows
{
using Basic;
public class TraktShowIds : TraktIds
{
}
}
| namespace TraktApiSharp.Objects.Get.Shows
{
using Basic;
/// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt show.</summary>
public class TraktShowIds : TraktIds
{
}
}
|
Update json.net to use new MIME, encoding and camelCase formatting | using System;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace DiplomContentSystem.Requests
{
public class RequestService
{
public async Task<Stream> SendRequest(object data)
{
using (var client = new HttpClient())
{
try
{
var content = new StringContent(JsonConvert.SerializeObject(data)
);
client.BaseAddress = new Uri("http://localhost:1337");
var response = await client.PostAsync("api/docx", content);
response.EnsureSuccessStatusCode(); // Throw in not success
return await response.Content.ReadAsStreamAsync();
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request exception: {e.Message}");
throw (e);
}
}
}
}
}
| using System;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace DiplomContentSystem.Requests
{
public class RequestService
{
public async Task<Stream> SendRequest(object data)
{
using (var client = new HttpClient())
{
try
{
var content = new StringContent(JsonConvert.SerializeObject(data,
new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}), System.Text.Encoding.UTF8, "application/json");
client.BaseAddress = new Uri("http://localhost:1337");
var response = await client.PostAsync("api/docx",content);
response.EnsureSuccessStatusCode(); // Throw in not success
return await response.Content.ReadAsStreamAsync();
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request exception: {e.Message}");
throw (e);
}
}
}
}
}
|
Make the implementation method private. | #region Copyright and license information
// Copyright 2010-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
namespace Edulinq
{
public static partial class Enumerable
{
public static IEnumerable<TResult> Repeat<TResult>(this TResult element, int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
return RepeatImpl(element, count);
}
public static IEnumerable<TResult> RepeatImpl<TResult>(TResult element, int count)
{
for (int i = 0; i < count; i++)
{
yield return element;
}
}
}
}
| #region Copyright and license information
// Copyright 2010-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
namespace Edulinq
{
public static partial class Enumerable
{
public static IEnumerable<TResult> Repeat<TResult>(this TResult element, int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
return RepeatImpl(element, count);
}
private static IEnumerable<TResult> RepeatImpl<TResult>(TResult element, int count)
{
for (int i = 0; i < count; i++)
{
yield return element;
}
}
}
}
|
Fix CommandConnection methods in Test | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mycroft;
using System.IO;
using System.Diagnostics;
namespace Mycroft.Tests
{
[TestClass]
public class TestCommandConnection
{
[TestMethod]
public async Task TestBodylessMessage(){
var s = new MemoryStream(Encoding.UTF8.GetBytes("6\nAPP_UP"));
var cmd = new CommandConnection(s);
var msg = await cmd.getCommandAsync();
Trace.WriteLine(msg);
if (msg != "APP_UP")
throw new Exception("Incorrect message!");
}
[TestMethod]
public async Task TestBodaciousMessage()
{
var input = "30\nMSG_BROADCAST {\"key\": \"value\"}";
var s = new MemoryStream(Encoding.UTF8.GetBytes(input));
var cmd = new CommandConnection(s);
var msg = await cmd.getCommandAsync();
Trace.WriteLine(msg);
Trace.WriteLine(input.Substring(3));
if (msg != input.Substring(3))
throw new Exception("Incorrect message!");
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mycroft;
using System.IO;
using System.Diagnostics;
namespace Mycroft.Tests
{
[TestClass]
public class TestCommandConnection
{
[TestMethod]
public async Task TestBodylessMessage(){
var s = new MemoryStream(Encoding.UTF8.GetBytes("6\nAPP_UP"));
var cmd = new CommandConnection(s);
var msg = await cmd.GetCommandAsync();
Trace.WriteLine(msg);
if (msg != "APP_UP")
throw new Exception("Incorrect message!");
}
[TestMethod]
public async Task TestBodaciousMessage()
{
var input = "30\nMSG_BROADCAST {\"key\": \"value\"}";
var s = new MemoryStream(Encoding.UTF8.GetBytes(input));
var cmd = new CommandConnection(s);
var msg = await cmd.GetCommandAsync();
Trace.WriteLine(msg);
Trace.WriteLine(input.Substring(3));
if (msg != input.Substring(3))
throw new Exception("Incorrect message!");
}
}
}
|
Fix deserialization of RegEx enabled properties | using System;
using Newtonsoft.Json;
namespace Archetype.Models
{
public class ArchetypePreValueProperty
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("remove")]
public bool Remove { get; set; }
[JsonProperty("collapse")]
public bool Collapse { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("helpText")]
public string HelpText { get; set; }
[JsonProperty("dataTypeGuid")]
public Guid DataTypeGuid { get; set; }
[JsonProperty("propertyEditorAlias")]
public string PropertyEditorAlias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("required")]
public bool Required { get; set; }
[JsonProperty("regEx")]
public bool RegEx { get; set; }
}
} | using System;
using Newtonsoft.Json;
namespace Archetype.Models
{
public class ArchetypePreValueProperty
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("remove")]
public bool Remove { get; set; }
[JsonProperty("collapse")]
public bool Collapse { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("helpText")]
public string HelpText { get; set; }
[JsonProperty("dataTypeGuid")]
public Guid DataTypeGuid { get; set; }
[JsonProperty("propertyEditorAlias")]
public string PropertyEditorAlias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("required")]
public bool Required { get; set; }
[JsonProperty("regEx")]
public string RegEx { get; set; }
}
} |
Add flush for mock channel | namespace FunctionalTestUtils
{
using System;
using System.Collections.Generic;
using Microsoft.ApplicationInsights.Channel;
public class BackTelemetryChannel : ITelemetryChannel
{
private IList<ITelemetry> buffer;
public BackTelemetryChannel()
{
this.buffer = new List<ITelemetry>();
}
public IList<ITelemetry> Buffer
{
get
{
return this.buffer;
}
}
public bool? DeveloperMode
{
get
{
return true;
}
set
{
}
}
public string EndpointAddress
{
get
{
return "https://dc.services.visualstudio.com/v2/track";
}
set
{
}
}
public void Dispose()
{
}
public void Flush()
{
throw new NotImplementedException();
}
public void Send(ITelemetry item)
{
this.buffer.Add(item);
}
}
} | namespace FunctionalTestUtils
{
using System;
using System.Collections.Generic;
using Microsoft.ApplicationInsights.Channel;
public class BackTelemetryChannel : ITelemetryChannel
{
private IList<ITelemetry> buffer;
public BackTelemetryChannel()
{
this.buffer = new List<ITelemetry>();
}
public IList<ITelemetry> Buffer
{
get
{
return this.buffer;
}
}
public bool? DeveloperMode
{
get
{
return true;
}
set
{
}
}
public string EndpointAddress
{
get
{
return "https://dc.services.visualstudio.com/v2/track";
}
set
{
}
}
public void Dispose()
{
}
public void Flush()
{
}
public void Send(ITelemetry item)
{
this.buffer.Add(item);
}
}
} |
Set nuget package version to 2.0.0-beta1 | using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")]
// NOTE: When changing this version, also update Cassette.MSBuild\Cassette.targets to match.
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyFileVersion("2.0.0.0")] | using System.Reflection;
[assembly: AssemblyCompany("Andrew Davey")]
[assembly: AssemblyProduct("Cassette")]
[assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")]
[assembly: AssemblyInformationalVersion("2.0.0-beta1")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyFileVersion("2.0.0.0")] |
Remove redundant configuration loading of diagnostics configuration | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace DotVVM.Framework.Diagnostics
{
public class DotvvmDiagnosticsConfiguration
{
public DotvvmDiagnosticsConfiguration()
{
LoadConfiguration();
}
private DiagnosticsServerConfiguration configuration;
public string DiagnosticsServerHostname
{
get
{
if (configuration == null)
LoadConfiguration();
return configuration.HostName;
}
}
public int? DiagnosticsServerPort
{
get
{
if (configuration == null)
LoadConfiguration();
return configuration?.Port;
}
}
private void LoadConfiguration()
{
try
{
var diagnosticsJson = File.ReadAllText(DiagnosticsServerConfiguration.DiagnosticsFilePath);
configuration = JsonConvert.DeserializeObject<DiagnosticsServerConfiguration>(diagnosticsJson);
}
catch
{
// ignored
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace DotVVM.Framework.Diagnostics
{
public class DotvvmDiagnosticsConfiguration
{
public DotvvmDiagnosticsConfiguration()
{
LoadConfiguration();
}
private DiagnosticsServerConfiguration configuration;
public string DiagnosticsServerHostname => configuration.HostName;
public int? DiagnosticsServerPort => configuration?.Port;
private void LoadConfiguration()
{
try
{
var diagnosticsJson = File.ReadAllText(DiagnosticsServerConfiguration.DiagnosticsFilePath);
configuration = JsonConvert.DeserializeObject<DiagnosticsServerConfiguration>(diagnosticsJson);
}
catch
{
// ignored
}
}
}
}
|
Exclude Cake files from line span mapping | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
namespace OmniSharp.Helpers
{
public static class LocationExtensions
{
public static QuickFix GetQuickFix(this Location location, OmniSharpWorkspace workspace)
{
if (!location.IsInSource)
throw new Exception("Location is not in the source tree");
var lineSpan = location.GetMappedLineSpan();
var path = lineSpan.Path;
var documents = workspace.GetDocuments(path);
var line = lineSpan.StartLinePosition.Line;
var text = location.SourceTree.GetText().Lines[line].ToString();
return new QuickFix
{
Text = text.Trim(),
FileName = path,
Line = line,
Column = lineSpan.HasMappedPath ? 0 : lineSpan.StartLinePosition.Character, // when a #line directive maps into a separate file, assume columns (0,0)
EndLine = lineSpan.EndLinePosition.Line,
EndColumn = lineSpan.HasMappedPath ? 0 : lineSpan.EndLinePosition.Character,
Projects = documents.Select(document => document.Project.Name).ToArray()
};
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
namespace OmniSharp.Helpers
{
public static class LocationExtensions
{
public static QuickFix GetQuickFix(this Location location, OmniSharpWorkspace workspace)
{
if (!location.IsInSource)
throw new Exception("Location is not in the source tree");
var lineSpan = Path.GetExtension(location.SourceTree.FilePath).Equals(".cake", StringComparison.OrdinalIgnoreCase)
? location.GetLineSpan()
: location.GetMappedLineSpan();
var path = lineSpan.Path;
var documents = workspace.GetDocuments(path);
var line = lineSpan.StartLinePosition.Line;
var text = location.SourceTree.GetText().Lines[line].ToString();
return new QuickFix
{
Text = text.Trim(),
FileName = path,
Line = line,
Column = lineSpan.HasMappedPath ? 0 : lineSpan.StartLinePosition.Character, // when a #line directive maps into a separate file, assume columns (0,0)
EndLine = lineSpan.EndLinePosition.Line,
EndColumn = lineSpan.HasMappedPath ? 0 : lineSpan.EndLinePosition.Character,
Projects = documents.Select(document => document.Project.Name).ToArray()
};
}
}
}
|
Improve way how fixture is bootup. | using System.Linq;
using Microsoft.Extensions.Configuration;
using Slp.Evi.Storage.Database;
using Slp.Evi.Storage.Database.Vendor.MsSql;
using Xunit;
namespace Slp.Evi.Test.System.Sparql.Vendor
{
public sealed class MsSqlSparqlFixture
: SparqlFixture
{
public MsSqlSparqlFixture()
{
// Prepare all databases beforehand
var bootUp = SparqlTestSuite.TestData.Select(x => x[0]).Cast<string>().Distinct()
.Select(x => base.GetStorage(x));
}
protected override ISqlDatabase GetSqlDb()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("database.json")
.AddEnvironmentVariables();
var config = builder.Build();
var connectionString = config.GetConnectionString("mssql");
return (new MsSqlDbFactory()).CreateSqlDb(connectionString, 30);
}
}
public class MsSqlSparqlTestSuite
: SparqlTestSuite, IClassFixture<MsSqlSparqlFixture>
{
public MsSqlSparqlTestSuite(MsSqlSparqlFixture fixture)
: base(fixture)
{
}
}
}
| using System.Linq;
using Microsoft.Extensions.Configuration;
using Slp.Evi.Storage.Database;
using Slp.Evi.Storage.Database.Vendor.MsSql;
using Xunit;
namespace Slp.Evi.Test.System.Sparql.Vendor
{
public sealed class MsSqlSparqlFixture
: SparqlFixture
{
public MsSqlSparqlFixture()
{
// Prepare all databases beforehand
var datasetsToBootup = SparqlTestSuite.TestData.Select(x => x[0]).Cast<string>().Distinct();
foreach (var dataset in datasetsToBootup)
{
GetStorage(dataset);
}
}
protected override ISqlDatabase GetSqlDb()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("database.json")
.AddEnvironmentVariables();
var config = builder.Build();
var connectionString = config.GetConnectionString("mssql");
return (new MsSqlDbFactory()).CreateSqlDb(connectionString, 30);
}
}
public class MsSqlSparqlTestSuite
: SparqlTestSuite, IClassFixture<MsSqlSparqlFixture>
{
public MsSqlSparqlTestSuite(MsSqlSparqlFixture fixture)
: base(fixture)
{
}
}
}
|
Fix compile error with namespace conflict | using System;
using UnityEngine;
namespace Alensia.Core.UI.Legacy
{
[Serializable]
public class CursorDefinition
{
public bool Visible;
public CursorLockMode LockMode;
public Vector2 Hotspot;
public Texture2D Image;
public void Apply()
{
Cursor.visible = Visible;
Cursor.lockState = LockMode;
Cursor.SetCursor(Image, Hotspot, CursorMode.Auto);
}
public static CursorDefinition Hidden = new CursorDefinition
{
Visible = false,
LockMode = CursorLockMode.Locked
};
public static CursorDefinition Default = new CursorDefinition
{
Visible = true,
LockMode = CursorLockMode.None
};
}
} | using System;
using UnityEngine;
namespace Alensia.Core.UI.Legacy
{
[Serializable]
public class CursorDefinition
{
public bool Visible;
public CursorLockMode LockMode;
public Vector2 Hotspot;
public Texture2D Image;
public void Apply()
{
UnityEngine.Cursor.visible = Visible;
UnityEngine.Cursor.lockState = LockMode;
UnityEngine.Cursor.SetCursor(Image, Hotspot, CursorMode.Auto);
}
public static CursorDefinition Hidden = new CursorDefinition
{
Visible = false,
LockMode = CursorLockMode.Locked
};
public static CursorDefinition Default = new CursorDefinition
{
Visible = true,
LockMode = CursorLockMode.None
};
}
} |
Change if to switch expression | using AsmResolver.PE.Debug.CodeView;
namespace AsmResolver.PE.Debug
{
/// <summary>
/// Provides a default implementation of the <see cref="IDebugDataReader"/> interface.
/// </summary>
public class DefaultDebugDataReader : IDebugDataReader
{
/// <inheritdoc />
public IDebugDataSegment ReadDebugData(PEReaderContext context, DebugDataType type,
IBinaryStreamReader reader)
{
if (type == DebugDataType.CodeView)
return CodeViewDataSegment.FromReader(reader);
return new CustomDebugDataSegment(type, DataSegment.FromReader(reader));
}
}
}
| using AsmResolver.PE.Debug.CodeView;
namespace AsmResolver.PE.Debug
{
/// <summary>
/// Provides a default implementation of the <see cref="IDebugDataReader"/> interface.
/// </summary>
public class DefaultDebugDataReader : IDebugDataReader
{
/// <inheritdoc />
public IDebugDataSegment ReadDebugData(PEReaderContext context, DebugDataType type,
IBinaryStreamReader reader)
{
return type switch
{
DebugDataType.CodeView => CodeViewDataSegment.FromReader(reader, context),
_ => new CustomDebugDataSegment(type, DataSegment.FromReader(reader))
};
}
}
}
|
Replace BinaryFormatter with JsonSerializer due to the former being obsoleted. Tests still fail. | using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SimpSim.NET
{
public class StateSaver
{
public virtual void SaveMemory(Memory memory, FileInfo file)
{
Save(memory, file);
}
public virtual Memory LoadMemory(FileInfo file)
{
return Load<Memory>(file);
}
public virtual void SaveRegisters(Registers registers, FileInfo file)
{
Save(registers, file);
}
public virtual Registers LoadRegisters(FileInfo file)
{
return Load<Registers>(file);
}
public virtual void SaveMachine(Machine machine, FileInfo file)
{
Save(machine, file);
}
public virtual Machine LoadMachine(FileInfo file)
{
return Load<Machine>(file);
}
private void Save(object @object, FileInfo file)
{
using (var fileStream = file.Create())
new BinaryFormatter().Serialize(fileStream, @object);
}
private T Load<T>(FileInfo file)
{
using (var fileStream = file.OpenRead())
return (T)new BinaryFormatter().Deserialize(fileStream);
}
}
}
| using System.IO;
using System.Text.Json;
namespace SimpSim.NET
{
public class StateSaver
{
public virtual void SaveMemory(Memory memory, FileInfo file)
{
Save(memory, file);
}
public virtual Memory LoadMemory(FileInfo file)
{
return Load<Memory>(file);
}
public virtual void SaveRegisters(Registers registers, FileInfo file)
{
Save(registers, file);
}
public virtual Registers LoadRegisters(FileInfo file)
{
return Load<Registers>(file);
}
public virtual void SaveMachine(Machine machine, FileInfo file)
{
Save(machine, file);
}
public virtual Machine LoadMachine(FileInfo file)
{
return Load<Machine>(file);
}
private void Save(object @object, FileInfo file)
{
using (var streamWriter = file.CreateText())
streamWriter.Write(JsonSerializer.Serialize(@object));
}
private T Load<T>(FileInfo file)
{
using (var streamReader = file.OpenText())
return JsonSerializer.Deserialize<T>(streamReader.ReadToEnd());
}
}
}
|
Check that the puzzle has not already been solved. | using UnityEngine;
using System.Collections;
public class DeskLampPuzzle : Puzzle
{
private bool isLampOn = false;
private bool hasLampBeenTurnedOn = false;
private InteractableSwitch lampSwitch;
// Use this for initialization
public override void Start ()
{
base.Start();
lampSwitch = GetComponent<InteractableSwitch>();
}
// Update is called once per frame
void Update () {
if (isLampOn != lampSwitch.turnedOn) {
isLampOn = lampSwitch.turnedOn;
hasLampBeenTurnedOn = true;
base.CompletePuzzle();
}
}
}
| using UnityEngine;
using System.Collections;
public class DeskLampPuzzle : Puzzle
{
private bool isLampOn = false;
private bool hasLampBeenTurnedOn = false;
private InteractableSwitch lampSwitch;
// Use this for initialization
public override void Start ()
{
base.Start();
lampSwitch = GetComponent<InteractableSwitch>();
}
// Update is called once per frame
void Update () {
if (isLampOn != lampSwitch.turnedOn) {
isLampOn = lampSwitch.turnedOn;
if (!hasLampBeenTurnedOn) {
base.CompletePuzzle();
}
hasLampBeenTurnedOn = true;
}
}
}
|
Fix order of games when calculating ratings | using System.Collections.Generic;
using System.Linq;
namespace EloWeb.Models
{
public class Games
{
public enum GamesSortOrder
{
MostRecentFirst = 1,
MostRecentLast = 2
}
private static List<Game> _games = new List<Game>();
public static void Initialise(IEnumerable<Game> gameEntities)
{
_games = gameEntities.ToList();
foreach(var game in _games)
Players.UpdateRatings(game);
}
public static void Add(Game game)
{
_games.Add(game);
}
public static IEnumerable<Game> All()
{
return _games.AsEnumerable();
}
public static IEnumerable<Game> MostRecent(int howMany, GamesSortOrder sortOrder)
{
var games = _games.AsEnumerable()
.OrderBy(g => g.WhenPlayed)
.Reverse()
.Take(howMany);
if (sortOrder == GamesSortOrder.MostRecentLast)
return games.Reverse();
return games;
}
public static IEnumerable<Game> GamesByPlayer(string name)
{
return _games.Where(game => game.Winner == name || game.Loser == name);
}
}
} | using System.Collections.Generic;
using System.Linq;
namespace EloWeb.Models
{
public class Games
{
public enum GamesSortOrder
{
MostRecentFirst = 1,
MostRecentLast = 2
}
private static List<Game> _games = new List<Game>();
public static void Initialise(IEnumerable<Game> gameEntities)
{
_games = gameEntities
.OrderBy(g => g.WhenPlayed)
.ToList();
foreach(var game in _games)
Players.UpdateRatings(game);
}
public static void Add(Game game)
{
_games.Add(game);
}
public static IEnumerable<Game> All()
{
return _games.AsEnumerable();
}
public static IEnumerable<Game> MostRecent(int howMany, GamesSortOrder sortOrder)
{
var games = _games.AsEnumerable()
.OrderBy(g => g.WhenPlayed)
.Reverse()
.Take(howMany);
if (sortOrder == GamesSortOrder.MostRecentLast)
return games.Reverse();
return games;
}
public static IEnumerable<Game> GamesByPlayer(string name)
{
return _games.Where(game => game.Winner == name || game.Loser == name);
}
}
} |
Fix issue with tagHelper that requries field or property to target for | @using System.Globalization
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options
@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultureItems = new SelectList(LocOptions.Value.SupportedUICultures, nameof(CultureInfo.Name), nameof(CultureInfo.DisplayName));
}
<div>
<form id="selectLanguage" asp-area="" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" class="form-horizontal" role="form">
@Localizer["Language:"]
<select name="culture" asp-for="@Context.GetCurrentCulture()" asp-items="cultureItems"></select>
<button>OK</button>
</form>
</div> | @using System.Globalization
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options
@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultureItems = new SelectList(LocOptions.Value.SupportedUICultures, nameof(CultureInfo.Name), nameof(CultureInfo.DisplayName));
var currentCulture = Context.GetCurrentCulture();
}
<div>
<form id="selectLanguage" asp-area="" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" class="form-horizontal" role="form">
@Localizer["Language:"]
<select name="culture" asp-for="@currentCulture" asp-items="cultureItems"></select>
<button>OK</button>
</form>
</div> |
Correct AssemblyProduct name from Security to Credentials | 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Security")]
[assembly: AssemblyTrademark("")]
// 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("ea66be4b-3391-49c4-96e8-b1b9044397b9")]
| 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Credentials")]
[assembly: AssemblyTrademark("")]
// 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("ea66be4b-3391-49c4-96e8-b1b9044397b9")]
|
Drop the Xamarin copyright after the CLA has been signed to contribute this back to Microsoft | 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("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyCopyright("Copyright © Xamarin Inc. 2013")]
[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("9453e5ef-4541-4491-941f-d20f4e39c967")]
// 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")]
| 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("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Mobile.Ext.iOS")]
[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("9453e5ef-4541-4491-941f-d20f4e39c967")]
// 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")]
|
Remove no longer needed display name fallback | using Arkivverket.Arkade.Core.Base.Addml.Processes;
using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Util;
namespace Arkivverket.Arkade.Core.Base
{
public static class ArkadeTestNameProvider
{
public static string GetDisplayName(IArkadeTest arkadeTest)
{
TestId testId = arkadeTest.GetId();
string testName = GetTestName(testId);
string displayName = testName != null
? string.Format(ArkadeTestDisplayNames.DisplayNameFormat, testId, testName)
: GetFallBackDisplayName(arkadeTest);
return displayName;
}
private static string GetTestName(TestId testId)
{
string resourceDisplayNameKey = testId.ToString().Replace('.', '_');
if (testId.Version.Equals("5.5"))
resourceDisplayNameKey = $"{resourceDisplayNameKey}v5_5";
return ArkadeTestDisplayNames.ResourceManager.GetString(resourceDisplayNameKey);
}
private static string GetFallBackDisplayName(IArkadeTest arkadeTest)
{
try
{
return ((AddmlProcess) arkadeTest).GetName(); // Process name
}
catch
{
return arkadeTest.GetType().Name; // Class name
}
}
}
}
| using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Util;
namespace Arkivverket.Arkade.Core.Base
{
public static class ArkadeTestNameProvider
{
public static string GetDisplayName(IArkadeTest arkadeTest)
{
TestId testId = arkadeTest.GetId();
string testName = GetTestName(testId);
return string.Format(ArkadeTestDisplayNames.DisplayNameFormat, testId, testName);
}
private static string GetTestName(TestId testId)
{
string resourceDisplayNameKey = testId.ToString().Replace('.', '_');
if (testId.Version.Equals("5.5"))
resourceDisplayNameKey = $"{resourceDisplayNameKey}v5_5";
return ArkadeTestDisplayNames.ResourceManager.GetString(resourceDisplayNameKey);
}
}
}
|
Add Scripts section and Bootstrap styling. | <!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/bootstrap.min.css")
</head>
<body>
<div>
@RenderBody()
</div>
@RenderSection("Scripts", false)
</body>
</html>
|
Use the correct namespace on the static content module. |
using System;
using System.IO;
using Mango;
//
// This the default StaticContentModule that comes with all Mango apps
// if you do not wish to serve any static content with Mango you can
// remove its route handler from <YourApp>.cs's constructor and delete
// this file.
//
// All Content placed on the Content/ folder should be handled by this
// module.
//
namespace AppNameFoo {
public class StaticContentModule : MangoModule {
public StaticContentModule ()
{
Get ("*", Content);
}
public static void Content (IMangoContext ctx)
{
string path = ctx.Request.LocalPath;
if (path.StartsWith ("/"))
path = path.Substring (1);
if (File.Exists (path)) {
ctx.Response.SendFile (path);
} else
ctx.Response.StatusCode = 404;
}
}
}
|
using System;
using System.IO;
using Mango;
//
// This the default StaticContentModule that comes with all Mango apps
// if you do not wish to serve any static content with Mango you can
// remove its route handler from <YourApp>.cs's constructor and delete
// this file.
//
// All Content placed on the Content/ folder should be handled by this
// module.
//
namespace $APPNAME {
public class StaticContentModule : MangoModule {
public StaticContentModule ()
{
Get ("*", Content);
}
public static void Content (IMangoContext ctx)
{
string path = ctx.Request.LocalPath;
if (path.StartsWith ("/"))
path = path.Substring (1);
if (File.Exists (path)) {
ctx.Response.SendFile (path);
} else
ctx.Response.StatusCode = 404;
}
}
}
|
Fix for several handlers for one message in projection group | using System;
using System.Collections.Generic;
namespace GridDomain.CQRS.Messaging.MessageRouting
{
public class ProjectionGroup: IProjectionGroup
{
private readonly IServiceLocator _locator;
readonly Dictionary<Type, List<Action<object>>> _handlers = new Dictionary<Type, List<Action<object>>>();
public ProjectionGroup(IServiceLocator locator)
{
_locator = locator;
}
public void Add<TMessage, THandler>(string correlationPropertyName ) where THandler : IHandler<TMessage>
{
var handler = _locator.Resolve<THandler>();
List<Action<object>> builderList;
if (!_handlers.TryGetValue(typeof (TMessage), out builderList))
{
builderList = new List<Action<object>>();
_handlers[typeof (TMessage)] = builderList;
}
builderList.Add(o => handler.Handle((TMessage) o));
_acceptMessages.Add(new MessageRoute(typeof(TMessage), correlationPropertyName));
}
public void Project(object message)
{
var msgType = message.GetType();
foreach(var handler in _handlers[msgType])
handler(message);
}
private readonly List<MessageRoute> _acceptMessages = new List<MessageRoute>();
public IReadOnlyCollection<MessageRoute> AcceptMessages => _acceptMessages;
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace GridDomain.CQRS.Messaging.MessageRouting
{
public class ProjectionGroup: IProjectionGroup
{
private readonly IServiceLocator _locator;
readonly Dictionary<Type, List<Action<object>>> _handlers = new Dictionary<Type, List<Action<object>>>();
public ProjectionGroup(IServiceLocator locator)
{
_locator = locator;
}
public void Add<TMessage, THandler>(string correlationPropertyName ) where THandler : IHandler<TMessage>
{
var handler = _locator.Resolve<THandler>();
List<Action<object>> builderList;
if (!_handlers.TryGetValue(typeof (TMessage), out builderList))
{
builderList = new List<Action<object>>();
_handlers[typeof (TMessage)] = builderList;
}
builderList.Add(o => handler.Handle((TMessage) o));
if(_acceptMessages.All(m => m.MessageType != typeof (TMessage)))
_acceptMessages.Add(new MessageRoute(typeof(TMessage), correlationPropertyName));
}
public void Project(object message)
{
var msgType = message.GetType();
foreach(var handler in _handlers[msgType])
handler(message);
}
private readonly List<MessageRoute> _acceptMessages = new List<MessageRoute>();
public IReadOnlyCollection<MessageRoute> AcceptMessages => _acceptMessages;
}
} |
Use await um command tests | using Lime.Protocol;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Takenet.MessagingHub.Client.Test
{
[TestFixture]
internal class MessagingHubClientTests_SendCommand : MessagingHubClientTestBase
{
[SetUp]
protected override void Setup()
{
base.Setup();
}
[TearDown]
protected override void TearDown()
{
base.TearDown();
}
[Test]
public async Task Send_Command_And_Receive_Response_With_Success()
{
//Arrange
var commandId = Guid.NewGuid();
var commandResponse = new Command
{
Id = commandId,
Status = CommandStatus.Success,
};
ClientChannel.ProcessCommandAsync(null, CancellationToken.None).ReturnsForAnyArgs(commandResponse);
await MessagingHubClient.StartAsync();
//Act
var result = MessagingHubClient.SendCommandAsync(new Command { Id = commandId }).Result;
//Assert
ClientChannel.ReceivedWithAnyArgs().ReceiveCommandAsync(CancellationToken.None);
result.ShouldNotBeNull();
result.Status.ShouldBe(CommandStatus.Success);
result.Id.ShouldBe(commandId);
}
[Test]
public void Send_Command_Without_Start_Should_Throw_Exception()
{
//Act / Assert
Should.ThrowAsync<InvalidOperationException>(async () => await MessagingHubClient.SendCommandAsync(Arg.Any<Command>()).ConfigureAwait(false)).Wait();
}
}
}
| using Lime.Protocol;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Takenet.MessagingHub.Client.Test
{
[TestFixture]
internal class MessagingHubClientTests_SendCommand : MessagingHubClientTestBase
{
[SetUp]
protected override void Setup()
{
base.Setup();
}
[TearDown]
protected override void TearDown()
{
base.TearDown();
}
[Test]
public async Task Send_Command_And_Receive_Response_With_Success()
{
//Arrange
var commandId = Guid.NewGuid();
var commandResponse = new Command
{
Id = commandId,
Status = CommandStatus.Success,
};
ClientChannel.ProcessCommandAsync(null, CancellationToken.None).ReturnsForAnyArgs(commandResponse);
await MessagingHubClient.StartAsync();
//Act
var result = await MessagingHubClient.SendCommandAsync(new Command { Id = commandId });
await Task.Delay(TIME_OUT);
//Assert
ClientChannel.ReceivedWithAnyArgs().ReceiveCommandAsync(CancellationToken.None);
result.ShouldNotBeNull();
result.Status.ShouldBe(CommandStatus.Success);
result.Id.ShouldBe(commandId);
}
[Test]
public void Send_Command_Without_Start_Should_Throw_Exception()
{
//Act / Assert
Should.ThrowAsync<InvalidOperationException>(async () => await MessagingHubClient.SendCommandAsync(Arg.Any<Command>()).ConfigureAwait(false)).Wait();
}
}
}
|
Fix beatmap potentially changing in test scene | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Timing;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneTimingScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneTimingScreen()
{
editorBeatmap = new EditorBeatmap(CreateBeatmap(new OsuRuleset().RulesetInfo));
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Child = new TimingScreen();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Timing;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneTimingScreen : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
public TestSceneTimingScreen()
{
editorBeatmap = new EditorBeatmap(CreateBeatmap(new OsuRuleset().RulesetInfo));
}
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(editorBeatmap.PlayableBeatmap);
Beatmap.Disabled = true;
Child = new TimingScreen();
}
protected override void Dispose(bool isDisposing)
{
Beatmap.Disabled = false;
base.Dispose(isDisposing);
}
}
}
|
Use the actual db data | using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Models
{
public class NavigationViewComponent : ViewComponent
{
private readonly Database db;
public Soldier Soldier { get; private set; }
public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);
public IEnumerable<Embed> NavItems
{
get
{
// TODO Only for nav items
// TODO Only for the logged in unit
yield return new Embed { Name = "PO Tracker" };
yield return new Embed { Name = "SUTA" };
//return
// db
// .Embeds
// .ToList();
}
}
public NavigationViewComponent(Database db)
{
this.db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);
return View(this);
}
}
} | using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Models
{
public class NavigationViewComponent : ViewComponent
{
private readonly Database db;
public Soldier Soldier { get; private set; }
public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);
public IEnumerable<Embed> NavItems
{
get
{
// TODO Only for nav items
// TODO Only for the logged in uni
return
db
.Embeds
.ToList();
}
}
public NavigationViewComponent(Database db)
{
this.db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);
return View(this);
}
}
} |
Make sure Jasper MessageId goes across the wire | using System.Text;
using Confluent.Kafka;
using Jasper.Transports;
namespace Jasper.ConfluentKafka
{
public class KafkaTransportProtocol<TKey, TVal> : ITransportProtocol<Message<TKey, TVal>>
{
public Message<TKey, TVal> WriteFromEnvelope(Envelope envelope) =>
new Message<TKey, TVal>
{
Headers = new Headers(),
Value = (TVal) envelope.Message
};
public Envelope ReadEnvelope(Message<TKey, TVal> message)
{
var env = new Envelope();
foreach (var header in message.Headers)
{
env.Headers.Add(header.Key, Encoding.UTF8.GetString(header.GetValueBytes()));
}
env.Message = message.Value;
return env;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Confluent.Kafka;
using Jasper.Transports;
namespace Jasper.ConfluentKafka
{
public class KafkaTransportProtocol<TKey, TVal> : ITransportProtocol<Message<TKey, TVal>>
{
private const string JasperMessageIdHeader = "Jasper_MessageId";
public Message<TKey, TVal> WriteFromEnvelope(Envelope envelope)
{
var message = new Message<TKey, TVal>
{
Headers = new Headers(),
Value = (TVal) envelope.Message
};
foreach (KeyValuePair<string, string> h in envelope.Headers)
{
Header header = new Header(h.Key, Encoding.UTF8.GetBytes(h.Value));
message.Headers.Add(header);
}
message.Headers.Add(JasperMessageIdHeader, Encoding.UTF8.GetBytes(envelope.Id.ToString()));
return message;
}
public Envelope ReadEnvelope(Message<TKey, TVal> message)
{
var env = new Envelope();
foreach (var header in message.Headers.Where(h => !h.Key.StartsWith("Jasper")))
{
env.Headers.Add(header.Key, Encoding.UTF8.GetString(header.GetValueBytes()));
}
var messageIdHeader = message.Headers.Single(h => h.Key.Equals(JasperMessageIdHeader));
env.Id = Guid.Parse(Encoding.UTF8.GetString(messageIdHeader.GetValueBytes()));
env.Message = message.Value;
return env;
}
}
}
|
Remove unused field for now to appease inspectcode | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
public class DownloadButton : BeatmapCardIconButton
{
private readonly APIBeatmapSet beatmapSet;
public DownloadButton(APIBeatmapSet beatmapSet)
{
this.beatmapSet = beatmapSet;
Icon.Icon = FontAwesome.Solid.FileDownload;
}
// TODO: implement behaviour
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
public class DownloadButton : BeatmapCardIconButton
{
public DownloadButton(APIBeatmapSet beatmapSet)
{
Icon.Icon = FontAwesome.Solid.FileDownload;
}
// TODO: implement behaviour
}
}
|
Update Lists migrations for Autoroute | using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
namespace Orchard.Lists {
public class Migrations : DataMigrationImpl {
public int Create() {
ContentDefinitionManager.AlterTypeDefinition("List",
cfg=>cfg
.WithPart("CommonPart")
.WithPart("RoutePart")
.WithPart("ContainerPart")
.WithPart("MenuPart")
.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2"))
.Creatable());
return 3;
}
public int UpdateFrom1() {
ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
return 3;
}
public int UpdateFrom2() {
ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
return 3;
}
}
}
| using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
namespace Orchard.Lists {
public class Migrations : DataMigrationImpl {
public int Create() {
ContentDefinitionManager.AlterTypeDefinition("List",
cfg=>cfg
.WithPart("CommonPart")
.WithPart("TitlePart")
.WithPart("AutoroutePart")
.WithPart("ContainerPart")
.WithPart("MenuPart")
.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2"))
.Creatable());
return 4;
}
public int UpdateFrom1() {
ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
return 3;
}
public int UpdateFrom2() {
ContentDefinitionManager.AlterTypeDefinition("List", cfg => cfg.WithPart("AdminMenuPart", p => p.WithSetting("AdminMenuPartTypeSettings.DefaultPosition", "2")));
return 3;
}
public int UpdateFrom3() {
// TODO: (PH:Autoroute) Copy paths, routes, etc.
ContentDefinitionManager.AlterTypeDefinition("List",
cfg => cfg
.RemovePart("RoutePart")
.WithPart("TitlePart")
.WithPart("AutoroutePart"));
return 4;
}
}
}
|
Add missing resource base class | using HalKit.Json;
using HalKit.Models.Response;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GogoKit.Models.Response
{
/// <summary>
/// A carrier (e.g. UPS) that will collect tickets that are to be delivered.
/// </summary>
/// <remarks>See http://developer.viagogo.net/#carrier</remarks>
[DataContract(Name = "carrier")]
public class Carrier
{
/// <summary>
/// The carrier identifier.
/// </summary>
[DataMember(Name = "id")]
public int? Id { get; set; }
/// <summary>
/// The name of the carrier.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// The windows available for ticket collection.
/// </summary>
[DataMember(Name = "pickup_windows")]
public IList<PickupWindow> PickupWindows { get; set; }
/// <summary>
/// Creates a new pickup for the ticket(s).
/// </summary>
/// <remarks>See http://developer.viagogo.net/#carriercreatepickup</remarks>
[Rel("carrier:createpickup")]
public Link CreatePickupLink { get; set; }
}
}
| using HalKit.Json;
using HalKit.Models.Response;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GogoKit.Models.Response
{
/// <summary>
/// A carrier (e.g. UPS) that will collect tickets that are to be delivered.
/// </summary>
/// <remarks>See http://developer.viagogo.net/#carrier</remarks>
[DataContract(Name = "carrier")]
public class Carrier : Resource
{
/// <summary>
/// The carrier identifier.
/// </summary>
[DataMember(Name = "id")]
public int? Id { get; set; }
/// <summary>
/// The name of the carrier.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// The windows available for ticket collection.
/// </summary>
[DataMember(Name = "pickup_windows")]
public IList<PickupWindow> PickupWindows { get; set; }
/// <summary>
/// Creates a new pickup for the ticket(s).
/// </summary>
/// <remarks>See http://developer.viagogo.net/#carriercreatepickup</remarks>
[Rel("carrier:createpickup")]
public Link CreatePickupLink { get; set; }
}
}
|
Create server side API for single multiple answer question | 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>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SaveChanges();
}
/// <summary>
/// Add option of single multiple answer question into SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public void AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
|
Fix Areas property is not deserialized, In the return value of the GetRichMenuListAsync method. | namespace Line.Messaging
{
/// <summary>
/// Rich menu response object.
/// https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object
/// </summary>
public class ResponseRichMenu : RichMenu
{
/// <summary>
/// Rich menu ID
/// </summary>
public string RichMenuId { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="richMenuId">
/// Rich menu ID
/// </param>
/// <param name="source">
/// Rich menu object
/// </param>
public ResponseRichMenu(string richMenuId, RichMenu source)
{
RichMenuId = richMenuId;
Size = source.Size;
Selected = source.Selected;
Name = source.Name;
ChatBarText = source.ChatBarText;
Areas = source.Areas;
}
internal static ResponseRichMenu CreateFrom(dynamic dynamicObject)
{
var menu = new RichMenu()
{
Name = (string)dynamicObject?.name,
Size = new ImagemapSize((int)(dynamicObject?.size?.width ?? 0), (int)(dynamicObject?.size?.height ?? 0)),
Selected = (bool)(dynamicObject?.selected ?? false),
ChatBarText = (string)dynamicObject?.chatBarText
};
return new ResponseRichMenu((string)dynamicObject?.richMenuId, menu);
}
}
}
| namespace Line.Messaging
{
/// <summary>
/// Rich menu response object.
/// https://developers.line.me/en/docs/messaging-api/reference/#rich-menu-response-object
/// </summary>
public class ResponseRichMenu : RichMenu
{
/// <summary>
/// Rich menu ID
/// </summary>
public string RichMenuId { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="richMenuId">
/// Rich menu ID
/// </param>
/// <param name="source">
/// Rich menu object
/// </param>
public ResponseRichMenu(string richMenuId, RichMenu source)
{
RichMenuId = richMenuId;
Size = source.Size;
Selected = source.Selected;
Name = source.Name;
ChatBarText = source.ChatBarText;
Areas = source.Areas;
}
internal static ResponseRichMenu CreateFrom(dynamic dynamicObject)
{
var menu = new RichMenu()
{
Name = (string)dynamicObject?.name,
Size = new ImagemapSize((int)(dynamicObject?.size?.width ?? 0), (int)(dynamicObject?.size?.height ?? 0)),
Selected = (bool)(dynamicObject?.selected ?? false),
ChatBarText = (string)dynamicObject?.chatBarText,
Areas = ActionArea.CreateFrom(dynamicObject?.areas)
};
return new ResponseRichMenu((string)dynamicObject?.richMenuId, menu);
}
}
}
|
Patch out the Tracescope for as far as possible when applicable. | using System;
namespace Staxel.Trace {
public struct TraceScope : IDisposable {
public TraceKey Key;
public TraceScope(TraceKey key) {
Key = key;
TraceRecorder.Enter(Key);
}
public void Dispose() {
TraceRecorder.Leave(Key);
}
}
}
| using System;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
namespace Staxel.Trace {
public struct TraceScope : IDisposable {
public TraceKey Key;
[TargetedPatchingOptOut("")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TraceScope(TraceKey key) {
Key = key;
TraceRecorder.Enter(Key);
}
[Conditional("TRACE")]
[TargetedPatchingOptOut("")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose() {
TraceRecorder.Leave(Key);
}
}
}
|
Use SetUp for tests, add test for clearing children | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Tests.Visual.Containers
{
public class TestSceneEnumerator : FrameworkTestScene
{
private Container parent;
[Test]
public void TestAddChildDuringEnumerationFails()
{
AddStep("create hierarchy", () => Child = parent = new Container
{
Child = new Container
{
}
});
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var child in parent)
{
}
}));
AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Add(new Container());
}
}));
}
[Test]
public void TestRemoveChildDuringEnumerationFails()
{
AddStep("create hierarchy", () => Child = parent = new Container
{
Child = new Container
{
}
});
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var child in parent)
{
}
}));
AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Remove(child, true);
}
}));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Tests.Visual.Containers
{
public class TestSceneEnumerator : FrameworkTestScene
{
private Container parent;
[SetUp]
public void SetUp()
{
Child = parent = new Container
{
Child = new Container
{
}
};
}
[Test]
public void TestEnumeratingNormally()
{
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var child in parent)
{
}
}));
}
[Test]
public void TestAddChildDuringEnumerationFails()
{
AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Add(new Container());
}
}));
}
[Test]
public void TestRemoveChildDuringEnumerationFails()
{
AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Remove(child, true);
}
}));
}
[Test]
public void TestClearDuringEnumerationFails()
{
AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Clear();
}
}));
}
}
}
|
Enable pattern helper as equivalent of component helper | using System;
using System.Collections.Generic;
using System.Linq;
using Veil;
using Veil.Helper;
namespace NitroNet.ViewEngine.TemplateHandler
{
internal class ComponentHelperHandler : IHelperHandler
{
private readonly INitroTemplateHandler _handler;
public ComponentHelperHandler(INitroTemplateHandler handler)
{
_handler = handler;
}
public bool IsSupported(string name)
{
return name.StartsWith("component", StringComparison.OrdinalIgnoreCase);
}
public void Evaluate(object model, RenderingContext context, IDictionary<string, string> parameters)
{
RenderingParameter template;
var firstParameter = parameters.FirstOrDefault();
if (string.IsNullOrEmpty(firstParameter.Value))
{
template = new RenderingParameter("name")
{
Value = firstParameter.Key.Trim('"', '\'')
};
}
else
{
template = CreateRenderingParameter("name", parameters);
}
var skin = CreateRenderingParameter("template", parameters);
var dataVariation = CreateRenderingParameter("data", parameters);
_handler.RenderComponent(template, skin, dataVariation, model, context);
}
private RenderingParameter CreateRenderingParameter(string name, IDictionary<string, string> parameters)
{
var renderingParameter = new RenderingParameter(name);
if (parameters.ContainsKey(renderingParameter.Name))
{
var value = parameters[renderingParameter.Name];
if (!value.StartsWith("\"") && !value.StartsWith("'"))
{
renderingParameter.IsDynamic = true;
}
renderingParameter.Value = value.Trim('"', '\'');
}
return renderingParameter;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Veil;
using Veil.Helper;
namespace NitroNet.ViewEngine.TemplateHandler
{
internal class ComponentHelperHandler : IHelperHandler
{
private readonly INitroTemplateHandler _handler;
public ComponentHelperHandler(INitroTemplateHandler handler)
{
_handler = handler;
}
public bool IsSupported(string name)
{
return name.StartsWith("component", StringComparison.OrdinalIgnoreCase) || name.StartsWith("pattern", StringComparison.OrdinalIgnoreCase);
}
public void Evaluate(object model, RenderingContext context, IDictionary<string, string> parameters)
{
RenderingParameter template;
var firstParameter = parameters.FirstOrDefault();
if (string.IsNullOrEmpty(firstParameter.Value))
{
template = new RenderingParameter("name")
{
Value = firstParameter.Key.Trim('"', '\'')
};
}
else
{
template = CreateRenderingParameter("name", parameters);
}
var skin = CreateRenderingParameter("template", parameters);
var dataVariation = CreateRenderingParameter("data", parameters);
_handler.RenderComponent(template, skin, dataVariation, model, context);
}
private RenderingParameter CreateRenderingParameter(string name, IDictionary<string, string> parameters)
{
var renderingParameter = new RenderingParameter(name);
if (parameters.ContainsKey(renderingParameter.Name))
{
var value = parameters[renderingParameter.Name];
if (!value.StartsWith("\"") && !value.StartsWith("'"))
{
renderingParameter.IsDynamic = true;
}
renderingParameter.Value = value.Trim('"', '\'');
}
return renderingParameter;
}
}
} |
Make the CackeKeyPrefix protected instead of Public | using System;
namespace NHibernate.Sessions.Operations
{
public abstract class AbstractCachedDatabaseQuery<T> : DatabaseOperation
{
protected abstract void ConfigureCache(CacheConfig cacheConfig);
protected abstract T QueryDatabase(ISessionManager sessionManager);
public virtual string CacheKeyPrefix
{
get { return GetType().FullName; }
}
protected T GetDatabaseResult(ISessionManager sessionManager, IDatabaseQueryCache databaseQueryCache = null)
{
var cacheConfig = CacheConfig.None;
ConfigureCache(cacheConfig);
if (databaseQueryCache == null || cacheConfig.AbsoluteDuration == TimeSpan.Zero)
return QueryDatabase(sessionManager);
return databaseQueryCache.Get(() => QueryDatabase(sessionManager), cacheConfig.BuildCacheKey(CacheKeyPrefix), cacheConfig.AbsoluteDuration, cacheConfig.CacheNulls);
}
}
} | using System;
namespace NHibernate.Sessions.Operations
{
public abstract class AbstractCachedDatabaseQuery<T> : DatabaseOperation
{
protected abstract void ConfigureCache(CacheConfig cacheConfig);
protected abstract T QueryDatabase(ISessionManager sessionManager);
protected virtual string CacheKeyPrefix
{
get { return GetType().FullName; }
}
protected T GetDatabaseResult(ISessionManager sessionManager, IDatabaseQueryCache databaseQueryCache = null)
{
var cacheConfig = CacheConfig.None;
ConfigureCache(cacheConfig);
if (databaseQueryCache == null || cacheConfig.AbsoluteDuration == TimeSpan.Zero)
return QueryDatabase(sessionManager);
return databaseQueryCache.Get(() => QueryDatabase(sessionManager), cacheConfig.BuildCacheKey(CacheKeyPrefix), cacheConfig.AbsoluteDuration, cacheConfig.CacheNulls);
}
}
} |
Create generic invoke method for RPC | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Specialized;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Core.EventDelegate
{
public class JsonRPCEventDelegate
{
private string RPCUrl;
public JsonRPCEventDelegate(int port)
{
this.RPCUrl = "http://localhost:" + port.ToString() + @"/";
}
public void Notify(string eventName, dynamic eventData)
{
WebRequest request = WebRequest.Create (this.RPCUrl);
request.ContentType = "application/json-rpc";
request.Method = "POST";
var values = new Dictionary<string, dynamic>(){
{"method", "notify"},
{"params", JsonConvert.SerializeObject(eventData)},
{"id", "null"}
};
var data = JsonConvert.SerializeObject(values);
byte[] byteArray = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Flush();
dataStream.Close();
WebResponse response = request.GetResponse();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Specialized;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Core.EventDelegate
{
public class JsonRPCEventDelegate
{
private string RPCUrl;
public JsonRPCEventDelegate(int port)
{
this.RPCUrl = "http://localhost:" + port.ToString() + @"/";
}
public WebResponse InvokeMethod(string method, string methodParams, string id)
{
WebRequest request = WebRequest.Create(this.RPCUrl);
request.ContentType = "application/json-rpc";
request.Method = "POST";
var values = new Dictionary<string, dynamic>(){
{"method", method},
{"params", methodParams},
{"id", id}
};
var data = JsonConvert.SerializeObject(values);
byte[] byteArray = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Flush();
dataStream.Close();
return request.GetResponse();
}
public void Notify(string eventName, dynamic eventData)
{
var response = this.InvokeMethod(
"notify",
JsonConvert.SerializeObject(
new Dictionary<string, dynamic>(){
{"eventData", eventData},
{"eventName", eventName}
}),
"null"
);
}
}
}
|
Fix uri mapper return invalid uri | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;
namespace Postolego {
public class PostolegoMapper : UriMapperBase {
public override Uri MapUri(Uri uri) {
var tempUri = HttpUtility.UrlDecode(uri.ToString());
if(tempUri.Contains("postolego:")) {
if(tempUri.Contains("authorize")) {
return new Uri("/Pages/SignInPage.xaml", UriKind.Relative);
} else {
return uri;
}
} else {
if((App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession == null || !(App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession.IsAuthenticated) {
return new Uri("/Pages/SignInPage.xaml", UriKind.Relative);
} else {
return uri;
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;
namespace Postolego {
public class PostolegoMapper : UriMapperBase {
public override Uri MapUri(Uri uri) {
var tempUri = HttpUtility.UrlDecode(uri.ToString());
if(tempUri.Contains("postolego:")) {
if(tempUri.Contains("authorize")) {
return new Uri("/Pages/SignInPage.xaml", UriKind.Relative);
}
}
if((App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession == null || !(App.Current.Resources["PostolegoData"] as PostolegoData).PocketSession.IsAuthenticated) {
return new Uri("/Pages/SignInPage.xaml", UriKind.Relative);
} else {
return uri;
}
}
}
}
|
Make sure date processing is accurate | using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
var span = birthDay - DateTime.Now;
if (span.Days < 0)
{
// If the supplied birthday has already happened, then find the next one that will occur.
int years = span.Days / -365;
span = span.Add(TimeSpan.FromDays((years + 1) * 365));
}
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
} | using System;
using Humanizer;
namespace Repack
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Usage: repack [date]");
Console.WriteLine("Prints how long it is until your birthday.");
Console.WriteLine("If you don't supply your birthday, it uses mine.");
DateTime birthDay = GetBirthday(args);
Console.WriteLine();
var span = GetSpan(birthDay);
Console.WriteLine("{0} until your birthday", span.Humanize());
}
private static TimeSpan GetSpan(DateTime birthDay)
{
var span = birthDay.Date - DateTime.Now.Date;
if (span.Days < 0)
{
// If the supplied birthday has already happened, then find the next one that will occur.
int years = span.Days / -365;
if (span.Days % 365 != 0) years++;
span = span.Add(TimeSpan.FromDays(years * 365));
}
return span;
}
private static DateTime GetBirthday(string[] args)
{
string day = null;
if (args != null && args.Length > 0)
{
day = args[0];
}
return GetBirthday(day);
}
private static DateTime GetBirthday(string day)
{
DateTime parsed;
if (DateTime.TryParse(day, out parsed))
{
return parsed;
}
else
{
return new DateTime(DateTime.Now.Year, 8, 20);
}
}
}
} |
Use at least a password that has char that needs to be encoded so that that is tested. | namespace MyCouch.IntegrationTests
{
internal static class TestClientFactory
{
internal static IClient CreateDefault()
{
return new Client("http://mycouchtester:1q2w3e4r@localhost:5984/" + TestConstants.TestDbName);
}
}
} | using System;
namespace MyCouch.IntegrationTests
{
internal static class TestClientFactory
{
internal static IClient CreateDefault()
{
return new Client("http://mycouchtester:" + Uri.EscapeDataString("p@ssword") + "@localhost:5984/" + TestConstants.TestDbName);
}
}
} |
Set id when adding new cinema | using System.Collections.Generic;
using Argentum.Core;
namespace SilverScreen.Domain
{
public class Cinema : AggregateBase<CinemaState>
{
public Cinema(CinemaState state) : base(state) { }
private Cinema(string name)
{
Apply(new CinemaAdded(name));
}
public static Cinema Add(string name)
{
return new Cinema(name);
}
}
public class CinemaState : State
{
public string Name { get; set; }
public List<Screen> Screens { get; set; }
public void When(CinemaAdded evt)
{
Name = evt.Name;
}
}
public class CinemaAdded : IEvent
{
public string Name { get; private set; }
public CinemaAdded(string name)
{
Name = name;
}
}
}
| using System;
using System.Collections.Generic;
using Argentum.Core;
namespace SilverScreen.Domain
{
public class Cinema : AggregateBase<CinemaState>
{
public Cinema(CinemaState state) : base(state) { }
private Cinema(Guid id, string name)
{
Apply(new CinemaAdded(id, name));
}
public static Cinema Add(string name)
{
return new Cinema(Guid.NewGuid(), name);
}
}
public class CinemaState : State
{
public string Name { get; set; }
public List<Screen> Screens { get; set; }
public void When(CinemaAdded evt)
{
Id = evt.Id;
Name = evt.Name;
}
}
public class CinemaAdded : IEvent
{
public Guid Id { get; private set; }
public string Name { get; private set; }
public CinemaAdded(Guid id, string name)
{
Id = id;
Name = name;
}
}
}
|
Change HttpContext variable to aspnet.HttpContext. | using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using SignalR.Abstractions;
namespace SignalR.AspNet
{
public class AspNetHost : HttpTaskAsyncHandler
{
private readonly PersistentConnection _connection;
private static readonly Lazy<bool> _hasAcceptWebSocketRequest =
new Lazy<bool>(() =>
{
return typeof(HttpContextBase).GetMethods().Any(m => m.Name.Equals("AcceptWebSocketRequest", StringComparison.OrdinalIgnoreCase));
});
public AspNetHost(PersistentConnection connection)
{
_connection = connection;
}
public override Task ProcessRequestAsync(HttpContextBase context)
{
var request = new AspNetRequest(context.Request);
var response = new AspNetResponse(context.Request, context.Response);
var hostContext = new HostContext(request, response, context.User);
// Determine if the client should bother to try a websocket request
hostContext.Items["supportsWebSockets"] = _hasAcceptWebSocketRequest.Value;
// Set the debugging flag
hostContext.Items["debugMode"] = context.IsDebuggingEnabled;
// Stick the context in here so transports or other asp.net specific logic can
// grab at it.
hostContext.Items["aspnet.context"] = context;
return _connection.ProcessRequestAsync(hostContext);
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using SignalR.Abstractions;
namespace SignalR.AspNet
{
public class AspNetHost : HttpTaskAsyncHandler
{
private readonly PersistentConnection _connection;
private static readonly Lazy<bool> _hasAcceptWebSocketRequest =
new Lazy<bool>(() =>
{
return typeof(HttpContextBase).GetMethods().Any(m => m.Name.Equals("AcceptWebSocketRequest", StringComparison.OrdinalIgnoreCase));
});
public AspNetHost(PersistentConnection connection)
{
_connection = connection;
}
public override Task ProcessRequestAsync(HttpContextBase context)
{
var request = new AspNetRequest(context.Request);
var response = new AspNetResponse(context.Request, context.Response);
var hostContext = new HostContext(request, response, context.User);
// Determine if the client should bother to try a websocket request
hostContext.Items["supportsWebSockets"] = _hasAcceptWebSocketRequest.Value;
// Set the debugging flag
hostContext.Items["debugMode"] = context.IsDebuggingEnabled;
// Stick the context in here so transports or other asp.net specific logic can
// grab at it.
hostContext.Items["aspnet.HttpContext"] = context;
return _connection.ProcessRequestAsync(hostContext);
}
}
}
|
Remove unnecessary room id from leave room request | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <returns>Whether the room could be joined.</returns>
Task<bool> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
Task LeaveRoom(long roomId);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <returns>Whether the room could be joined.</returns>
Task<bool> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
Task LeaveRoom();
}
}
|
Add some missing headers to generated .vcproj file. | ###############################################################################
# Copyright Lewis Baker
# Licenced under MIT license. See LICENSE.txt for details.
###############################################################################
import cake.path
from cake.tools import compiler, script, env, project
includes = cake.path.join(env.expand('${CPPCORO}'), 'include', 'cppcoro', [
'broken_promise.hpp',
'task.hpp',
'single_consumer_event.hpp',
])
sources = script.cwd([
'async_mutex.cpp',
])
extras = script.cwd([
'build.cake',
'use.cake',
])
buildDir = env.expand('${CPPCORO_BUILD}')
compiler.addIncludePath(env.expand('${CPPCORO}/include'))
objects = compiler.objects(
targetDir=env.expand('${CPPCORO_BUILD}/obj'),
sources=sources,
)
lib = compiler.library(
target=env.expand('${CPPCORO_LIB}/cppcoro'),
sources=objects,
)
vcproj = project.project(
target=env.expand('${CPPCORO_PROJECT}/cppcoro'),
items={
'Include': includes,
'Source': sources,
'': extras
},
output=lib,
)
script.setResult(
project=vcproj,
library=lib,
)
| ###############################################################################
# Copyright Lewis Baker
# Licenced under MIT license. See LICENSE.txt for details.
###############################################################################
import cake.path
from cake.tools import compiler, script, env, project
includes = cake.path.join(env.expand('${CPPCORO}'), 'include', 'cppcoro', [
'async_mutex.hpp',
'broken_promise.hpp',
'lazy_task.hpp',
'single_consumer_event.hpp',
'task.hpp',
])
sources = script.cwd([
'async_mutex.cpp',
])
extras = script.cwd([
'build.cake',
'use.cake',
])
buildDir = env.expand('${CPPCORO_BUILD}')
compiler.addIncludePath(env.expand('${CPPCORO}/include'))
objects = compiler.objects(
targetDir=env.expand('${CPPCORO_BUILD}/obj'),
sources=sources,
)
lib = compiler.library(
target=env.expand('${CPPCORO_LIB}/cppcoro'),
sources=objects,
)
vcproj = project.project(
target=env.expand('${CPPCORO_PROJECT}/cppcoro'),
items={
'Include': includes,
'Source': sources,
'': extras
},
output=lib,
)
script.setResult(
project=vcproj,
library=lib,
)
|
Update in line with other/unspecified switch | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Utils;
namespace osu.Game.Overlays.BeatmapListing
{
[HasOrderedElements]
public enum SearchLanguage
{
[Order(0)]
Any,
[Order(13)]
Other,
[Order(1)]
English,
[Order(6)]
Japanese,
[Order(2)]
Chinese,
[Order(12)]
Instrumental,
[Order(7)]
Korean,
[Order(3)]
French,
[Order(4)]
German,
[Order(9)]
Swedish,
[Order(8)]
Spanish,
[Order(5)]
Italian,
[Order(10)]
Russian,
[Order(11)]
Polish,
[Order(14)]
Unspecified
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Utils;
namespace osu.Game.Overlays.BeatmapListing
{
[HasOrderedElements]
public enum SearchLanguage
{
[Order(0)]
Any,
[Order(14)]
Unspecified,
[Order(1)]
English,
[Order(6)]
Japanese,
[Order(2)]
Chinese,
[Order(12)]
Instrumental,
[Order(7)]
Korean,
[Order(3)]
French,
[Order(4)]
German,
[Order(9)]
Swedish,
[Order(8)]
Spanish,
[Order(5)]
Italian,
[Order(10)]
Russian,
[Order(11)]
Polish,
[Order(13)]
Other
}
}
|
Increase fade-out time of hitobjects in the editor | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit
{
public class DrawableOsuEditRuleset : DrawableOsuRuleset
{
public DrawableOsuEditRuleset(Ruleset ruleset, IWorkingBeatmap beatmap, IReadOnlyList<Mod> mods)
: base(ruleset, beatmap, mods)
{
}
protected override Playfield CreatePlayfield() => new OsuPlayfieldNoCursor();
public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new OsuPlayfieldAdjustmentContainer { Size = Vector2.One };
private class OsuPlayfieldNoCursor : OsuPlayfield
{
protected override GameplayCursorContainer CreateCursor() => null;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.UI;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit
{
public class DrawableOsuEditRuleset : DrawableOsuRuleset
{
public DrawableOsuEditRuleset(Ruleset ruleset, IWorkingBeatmap beatmap, IReadOnlyList<Mod> mods)
: base(ruleset, beatmap, mods)
{
}
public override DrawableHitObject<OsuHitObject> CreateDrawableRepresentation(OsuHitObject h)
=> base.CreateDrawableRepresentation(h)?.With(d => d.ApplyCustomUpdateState += updateState);
private void updateState(DrawableHitObject hitObject, ArmedState state)
{
switch (state)
{
case ArmedState.Miss:
// Get the existing fade out transform
var existing = hitObject.Transforms.LastOrDefault(t => t.TargetMember == nameof(Alpha));
if (existing == null)
return;
using (hitObject.BeginAbsoluteSequence(existing.StartTime))
hitObject.FadeOut(500).Expire();
break;
}
}
protected override Playfield CreatePlayfield() => new OsuPlayfieldNoCursor();
public override PlayfieldAdjustmentContainer CreatePlayfieldAdjustmentContainer() => new OsuPlayfieldAdjustmentContainer { Size = Vector2.One };
private class OsuPlayfieldNoCursor : OsuPlayfield
{
protected override GameplayCursorContainer CreateCursor() => null;
}
}
}
|
Return type T for metadata scalars. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ecologylab.semantics.metadata.scalar
{
abstract public class MetadataScalarBase<T>
{
public T value;
public static String VALUE_FIELD_NAME = "value";
public MetadataScalarBase()
{
}
public MetadataScalarBase(object value)
{
this.value = (T) value;
}
public object Value
{
get { return value; }
set { this.value = (T)value; }
}
public override String ToString()
{
return value == null ? "null" : value.ToString();
}
}
public class MetadataString : MetadataScalarBase<String>
{
public MetadataString(){}
//The termvector stuff goes here !
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public MetadataString(object value):base(value)
{}
}
public class MetadataInteger : MetadataScalarBase<int>
{
public MetadataInteger(){}
public MetadataInteger(object value):base(value)
{}
}
public class MetadataParsedURL : MetadataScalarBase<Uri>
{
public MetadataParsedURL(){}
public MetadataParsedURL(object value):base(value)
{}
}
public class MetadataDate : MetadataScalarBase<DateTime>
{
public MetadataDate(){}
public MetadataDate(object value):base(value)
{}
}
public class MetadataStringBuilder : MetadataScalarBase<StringBuilder>
{
public MetadataStringBuilder(){}
public MetadataStringBuilder(object value):base(value)
{}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ecologylab.semantics.metadata.scalar
{
abstract public class MetadataScalarBase<T>
{
public T value;
public static String VALUE_FIELD_NAME = "value";
public MetadataScalarBase()
{
}
public MetadataScalarBase(object value)
{
this.value = (T) value;
}
public T Value
{
get { return value; }
set { this.value = (T)value; }
}
public override String ToString()
{
return value == null ? "null" : value.ToString();
}
}
public class MetadataString : MetadataScalarBase<String>
{
public MetadataString(){}
//The termvector stuff goes here !
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public MetadataString(object value):base(value)
{}
}
public class MetadataInteger : MetadataScalarBase<int>
{
public MetadataInteger(){}
public MetadataInteger(object value):base(value)
{}
}
public class MetadataParsedURL : MetadataScalarBase<Uri>
{
public MetadataParsedURL(){}
public MetadataParsedURL(object value):base(value)
{}
}
public class MetadataDate : MetadataScalarBase<DateTime>
{
public MetadataDate(){}
public MetadataDate(object value):base(value)
{}
}
public class MetadataStringBuilder : MetadataScalarBase<StringBuilder>
{
public MetadataStringBuilder(){}
public MetadataStringBuilder(object value):base(value)
{}
}
}
|
Change service's start mode to auto | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Configuration;
namespace SuperSocket.SocketService
{
[RunInstaller(true)]
public partial class SocketServiceInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public SocketServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Manual;
serviceInstaller.ServiceName = ConfigurationManager.AppSettings["ServiceName"];
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Configuration;
namespace SuperSocket.SocketService
{
[RunInstaller(true)]
public partial class SocketServiceInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public SocketServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = ConfigurationManager.AppSettings["ServiceName"];
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
} |
Fix SelectorTab crashing tests after a reload | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Online.Chat;
namespace osu.Game.Overlays.Chat.Tabs
{
public class ChannelSelectorTabItem : ChannelTabItem
{
public override bool IsRemovable => false;
public override bool IsSwitchable => false;
protected override bool IsBoldWhenActive => false;
public ChannelSelectorTabItem()
: base(new ChannelSelectorTabChannel())
{
Depth = float.MaxValue;
Width = 45;
Icon.Alpha = 0;
Text.Font = Text.Font.With(size: 45);
Text.Truncate = false;
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
BackgroundInactive = colour.Gray2;
BackgroundActive = colour.Gray3;
}
public class ChannelSelectorTabChannel : Channel
{
public ChannelSelectorTabChannel()
{
Name = "+";
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Online.Chat;
namespace osu.Game.Overlays.Chat.Tabs
{
public class ChannelSelectorTabItem : ChannelTabItem
{
public override bool IsRemovable => false;
public override bool IsSwitchable => false;
protected override bool IsBoldWhenActive => false;
public ChannelSelectorTabItem()
: base(new ChannelSelectorTabChannel())
{
Depth = float.MaxValue;
Width = 45;
Icon.Alpha = 0;
Text.Font = Text.Font.With(size: 45);
Text.Truncate = false;
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
BackgroundInactive = colour.Gray2;
BackgroundActive = colour.Gray3;
}
public class ChannelSelectorTabChannel : Channel
{
public ChannelSelectorTabChannel()
{
Name = "+";
Type = ChannelType.Temporary;
}
}
}
}
|
Fix a bug that causes the GetProviderNode to return null references. | using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Nohros.Configuration;
namespace Nohros.Data.Providers
{
public partial class SqlConnectionProvider : IConnectionProviderFactory
{
#region .ctor
/// <summary>
/// Constructor implied by the interface
/// <see cref="IConnectionProviderFactory"/>.
/// </summary>
SqlConnectionProvider() {
}
#endregion
#region IConnectionProviderFactory Members
/// <inheritdoc/>
IConnectionProvider IConnectionProviderFactory.CreateProvider(
IDictionary<string, string> options) {
string connection_string;
SqlConnectionStringBuilder builder;
if (options.TryGetValue(kConnectionStringOption, out connection_string)) {
builder = new SqlConnectionStringBuilder(connection_string);
} else {
string[] data = ProviderOptions.ThrowIfNotExists(options, kServerOption,
kLoginOption, kPasswordOption);
const int kServer = 0;
const int kLogin = 1;
const int kPassword = 2;
builder = new SqlConnectionStringBuilder {
DataSource = data[kServer],
UserID = data[kLogin],
Password = data[kPassword]
};
}
return new SqlConnectionProvider(builder.ConnectionString);
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Nohros.Configuration;
namespace Nohros.Data.Providers
{
public partial class SqlConnectionProvider : IConnectionProviderFactory
{
#region .ctor
/// <summary>
/// Constructor implied by the interface
/// <see cref="IConnectionProviderFactory"/>.
/// </summary>
SqlConnectionProvider() { }
#endregion
#region IConnectionProviderFactory Members
/// <inheritdoc/>
IConnectionProvider IConnectionProviderFactory.CreateProvider(
IDictionary<string, string> options) {
string connection_string;
SqlConnectionStringBuilder builder;
if (options.TryGetValue(kConnectionStringOption, out connection_string)) {
builder = new SqlConnectionStringBuilder(connection_string);
} else {
string[] data = ProviderOptions.ThrowIfNotExists(options, kServerOption,
kLoginOption, kPasswordOption);
const int kServer = 0;
const int kLogin = 1;
const int kPassword = 2;
builder = new SqlConnectionStringBuilder
{
DataSource = data[kServer],
UserID = data[kLogin],
Password = data[kPassword]
};
}
return new SqlConnectionProvider(builder.ConnectionString);
}
#endregion
}
}
|
Add more tests for NH-3408 | using System.Linq;
using NHibernate.Linq;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH3408
{
public class Fixture : BugTestCase
{
[Test]
public void ProjectAnonymousTypeWithArrayProperty()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var query = from c in session.Query<Country>()
select new { c.Picture, c.NationalHolidays };
Assert.DoesNotThrow(() => { query.ToList(); });
}
}
}
}
| using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH3408
{
public class Fixture : BugTestCase
{
[Test]
public void ProjectAnonymousTypeWithArrayProperty()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var query = from c in session.Query<Country>()
select new { c.Picture, c.NationalHolidays };
Assert.DoesNotThrow(() => { query.ToList(); });
}
}
[Test]
public void ProjectAnonymousTypeWithArrayPropertyWhenByteArrayContains()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var pictures = new List<byte[]>();
var query = from c in session.Query<Country>()
where pictures.Contains(c.Picture)
select new { c.Picture, c.NationalHolidays };
Assert.DoesNotThrow(() => { query.ToList(); });
}
}
[Test]
public void SelectBytePropertyWithArrayPropertyWhenByteArrayContains()
{
using (var session = OpenSession())
using (session.BeginTransaction())
{
var pictures = new List<byte[]>();
var query = from c in session.Query<Country>()
where pictures.Contains(c.Picture)
select c.Picture;
Assert.DoesNotThrow(() => { query.ToList(); });
}
}
}
}
|
Call the reflection method only if types don't match | using System;
using System.Linq;
using System.Reflection;
using WampSharp.Core.Serialization;
using WampSharp.Core.Utilities;
namespace WampSharp.V2.Core
{
public class WampObjectFormatter : IWampFormatter<object>
{
public static readonly IWampFormatter<object> Value = new WampObjectFormatter();
private WampObjectFormatter()
{
}
public bool CanConvert(object argument, Type type)
{
return type.IsInstanceOfType(argument);
}
public TTarget Deserialize<TTarget>(object message)
{
return (TTarget) message;
}
public object Deserialize(Type type, object message)
{
MethodInfo genericMethod =
Method.Get((WampObjectFormatter x) => x.Deserialize<object>(default(object)))
.GetGenericMethodDefinition();
// This actually only throws an exception if types don't match.
object converted =
genericMethod.MakeGenericMethod(type)
.Invoke(this, new object[] {message});
return converted;
}
public object Serialize(object value)
{
return value;
}
}
} | using System;
using System.Linq;
using System.Reflection;
using WampSharp.Core.Serialization;
using WampSharp.Core.Utilities;
namespace WampSharp.V2.Core
{
public class WampObjectFormatter : IWampFormatter<object>
{
public static readonly IWampFormatter<object> Value = new WampObjectFormatter();
private readonly MethodInfo mSerializeMethod =
Method.Get((WampObjectFormatter x) => x.Deserialize<object>(default(object)))
.GetGenericMethodDefinition();
private WampObjectFormatter()
{
}
public bool CanConvert(object argument, Type type)
{
return type.IsInstanceOfType(argument);
}
public TTarget Deserialize<TTarget>(object message)
{
return (TTarget) message;
}
public object Deserialize(Type type, object message)
{
if (type.IsInstanceOfType(message))
{
return message;
}
else
{
// This throws an exception if types don't match.
object converted =
mSerializeMethod.MakeGenericMethod(type)
.Invoke(this, new object[] {message});
return converted;
}
}
public object Serialize(object value)
{
return value;
}
}
} |
Set spinner tick start time to allow result reverting | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class DrawableSpinnerTick : DrawableOsuHitObject
{
private readonly BindableDouble bonusSampleVolume = new BindableDouble();
private bool hasBonusPoints;
/// <summary>
/// Whether this judgement has a bonus of 1,000 points additional to the numeric result.
/// Should be set when a spin occured after the spinner has completed.
/// </summary>
public bool HasBonusPoints
{
get => hasBonusPoints;
internal set
{
hasBonusPoints = value;
bonusSampleVolume.Value = value ? 1 : 0;
((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints = value;
}
}
public override bool DisplayResult => false;
public DrawableSpinnerTick(SpinnerTick spinnerTick)
: base(spinnerTick)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
Samples.AddAdjustment(AdjustableProperty.Volume, bonusSampleVolume);
}
public void TriggerResult(HitResult result) => ApplyResult(r => r.Type = result);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class DrawableSpinnerTick : DrawableOsuHitObject
{
private readonly BindableDouble bonusSampleVolume = new BindableDouble();
private bool hasBonusPoints;
/// <summary>
/// Whether this judgement has a bonus of 1,000 points additional to the numeric result.
/// Should be set when a spin occured after the spinner has completed.
/// </summary>
public bool HasBonusPoints
{
get => hasBonusPoints;
internal set
{
hasBonusPoints = value;
bonusSampleVolume.Value = value ? 1 : 0;
((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints = value;
}
}
public override bool DisplayResult => false;
public DrawableSpinnerTick(SpinnerTick spinnerTick)
: base(spinnerTick)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
Samples.AddAdjustment(AdjustableProperty.Volume, bonusSampleVolume);
}
public void TriggerResult(HitResult result)
{
HitObject.StartTime = Time.Current;
ApplyResult(r => r.Type = result);
}
}
}
|
Fix bug when root page would be shown a second time. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace XamarinFormsExtendedSplashPage
{
public partial class RootPage : ContentPage
{
public RootPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
Navigation.RemovePage(Navigation.NavigationStack[0]);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace XamarinFormsExtendedSplashPage
{
public partial class RootPage : ContentPage
{
public RootPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
var rootPage = Navigation.NavigationStack[0];
if (typeof (RootPage) == rootPage.GetType()) return;
Navigation.RemovePage(rootPage);
}
}
}
|
Make sure unit isn't null | @model Unit
<div>@Html.ActionLink(Model.Name, "Index", "Soldiers", new { unit = Model.Id })</div> | @model Unit
@if (Model != null)
{
<div>@Html.ActionLink(Model.Name, "Index", "Soldiers", new { unit = Model.Id })</div>
} |
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning. | //------------------------------------------------------------------------------
// <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")]
| //------------------------------------------------------------------------------
// <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")]
|
Add back a method that was removed bug is required by functional tests. | using System.Collections.Generic;
using System.Linq;
namespace NuGet.VisualStudio
{
public static class AggregatePackageSource
{
public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);
public static bool IsAggregate(this PackageSource source)
{
return source == Instance;
}
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregate(this IPackageSourceProvider provider)
{
return new[] { Instance }.Concat(provider.GetEnabledPackageSources());
}
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregateSmart(this IPackageSourceProvider provider)
{
var packageSources = provider.GetEnabledPackageSources().ToArray();
// If there's less than 2 package sources, don't add the Aggregate source because it will be exactly the same as the main source.
if (packageSources.Length <= 1)
{
return packageSources;
}
return new[] { Instance }.Concat(packageSources);
}
}
} | using System.Collections.Generic;
using System.Linq;
namespace NuGet.VisualStudio
{
public static class AggregatePackageSource
{
public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);
public static bool IsAggregate(this PackageSource source)
{
return source == Instance;
}
// IMPORTANT: do NOT remove this method. It is used by functional tests.
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregate()
{
return GetEnabledPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>());
}
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregate(this IPackageSourceProvider provider)
{
return new[] { Instance }.Concat(provider.GetEnabledPackageSources());
}
public static IEnumerable<PackageSource> GetEnabledPackageSourcesWithAggregateSmart(this IPackageSourceProvider provider)
{
var packageSources = provider.GetEnabledPackageSources().ToArray();
// If there's less than 2 package sources, don't add the Aggregate source because it will be exactly the same as the main source.
if (packageSources.Length <= 1)
{
return packageSources;
}
return new[] { Instance }.Concat(packageSources);
}
}
} |
Fix bug in DrawArea control | using System;
using System.Runtime.Serialization;
using SadConsole.UI.Controls;
using SadRogue.Primitives;
namespace SadConsole.UI.Themes
{
/// <summary>
/// A basic theme for a drawing surface that simply fills the surface based on the state.
/// </summary>
[DataContract]
public class DrawingAreaTheme : ThemeBase
{
/// <summary>
/// When true, only uses <see cref="ThemeStates.Normal"/> for drawing.
/// </summary>
[DataMember]
public bool UseNormalStateOnly { get; set; } = true;
/// <summary>
/// The current appearance based on the control state.
/// </summary>
public ColoredGlyph Appearance { get; protected set; }
/// <inheritdoc />
public override void UpdateAndDraw(ControlBase control, TimeSpan time)
{
if (!(control is DrawingArea drawingSurface)) return;
RefreshTheme(control.FindThemeColors(), control);
if (!UseNormalStateOnly)
Appearance = ControlThemeState.GetStateAppearance(control.State);
else
Appearance = ControlThemeState.Normal;
drawingSurface?.OnDraw(drawingSurface, time);
control.IsDirty = false;
}
/// <inheritdoc />
public override ThemeBase Clone() => new DrawingAreaTheme()
{
ControlThemeState = ControlThemeState.Clone(),
UseNormalStateOnly = UseNormalStateOnly
};
}
}
| using System;
using System.Runtime.Serialization;
using SadConsole.UI.Controls;
using SadRogue.Primitives;
namespace SadConsole.UI.Themes
{
/// <summary>
/// A basic theme for a drawing surface that simply fills the surface based on the state.
/// </summary>
[DataContract]
public class DrawingAreaTheme : ThemeBase
{
/// <summary>
/// When true, only uses <see cref="ThemeStates.Normal"/> for drawing.
/// </summary>
[DataMember]
public bool UseNormalStateOnly { get; set; } = true;
/// <summary>
/// The current appearance based on the control state.
/// </summary>
public ColoredGlyph Appearance { get; protected set; }
/// <inheritdoc />
public override void UpdateAndDraw(ControlBase control, TimeSpan time)
{
if (!(control is DrawingArea drawingSurface)) return;
RefreshTheme(control.FindThemeColors(), control);
if (!UseNormalStateOnly)
Appearance = ControlThemeState.GetStateAppearance(control.State);
else
Appearance = ControlThemeState.Normal;
drawingSurface.OnDraw?.Invoke(drawingSurface, time);
control.IsDirty = false;
}
/// <inheritdoc />
public override ThemeBase Clone() => new DrawingAreaTheme()
{
ControlThemeState = ControlThemeState.Clone(),
UseNormalStateOnly = UseNormalStateOnly
};
}
}
|
Remove CommentTest for jpeg test without metadata | using System;
using NUnit.Framework;
using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
using TagLib.Xmp;
using TagLib.Tests.Images.Validators;
namespace TagLib.Tests.Images
{
[TestFixture]
public class JpegNoMetadataTest
{
[Test]
public void Test ()
{
ImageTest.Run ("sample_no_metadata.jpg",
new JpegNoMetadataTestInvariantValidator (),
NoModificationValidator.Instance,
new NoModificationValidator (),
new CommentModificationValidator (),
new TagCommentModificationValidator (TagTypes.TiffIFD, false),
new TagCommentModificationValidator (TagTypes.XMP, false),
new TagKeywordsModificationValidator (TagTypes.XMP, false)
);
}
}
public class JpegNoMetadataTestInvariantValidator : IMetadataInvariantValidator
{
public void ValidateMetadataInvariants (Image.File file)
{
Assert.IsNotNull (file);
}
}
}
| using System;
using NUnit.Framework;
using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
using TagLib.Xmp;
using TagLib.Tests.Images.Validators;
namespace TagLib.Tests.Images
{
[TestFixture]
public class JpegNoMetadataTest
{
[Test]
public void Test ()
{
ImageTest.Run ("sample_no_metadata.jpg",
new JpegNoMetadataTestInvariantValidator (),
NoModificationValidator.Instance,
new NoModificationValidator (),
new TagCommentModificationValidator (TagTypes.TiffIFD, false),
new TagCommentModificationValidator (TagTypes.XMP, false),
new TagKeywordsModificationValidator (TagTypes.XMP, false)
);
}
}
public class JpegNoMetadataTestInvariantValidator : IMetadataInvariantValidator
{
public void ValidateMetadataInvariants (Image.File file)
{
Assert.IsNotNull (file);
}
}
}
|
Convert size parameter from int to long | using Azure.Test.PerfStress;
using CommandLine;
namespace Azure.Storage.Blobs.PerfStress.Core
{
public class SizeOptions : PerfStressOptions
{
[Option('s', "size", Default = 10 * 1024, HelpText = "Size of message (in bytes)")]
public int Size { get; set; }
}
}
| using Azure.Test.PerfStress;
using CommandLine;
namespace Azure.Storage.Blobs.PerfStress.Core
{
public class SizeOptions : PerfStressOptions
{
[Option('s', "size", Default = 10 * 1024, HelpText = "Size of message (in bytes)")]
public long Size { get; set; }
}
}
|
Remove unused RoleProvider setting from authentication configuration | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Bonobo.Git.Server.Configuration
{
public class AuthenticationSettings
{
public static string MembershipService { get; private set; }
public static string RoleProvider { get; private set; }
static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
RoleProvider = ConfigurationManager.AppSettings["RoleProvider"];
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Bonobo.Git.Server.Configuration
{
public class AuthenticationSettings
{
public static string MembershipService { get; private set; }
static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
}
}
} |
Fix access denied issue when access process information in RemoteProcessService | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketServiceCore.Command;
using System.Diagnostics;
namespace RemoteProcessService.Command
{
public class LIST : ICommand<RemotePrcessSession>
{
#region ICommand<RemotePrcessSession> Members
public void Execute(RemotePrcessSession session, CommandInfo commandData)
{
Process[] processes;
string firstParam = commandData.GetFirstParam();
if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
processes = Process.GetProcesses();
else
processes = Process.GetProcesses().Where(p =>
p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in processes)
{
sb.AppendLine(string.Format("{0}\t{1}\t{2}", p.ProcessName, p.Id, p.TotalProcessorTime));
}
sb.AppendLine();
session.SendResponse(sb.ToString());
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketServiceCore.Command;
using System.Diagnostics;
namespace RemoteProcessService.Command
{
public class LIST : ICommand<RemotePrcessSession>
{
#region ICommand<RemotePrcessSession> Members
public void Execute(RemotePrcessSession session, CommandInfo commandData)
{
Process[] processes;
string firstParam = commandData.GetFirstParam();
if (string.IsNullOrEmpty(firstParam) || firstParam == "*")
processes = Process.GetProcesses();
else
processes = Process.GetProcesses().Where(p =>
p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
StringBuilder sb = new StringBuilder();
foreach (var p in processes)
{
sb.AppendLine(string.Format("{0}\t{1}", p.ProcessName, p.Id));
}
sb.AppendLine();
session.SendResponse(sb.ToString());
}
#endregion
}
}
|
Fix code using old style code-gen factory classes - use GrainClient.GrainFactory | using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using GPSTracker.Common;
using GPSTracker.GrainInterface;
namespace GPSTracker.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> Test()
{
var rand = new Random();
var grain = DeviceGrainFactory.GetGrain(1);
await grain.ProcessMessage(new DeviceMessage(rand.Next(-90, 90), rand.Next(-180, 180), 1, 1, DateTime.UtcNow));
return Content("Sent");
}
}
}
| using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using GPSTracker.Common;
using GPSTracker.GrainInterface;
using Orleans;
namespace GPSTracker.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> Test()
{
var rand = new Random();
IDeviceGrain grain = GrainClient.GrainFactory.GetGrain<IDeviceGrain>(1);
await grain.ProcessMessage(new DeviceMessage(rand.Next(-90, 90), rand.Next(-180, 180), 1, 1, DateTime.UtcNow));
return Content("Sent");
}
}
}
|
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. | using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.DomainServices")]
[assembly: AssemblyDescription("")]
| using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.DomainServices")]
|
Fix behaviour from calling create multiple times | using UnityEngine;
using MsgPack;
[RequireComponent(typeof (AgentController))]
[RequireComponent(typeof (AgentSensor))]
public class AgentBehaviour : MonoBehaviour {
private LISClient client = new LISClient("myagent");
private AgentController controller;
private AgentSensor sensor;
private MsgPack.CompiledPacker packer = new MsgPack.CompiledPacker();
bool created = false;
public float Reward = 0.0F;
void OnCollisionEnter(Collision col) {
if(col.gameObject.tag == "Reward") {
NotificationCenter.DefaultCenter.PostNotification(this, "OnRewardCollision");
}
}
byte[] GenerateMessage() {
Message msg = new Message();
msg.reward = PlayerPrefs.GetFloat("Reward");
msg.image = sensor.GetRgbImages();
msg.depth = sensor.GetDepthImages();
return packer.Pack(msg);
}
void Start () {
controller = GetComponent<AgentController>();
sensor = GetComponent<AgentSensor>();
}
void Update () {
if(!created) {
client.Create(GenerateMessage());
created = true;
} else {
if(!client.Calling) {
client.Step(GenerateMessage());
}
if(client.HasAction) {
string action = client.GetAction();
controller.PerformAction(action);
}
}
}
}
| using UnityEngine;
using MsgPack;
[RequireComponent(typeof (AgentController))]
[RequireComponent(typeof (AgentSensor))]
public class AgentBehaviour : MonoBehaviour {
private LISClient client = new LISClient("myagent");
private AgentController controller;
private AgentSensor sensor;
private MsgPack.CompiledPacker packer = new MsgPack.CompiledPacker();
bool created = false;
public float Reward = 0.0F;
void OnCollisionEnter(Collision col) {
if(col.gameObject.tag == "Reward") {
NotificationCenter.DefaultCenter.PostNotification(this, "OnRewardCollision");
}
}
byte[] GenerateMessage() {
Message msg = new Message();
msg.reward = PlayerPrefs.GetFloat("Reward");
msg.image = sensor.GetRgbImages();
msg.depth = sensor.GetDepthImages();
return packer.Pack(msg);
}
void Start () {
controller = GetComponent<AgentController>();
sensor = GetComponent<AgentSensor>();
}
void Update () {
if(!created) {
if(!client.Calling) {
client.Create(GenerateMessage());
created = true;
}
} else {
if(!client.Calling) {
client.Step(GenerateMessage());
}
if(client.HasAction) {
string action = client.GetAction();
controller.PerformAction(action);
}
}
}
}
|
Fix failing at beginning of map | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
internal class CatchScoreProcessor : ScoreProcessor<CatchBaseHit, CatchJudgement>
{
public CatchScoreProcessor()
{
}
public CatchScoreProcessor(HitRenderer<CatchBaseHit, CatchJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void OnNewJudgement(CatchJudgement judgement)
{
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Catch.Scoring
{
internal class CatchScoreProcessor : ScoreProcessor<CatchBaseHit, CatchJudgement>
{
public CatchScoreProcessor()
{
}
public CatchScoreProcessor(HitRenderer<CatchBaseHit, CatchJudgement> hitRenderer)
: base(hitRenderer)
{
}
protected override void Reset()
{
base.Reset();
Health.Value = 1;
Accuracy.Value = 1;
}
protected override void OnNewJudgement(CatchJudgement judgement)
{
}
}
}
|
Improve help texts for CLI file generation | using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;
namespace Arkivverket.Arkade.CLI.Options
{
[Verb("generate", HelpText = "Generate a specified file. Run this command followed by '--help' for more detailed info.")]
public class GenerateOptions : OutputOptions
{
[Option('m', "metadata-example", Group = "file-type",
HelpText = "Generate json file with example metadata.")]
public bool GenerateMetadataExampleFile { get; set; }
[Option('s', "noark5-test-selection", Group = "file-type",
HelpText = "Generate text file with list of noark5 tests.")]
public bool GenerateNoark5TestSelectionFile { get; set; }
[Usage(ApplicationAlias = "arkade")]
public static IEnumerable<Example> Examples
{
get
{
yield return new Example("Generate json file with metadata example",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateMetadataExampleFile = true
});
yield return new Example("Generate text file with list of noark5-test",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateNoark5TestSelectionFile = true
});
yield return new Example("Generate both files",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateMetadataExampleFile = true,
GenerateNoark5TestSelectionFile = true
});
}
}
}
}
| using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;
namespace Arkivverket.Arkade.CLI.Options
{
[Verb("generate", HelpText = "Generate a specified file. Run this command followed by '--help' for more detailed info.")]
public class GenerateOptions : OutputOptions
{
[Option('m', "metadata-example", Group = "file-type",
HelpText = "Generate a metadata example file.")]
public bool GenerateMetadataExampleFile { get; set; }
[Option('s', "noark5-test-selection", Group = "file-type",
HelpText = "Generate a Noark 5 test selection file.")]
public bool GenerateNoark5TestSelectionFile { get; set; }
[Usage(ApplicationAlias = "arkade")]
public static IEnumerable<Example> Examples
{
get
{
yield return new Example("Generate a metadata example file",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateMetadataExampleFile = true
});
yield return new Example("Generate a Noark 5 test selection file",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateNoark5TestSelectionFile = true
});
yield return new Example("Generate a metadata example file and a Noark 5 test selection file",
new GenerateOptions
{
OutputDirectory = "outputDirectory",
GenerateMetadataExampleFile = true,
GenerateNoark5TestSelectionFile = true
});
}
}
}
}
|
Update Informational Version to 1.1.0-pre2 | using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany( "AvantiPoint, LLC" )]
[assembly: AssemblyCopyright( "Copyright © Dan Siegel 2016" )]
[assembly: NeutralResourcesLanguage( "en" )]
[assembly: AssemblyVersion( "1.1.0.0" )]
[assembly: AssemblyFileVersion( "1.1.0.0" )]
[assembly: AssemblyInformationalVersion( "1.1.0-pre1" )] | using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany( "AvantiPoint, LLC" )]
[assembly: AssemblyCopyright( "Copyright © Dan Siegel 2016" )]
[assembly: NeutralResourcesLanguage( "en" )]
[assembly: AssemblyVersion( "1.1.0.0" )]
[assembly: AssemblyFileVersion( "1.1.0.0" )]
[assembly: AssemblyInformationalVersion( "1.1.0-pre2" )] |
Update food box item with fibre | using System.Windows.Controls;
using System.Windows.Forms;
namespace food_tracker {
public class FoodBoxItem : ListBoxItem {
public int calories { get; set; }
public int fats { get; set; }
public int saturatedFat { get; set; }
public int carbohydrates { get; set; }
public int sugar { get; set; }
public int protein { get; set; }
public int salt { get; set; }
public string name { get; set; }
public FoodBoxItem() : base() { }
public FoodBoxItem(int cals, int fats, int satFat, int carbs, int sugars, int protein, int salt, string name) {
this.name = name;
this.calories = cals;
this.fats = fats;
this.salt = salt;
this.saturatedFat = satFat;
this.carbohydrates = carbs;
this.sugar = sugars;
this.protein = protein;
}
public override string ToString() {
return name;
}
}
}
| using System.Windows.Controls;
using System.Windows.Forms;
namespace food_tracker {
public class FoodBoxItem : ListBoxItem {
public int calories { get; set; }
public int fats { get; set; }
public int saturatedFat { get; set; }
public int carbohydrates { get; set; }
public int sugar { get; set; }
public int protein { get; set; }
public int salt { get; set; }
public int fibre { get; set; }
public string name { get; set; }
public FoodBoxItem() : base() { }
public FoodBoxItem(int cals, int fats, int satFat, int carbs, int sugars, int protein, int salt, int fibre, string name) {
this.name = name;
this.calories = cals;
this.fats = fats;
this.salt = salt;
this.saturatedFat = satFat;
this.carbohydrates = carbs;
this.sugar = sugars;
this.protein = protein;
this.fibre = fibre;
}
public override string ToString() {
return name;
}
}
}
|
Update ExitCode to long. This is because Windows Containers sometimes exit with 3221225725 | using System;
// ReSharper disable InconsistentNaming
namespace Ductus.FluentDocker.Model.Containers
{
public sealed class ContainerState
{
public string Status { get; set; }
public bool Running { get; set; }
public bool Paused { get; set; }
public bool Restarting { get; set; }
public bool OOMKilled { get; set; }
public bool Dead { get; set; }
public int Pid { get; set; }
public int ExitCode { get; set; }
public string Error { get; set; }
public DateTime StartedAt { get; set; }
public DateTime FinishedAt { get; set; }
public Health Health { get; set; }
}
} | using System;
// ReSharper disable InconsistentNaming
namespace Ductus.FluentDocker.Model.Containers
{
public sealed class ContainerState
{
public string Status { get; set; }
public bool Running { get; set; }
public bool Paused { get; set; }
public bool Restarting { get; set; }
public bool OOMKilled { get; set; }
public bool Dead { get; set; }
public int Pid { get; set; }
public long ExitCode { get; set; }
public string Error { get; set; }
public DateTime StartedAt { get; set; }
public DateTime FinishedAt { get; set; }
public Health Health { get; set; }
}
} |
Make WalletViewModel private and WalletViewModelBase protected. | using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.ViewModels
{
public abstract class WasabiWalletDocumentTabViewModel : WasabiDocumentTabViewModel
{
protected WasabiWalletDocumentTabViewModel(string title, WalletViewModelBase walletViewModel)
: base(title)
{
WalletViewModel = walletViewModel;
}
public WalletViewModelBase WalletViewModel { get; }
public Wallet Wallet => WalletViewModel.Wallet;
}
}
| using ReactiveUI;
using Splat;
using System;
using System.Reactive.Linq;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.ViewModels
{
public abstract class WasabiWalletDocumentTabViewModel : WasabiDocumentTabViewModel
{
protected WasabiWalletDocumentTabViewModel(string title, WalletViewModelBase walletViewModel)
: base(title)
{
WalletViewModel = walletViewModel;
}
public void ExpandWallet ()
{
WalletViewModel.IsExpanded = true;
}
private WalletViewModelBase WalletViewModel { get; }
protected Wallet Wallet => WalletViewModel.Wallet;
}
}
|
Fix typo and use <see langword=""/>. | using System;
namespace Microsoft.TeamFoundation.Authentication
{
public interface ITokenStore
{
/// <summary>
/// Deletes a <see cref="Token"/> from the underlying storage.
/// </summary>
/// <param name="targetUri">The key identifying which token is being deleted.</param>
void DeleteToken(Uri targetUri);
/// <summary>
/// Reads a <see cref="Token"/> from the underlying storage.
/// </summary>
/// <param name="targetUri">The key identifying which token to read.</param>
/// <param name="token">A <see cref="Token"/> if successful; otherwise false.</param>
/// <returns>True if successful; otherwise false.</returns>
bool ReadToken(Uri targetUri, out Token token);
/// <summary>
/// Writes a <see cref="Token"/> to the underlying storage.
/// </summary>
/// <param name="targetUri">
/// Unique identifier for the token, used when reading back from storage.
/// </param>
/// <param name="token">The <see cref="Token"/> to writen.</param>
void WriteToken(Uri targetUri, Token token);
}
}
| using System;
namespace Microsoft.TeamFoundation.Authentication
{
public interface ITokenStore
{
/// <summary>
/// Deletes a <see cref="Token"/> from the underlying storage.
/// </summary>
/// <param name="targetUri">The key identifying which token is being deleted.</param>
void DeleteToken(Uri targetUri);
/// <summary>
/// Reads a <see cref="Token"/> from the underlying storage.
/// </summary>
/// <param name="targetUri">The key identifying which token to read.</param>
/// <param name="token">A <see cref="Token"/> if successful; otherwise <see langword="null"/>.</param>
/// <returns><see langword="true"/> if successful; otherwise <see langword="false"/>.</returns>
bool ReadToken(Uri targetUri, out Token token);
/// <summary>
/// Writes a <see cref="Token"/> to the underlying storage.
/// </summary>
/// <param name="targetUri">
/// Unique identifier for the token, used when reading back from storage.
/// </param>
/// <param name="token">The <see cref="Token"/> to be written.</param>
void WriteToken(Uri targetUri, Token token);
}
}
|
Add information about http status codes in the reporting API |
@{
ViewBag.Title = "Reporting API - Introduction";
}
<article class="article">
<h1>Introduction to the Reporting API</h1>
<p>
The Reporting API is based on standard web technologies, web services and XML.
Use the Reporting API to extract from TimeLog into intranets, extranets,
business reporting tools, applications etc.
</p>
<p>
The idea behind the Reporting API is to give access to as much of the TimeLog
Project data models as possible in a easy to use XML format. The origin of the
API goes way back in the history of TimeLog, so we will extend on it on
a per-request basis for new fields and data types. Please get in touch, if you
think we lack some information in the various methods.
</p>
<p>
Be aware that no security policies on user access will be applied to any of the
methods in the Reporting API. The Reporting API is for flat data extractions.
Take care to apply your own policies if you are exposing the data in a data
warehouse or other business intelligence tools.
</p>
</article> |
@{
ViewBag.Title = "Reporting API - Introduction";
}
<article class="article">
<h1>Introduction to the Reporting API</h1>
<p>
The Reporting API is based on standard web technologies, web services and XML.
Use the Reporting API to extract from TimeLog into intranets, extranets,
business reporting tools, applications etc.
</p>
<p>
The idea behind the Reporting API is to give access to as much of the TimeLog
Project data models as possible in a easy to use XML format. The origin of the
API goes way back in the history of TimeLog, so we will extend on it on
a per-request basis for new fields and data types. Please get in touch, if you
think we lack some information in the various methods.
</p>
<p>
Be aware that no security policies on user access will be applied to any of the
methods in the Reporting API. The Reporting API is for flat data extractions.
Take care to apply your own policies if you are exposing the data in a data
warehouse or other business intelligence tools.
</p>
<h2 id="status-codes">Status codes</h2>
<p>
The reporting will (starting from end May 2021) return specific HTTP
status codes related to the result. The result body will remain unchanged and will
in many cases provide additional information. Possible status responses:
</p>
<ul class="arrows">
<li>200 OK - request successful</li>
<li>204 No Content - the result of the request is empty</li>
<li>400 Bad Request - covers both issues with input parameters, but possibly also internal errors</li>
<li>401 Unauthorized - the Site ID, API ID and API password combination is invalid</li>
</ul>
</article> |
Add ContentType of the response. | using System.Net;
namespace LtiLibrary.NetCore.Profiles
{
public class ToolConsumerProfileResponse
{
public HttpStatusCode StatusCode { get; set; }
public ToolConsumerProfile ToolConsumerProfile { get; set; }
}
}
| using System.Net;
namespace LtiLibrary.NetCore.Profiles
{
public class ToolConsumerProfileResponse
{
public string ContentType { get; set; }
public HttpStatusCode StatusCode { get; set; }
public ToolConsumerProfile ToolConsumerProfile { get; set; }
}
}
|
Add fix for missing method on interface | using System;
namespace Cake.Yarn
{
/// <summary>
/// Yarn Runner command interface
/// </summary>
public interface IYarnRunnerCommands
{
/// <summary>
/// execute 'yarn install' with options
/// </summary>
/// <param name="configure">options when running 'yarn install'</param>
IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null);
/// <summary>
/// execute 'yarn add' with options
/// </summary>
/// <param name="configure">options when running 'yarn add'</param>
IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null);
/// <summary>
/// execute 'yarn run' with arguments
/// </summary>
/// <param name="scriptName">name of the </param>
/// <param name="configure">options when running 'yarn run'</param>
IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null);
/// <summary>
/// execute 'yarn pack' with options
/// </summary>
/// <param name="packSettings">options when running 'yarn pack'</param>
IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null);
}
}
| using System;
namespace Cake.Yarn
{
/// <summary>
/// Yarn Runner command interface
/// </summary>
public interface IYarnRunnerCommands
{
/// <summary>
/// execute 'yarn install' with options
/// </summary>
/// <param name="configure">options when running 'yarn install'</param>
IYarnRunnerCommands Install(Action<YarnInstallSettings> configure = null);
/// <summary>
/// execute 'yarn add' with options
/// </summary>
/// <param name="configure">options when running 'yarn add'</param>
IYarnRunnerCommands Add(Action<YarnAddSettings> configure = null);
/// <summary>
/// execute 'yarn run' with arguments
/// </summary>
/// <param name="scriptName">name of the </param>
/// <param name="configure">options when running 'yarn run'</param>
IYarnRunnerCommands RunScript(string scriptName, Action<YarnRunSettings> configure = null);
/// <summary>
/// execute 'yarn pack' with options
/// </summary>
/// <param name="packSettings">options when running 'yarn pack'</param>
IYarnRunnerCommands Pack(Action<YarnPackSettings> packSettings = null);
/// <summary>
/// execute 'yarn version' with options
/// </summary>
/// <param name="versionSettings">options when running 'yarn version'</param>
IYarnRunnerCommands Version(Action<YarnVersionSettings> versionSettings = null);
}
}
|
Make sure logging doesn't cause cross-thread access to the log-file | using System;
using System.IO;
using System.Threading.Tasks;
namespace Ylp.GitDb.Core
{
public interface ILogger
{
Task Log(string message);
}
public class Logger : ILogger
{
public readonly string FileName;
public Logger(string fileName)
{
FileName = fileName;
}
public Task Log(string message)
{
File.AppendAllText(FileName, $"{DateTime.Now.ToString("HH:mm:ss")}: {message}\n");
return Task.CompletedTask;
}
}
} | using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace Ylp.GitDb.Core
{
public interface ILogger
{
Task Log(string message);
}
public class Logger : ILogger
{
public readonly string FileName;
static readonly object LockObj = new object();
public Logger(string fileName)
{
FileName = fileName;
}
public Task Log(string message)
{
lock(LockObj)
File.AppendAllText(FileName, $"{DateTime.Now.ToString("HH:mm:ss")}: {message}\n");
return Task.CompletedTask;
}
}
} |
Revert the whitespace change of the auto generated file |
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Tool : Bond Compiler 0.4.1.0
// File : ExceptionDetails_types.cs
//
// Changes to this file may cause incorrect behavior and will be lost when
// the code is regenerated.
// <auto-generated />
//------------------------------------------------------------------------------
// suppress "Missing XML comment for publicly visible type or member"
#pragma warning disable 1591
#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.External
{
using System.Collections.Concurrent;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.4.1.0")]
internal partial class ExceptionDetails
{
public int id { get; set; }
public int outerId { get; set; }
public string typeName { get; set; }
public string message { get; set; }
public bool hasFullStack { get; set; }
public string stack { get; set; }
public IList<StackFrame> parsedStack { get; set; }
public ExceptionDetails()
: this("AI.ExceptionDetails", "ExceptionDetails")
{ }
protected ExceptionDetails(string fullName, string name)
{
typeName = "";
message = "";
hasFullStack = true;
stack = "";
parsedStack = new List<StackFrame>();
}
}
} // AI
|
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Tool : Bond Compiler 0.4.1.0
// File : ExceptionDetails_types.cs
//
// Changes to this file may cause incorrect behavior and will be lost when
// the code is regenerated.
// <auto-generated />
//------------------------------------------------------------------------------
// suppress "Missing XML comment for publicly visible type or member"
#pragma warning disable 1591
#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.External
{
using System.Collections.Concurrent;
using System.Collections.Generic;
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.4.1.0")]
internal partial class ExceptionDetails
{
public int id { get; set; }
public int outerId { get; set; }
public string typeName { get; set; }
public string message { get; set; }
public bool hasFullStack { get; set; }
public string stack { get; set; }
public IList<StackFrame> parsedStack { get; set; }
public ExceptionDetails()
: this("AI.ExceptionDetails", "ExceptionDetails")
{}
protected ExceptionDetails(string fullName, string name)
{
typeName = "";
message = "";
hasFullStack = true;
stack = "";
parsedStack = new List<StackFrame>();
}
}
} // AI
|
Support all objects for debugger display. | using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Qowaiv.UnitTests.TestTools
{
public static class DebuggerDisplayAssert
{
public static void HasAttribute(Type type)
{
Assert.IsNotNull(type, "The supplied type should not be null.");
var act = (DebuggerDisplayAttribute)type.GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).FirstOrDefault();
Assert.IsNotNull(act, "The type '{0}' has no DebuggerDisplay attribute.", type);
Assert.AreEqual("{DebuggerDisplay}", act.Value, "DebuggerDisplay attribute value is not '{DebuggerDisplay}'.");
}
public static void HasResult(string expected, object value)
{
Assert.IsNotNull(value, "The supplied value should not be null.");
var type = value.GetType();
var prop = type.GetProperty("DebuggerDisplay", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(prop, "The type '{0}' does not contain a non-public property DebuggerDisplay.", type);
var actual = prop.GetValue(value);
Assert.AreEqual(expected, actual);
}
}
}
| using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Qowaiv.UnitTests.TestTools
{
public static class DebuggerDisplayAssert
{
public static void HasAttribute(Type type)
{
Assert.IsNotNull(type, "The supplied type should not be null.");
var act = (DebuggerDisplayAttribute)type.GetCustomAttributes(typeof(DebuggerDisplayAttribute), false).FirstOrDefault();
Assert.IsNotNull(act, "The type '{0}' has no DebuggerDisplay attribute.", type);
Assert.AreEqual("{DebuggerDisplay}", act.Value, "DebuggerDisplay attribute value is not '{DebuggerDisplay}'.");
}
public static void HasResult(object expected, object value)
{
Assert.IsNotNull(value, "The supplied value should not be null.");
var type = value.GetType();
var prop = type.GetProperty("DebuggerDisplay", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(prop, "The type '{0}' does not contain a non-public property DebuggerDisplay.", type);
var actual = prop.GetValue(value);
Assert.AreEqual(expected, actual);
}
}
}
|
Clean up test and reference original issue | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp8.LayoutRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp7.LayoutRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.LayoutRules.SA1514ElementDocumentationHeaderMustBePrecededByBlankLine,
StyleCop.Analyzers.LayoutRules.SA1514CodeFixProvider>;
public class SA1514CSharp8UnitTests : SA1514CSharp7UnitTests
{
/// <summary>
/// Verifies that method-like declarations with invalid documentation will produce the expected diagnostics.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestValidPropertyDeclarationAsync()
{
var testCode = @"namespace TestNamespace
{
public class TestClass
{
/// <summary>
/// Gets or sets the value.
/// </summary>
public string SomeString { get; set; } = null!;
/// <summary>
/// Gets or sets the value.
/// </summary>
public string AnotherString { get; set; } = null!;
}
}
";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
| // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp8.LayoutRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp7.LayoutRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.LayoutRules.SA1514ElementDocumentationHeaderMustBePrecededByBlankLine,
StyleCop.Analyzers.LayoutRules.SA1514CodeFixProvider>;
public class SA1514CSharp8UnitTests : SA1514CSharp7UnitTests
{
[Fact]
[WorkItem(3067, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3067")]
public async Task TestValidPropertyDeclarationAsync()
{
var testCode = @"namespace TestNamespace
{
public class TestClass
{
/// <summary>
/// Gets or sets the value.
/// </summary>
public string SomeString { get; set; } = null!;
/// <summary>
/// Gets or sets the value.
/// </summary>
public string AnotherString { get; set; } = null!;
}
}
";
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
|
Add failing test for append called several times for string identity | using System;
using Marten.Testing.Harness;
using Xunit;
namespace DocumentDbTests.Bugs
{
public class Bug_673_multiple_version_assertions: IntegrationContext
{
[Fact]
public void replaces_the_max_version_assertion()
{
var streamId = Guid.NewGuid();
using (var session = theStore.OpenSession())
{
session.Events.Append(streamId, new WhateverEvent(), new WhateverEvent());
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
var state = session.Events.FetchStreamState(streamId);
// ... do some stuff
var expectedVersion = state.Version + 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
// ... do some more stuff
expectedVersion += 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
session.SaveChanges();
}
}
public Bug_673_multiple_version_assertions(DefaultStoreFixture fixture) : base(fixture)
{
}
}
public class WhateverEvent
{
}
}
| using System;
using Marten.Events;
using Marten.Testing.Harness;
using Xunit;
namespace DocumentDbTests.Bugs
{
public class Bug_673_multiple_version_assertions: IntegrationContext
{
[Fact]
public void replaces_the_max_version_assertion()
{
var streamId = Guid.NewGuid();
using (var session = theStore.OpenSession())
{
session.Events.Append(streamId, new WhateverEvent(), new WhateverEvent());
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
var state = session.Events.FetchStreamState(streamId);
// ... do some stuff
var expectedVersion = state.Version + 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
// ... do some more stuff
expectedVersion += 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
session.SaveChanges();
}
}
[Fact]
public void replaces_the_max_version_assertion_for_string_identity()
{
UseStreamIdentity(StreamIdentity.AsString);
var streamId = Guid.NewGuid().ToString();
using (var session = theStore.OpenSession())
{
session.Events.Append(streamId, new WhateverEvent(), new WhateverEvent());
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
var state = session.Events.FetchStreamState(streamId);
// ... do some stuff
var expectedVersion = state.Version + 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
// ... do some more stuff
expectedVersion += 1;
session.Events.Append(streamId, expectedVersion, new WhateverEvent());
session.SaveChanges();
}
}
public Bug_673_multiple_version_assertions(DefaultStoreFixture fixture) : base(fixture)
{
}
}
public class WhateverEvent
{
}
}
|
Fix refactoring provider to correctly handle positions near EOF | using System;
using System.Collections.Generic;
using System.Linq;
namespace NQuery.Authoring.CodeActions
{
public abstract class CodeRefactoringProvider<T> : ICodeRefactoringProvider
where T : SyntaxNode
{
public IEnumerable<ICodeAction> GetRefactorings(SemanticModel semanticModel, int position)
{
var syntaxTree = semanticModel.Compilation.SyntaxTree;
var syntaxToken = syntaxTree.Root.FindToken(position);
var synaxNodes = syntaxToken.Parent.AncestorsAndSelf().OfType<T>();
return synaxNodes.SelectMany(n => GetRefactorings(semanticModel, position, n));
}
protected abstract IEnumerable<ICodeAction> GetRefactorings(SemanticModel semanticModel, int position, T node);
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace NQuery.Authoring.CodeActions
{
public abstract class CodeRefactoringProvider<T> : ICodeRefactoringProvider
where T : SyntaxNode
{
public IEnumerable<ICodeAction> GetRefactorings(SemanticModel semanticModel, int position)
{
var syntaxTree = semanticModel.Compilation.SyntaxTree;
return from t in syntaxTree.Root.FindStartTokens(position)
from n in t.Parent.AncestorsAndSelf().OfType<T>()
from r in GetRefactorings(semanticModel, position, n)
select r;
}
protected abstract IEnumerable<ICodeAction> GetRefactorings(SemanticModel semanticModel, int position, T node);
}
} |
Fix deserialization of RegEx enabled properties | using System;
using Newtonsoft.Json;
namespace Archetype.Models
{
public class ArchetypePreValueProperty
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("remove")]
public bool Remove { get; set; }
[JsonProperty("collapse")]
public bool Collapse { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("helpText")]
public string HelpText { get; set; }
[JsonProperty("dataTypeGuid")]
public Guid DataTypeGuid { get; set; }
[JsonProperty("propertyEditorAlias")]
public string PropertyEditorAlias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("required")]
public bool Required { get; set; }
[JsonProperty("regEx")]
public bool RegEx { get; set; }
}
} | using System;
using Newtonsoft.Json;
namespace Archetype.Models
{
public class ArchetypePreValueProperty
{
[JsonProperty("alias")]
public string Alias { get; set; }
[JsonProperty("remove")]
public bool Remove { get; set; }
[JsonProperty("collapse")]
public bool Collapse { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("helpText")]
public string HelpText { get; set; }
[JsonProperty("dataTypeGuid")]
public Guid DataTypeGuid { get; set; }
[JsonProperty("propertyEditorAlias")]
public string PropertyEditorAlias { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("required")]
public bool Required { get; set; }
[JsonProperty("regEx")]
public string RegEx { get; set; }
}
} |
Fix en dashboard. Uso de la clase de configuracion. | using System.Configuration;
using System.IO;
using System.Linq;
using System.Web.Helpers;
using System.Web.Mvc;
using Topppro.WebSite.Areas.Humanist.Models;
namespace Topppro.WebSite.Areas.Humanist.Controllers
{
[Authorize]
public class DashboardController : Controller
{
private readonly static string _dlcFolderPath =
ConfigurationManager.AppSettings["RootDownloadsFolderPath"];
public ActionResult Index()
{
var key = "RootDownloadsFolderPath";
var cached = WebCache.Get(key);
if (cached == null)
{
string dlc_path =
Server.MapPath(_dlcFolderPath);
DirectoryInfo dlc_folder = new DirectoryInfo(dlc_path);
if (!dlc_folder.Exists)
return null;
cached = dlc_folder.GetFiles()
.Select(f => new DLCModel()
{
Url = UrlHelper.GenerateContentUrl(Path.Combine(_dlcFolderPath, f.Name), HttpContext),
Name = Path.GetFileNameWithoutExtension(f.Name),
Color = "purple-stripe",
Icon = ""
});
WebCache.Set(key, cached);
}
return View(cached);
}
}
}
| using System.IO;
using System.Linq;
using System.Web.Helpers;
using System.Web.Mvc;
using Topppro.WebSite.Areas.Humanist.Models;
using Topppro.WebSite.Settings;
namespace Topppro.WebSite.Areas.Humanist.Controllers
{
[Authorize]
public class DashboardController : Controller
{
public ActionResult Index()
{
var key = typeof(DownloadSettings).Name;
var cached = WebCache.Get(key);
if (cached == null)
{
string dlc_path =
Server.MapPath(ToppproSettings.Download.Root);
DirectoryInfo dlc_folder = new DirectoryInfo(dlc_path);
if (!dlc_folder.Exists)
return null;
cached = dlc_folder.GetFiles()
.Select(f => new DLCModel()
{
Url = UrlHelper.GenerateContentUrl(Path.Combine(ToppproSettings.Download.Root, f.Name), HttpContext),
Name = Path.GetFileNameWithoutExtension(f.Name),
Color = "purple-stripe",
Icon = ""
});
WebCache.Set(key, cached);
}
return View(cached);
}
}
}
|
Fix bug in the repeater step validation | #load "00_constants.csx"
using DotvvmAcademy.Validation.Dothtml.Unit;
using DotvvmAcademy.Validation.Unit;
public DothtmlUnit Unit { get; set; } = new DothtmlUnit();
Unit.GetDirective("/@viewModel")
.RequireTypeArgument(ViewModelName);
var repeater = Unit.GetControl("/html/body/dot:Repeater");
{
repeater.GetProperty("@DataSource")
.RequireBinding(ItemsProperty);
repeater.GetControl("p/dot:Literal")
.GetProperty("@Text")
.RequireBinding("_this");
} | #load "00_constants.csx"
using DotvvmAcademy.Validation.Dothtml.Unit;
using DotvvmAcademy.Validation.Unit;
public DothtmlUnit Unit { get; set; } = new DothtmlUnit();
Unit.GetDirective("/@viewModel")
.RequireTypeArgument(ViewModelName);
var repeater = Unit.GetControl("/html/body/dot:Repeater");
{
repeater.GetProperty("@DataSource")
.RequireBinding(ItemsProperty)
.GetControl("p/dot:Literal")
.GetProperty("@Text")
.RequireBinding("_this");
} |
Update attribute summary and example | using System;
namespace EasyButtons
{
/// <summary>
/// Attribute to create a button in the inspector for calling the method it is attached to.
/// The method must have no arguments.
/// </summary>
/// <example>
/// [<see cref="ButtonAttribute"/>]
/// void MyMethod()
/// {
/// Debug.Log("Clicked!");
/// }
/// </example>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class ButtonAttribute : Attribute { }
} | using System;
namespace EasyButtons
{
/// <summary>
/// Attribute to create a button in the inspector for calling the method it is attached to.
/// The method must be public and have no arguments.
/// </summary>
/// <example>
/// [<see cref="ButtonAttribute"/>]
/// public void MyMethod()
/// {
/// Debug.Log("Clicked!");
/// }
/// </example>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class ButtonAttribute : Attribute { }
} |
Move diff bar to the right of the line numbers (like in the GitSCC extension) | #region using
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
#endregion
namespace GitDiffMargin
{
[Export(typeof (IWpfTextViewMarginProvider))]
[Name(EditorDiffMargin.MarginNameConst)]
[Order(Before = PredefinedMarginNames.LineNumber)]
[MarginContainer(PredefinedMarginNames.LeftSelection)]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Editable)]
internal sealed class EditorDiffMarginFactory : DiffMarginFactoryBase
{
public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, IWpfTextViewMargin containerMargin)
{
var marginCore = TryGetMarginCore(textViewHost);
if (marginCore == null)
return null;
return new EditorDiffMargin(textViewHost.TextView, marginCore);
}
}
} | #region using
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
#endregion
namespace GitDiffMargin
{
[Export(typeof (IWpfTextViewMarginProvider))]
[Name(EditorDiffMargin.MarginNameConst)]
[Order(After = PredefinedMarginNames.Spacer, Before = PredefinedMarginNames.Outlining)]
[MarginContainer(PredefinedMarginNames.LeftSelection)]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Editable)]
internal sealed class EditorDiffMarginFactory : DiffMarginFactoryBase
{
public override IWpfTextViewMargin CreateMargin(IWpfTextViewHost textViewHost, IWpfTextViewMargin containerMargin)
{
var marginCore = TryGetMarginCore(textViewHost);
if (marginCore == null)
return null;
return new EditorDiffMargin(textViewHost.TextView, marginCore);
}
}
} |
Remove random context cleanup console output | using System;
using System.Runtime.InteropServices;
namespace LibGPhoto2
{
public class Context : Object
{
[DllImport ("libgphoto2.so")]
internal static extern IntPtr gp_context_new ();
public Context ()
{
this.handle = new HandleRef (this, gp_context_new ());
}
[DllImport ("libgphoto2.so")]
internal static extern void gp_context_unref (HandleRef context);
protected override void Cleanup ()
{
System.Console.WriteLine ("cleanup context");
gp_context_unref(handle);
}
}
}
| using System;
using System.Runtime.InteropServices;
namespace LibGPhoto2
{
public class Context : Object
{
[DllImport ("libgphoto2.so")]
internal static extern IntPtr gp_context_new ();
public Context ()
{
this.handle = new HandleRef (this, gp_context_new ());
}
[DllImport ("libgphoto2.so")]
internal static extern void gp_context_unref (HandleRef context);
protected override void Cleanup ()
{
gp_context_unref(handle);
}
}
}
|
Add support for `SupportAddress` on `Account` create and update | namespace Stripe
{
using Newtonsoft.Json;
public class AccountBusinessProfileOptions : INestedOptions
{
[JsonProperty("mcc")]
public string Mcc { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("primary_color")]
public string PrimaryColor { get; set; }
[JsonProperty("product_description")]
public string ProductDescription { get; set; }
[JsonProperty("support_email")]
public string SupportEmail { get; set; }
[JsonProperty("support_phone")]
public string SupportPhone { get; set; }
[JsonProperty("support_url")]
public string SupportUrl { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
}
| namespace Stripe
{
using System;
using Newtonsoft.Json;
public class AccountBusinessProfileOptions : INestedOptions
{
/// <summary>
/// The merchant category code for the account. MCCs are used to classify businesses based
/// on the goods or services they provide.
/// </summary>
[JsonProperty("mcc")]
public string Mcc { get; set; }
/// <summary>
/// The customer-facing business name.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
[Obsolete("Use AccountSettingsBrandingOptions.PrimaryColor instead.")]
[JsonProperty("primary_color")]
public string PrimaryColor { get; set; }
/// <summary>
/// Internal-only description of the product sold by, or service provided by, the business.
/// Used by Stripe for risk and underwriting purposes.
/// </summary>
[JsonProperty("product_description")]
public string ProductDescription { get; set; }
/// <summary>
/// A publicly available mailing address for sending support issues to.
/// </summary>
[JsonProperty("support_address")]
public AddressOptions SupportAddress { get; set; }
/// <summary>
/// A publicly available email address for sending support issues to.
/// </summary>
[JsonProperty("support_email")]
public string SupportEmail { get; set; }
/// <summary>
/// A publicly available phone number to call with support issues.
/// </summary>
[JsonProperty("support_phone")]
public string SupportPhone { get; set; }
/// <summary>
/// A publicly available website for handling support issues.
/// </summary>
[JsonProperty("support_url")]
public string SupportUrl { get; set; }
/// <summary>
/// The business’s publicly available website.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
}
}
|
Add channel state None (CS_NONE) | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ChannelState.cs" company="Dan Barua">
// (C) Dan Barua and contributors. Licensed under the Mozilla Public License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NEventSocket.FreeSwitch
{
/// <summary>
/// Represents the state of a Channel
/// </summary>
public enum ChannelState
{
#pragma warning disable 1591
New,
Init,
Routing,
SoftExecute,
Execute,
ExchangeMedia,
Park,
ConsumeMedia,
Hibernate,
Reset,
Hangup,
Done,
Destroy,
Reporting
#pragma warning restore 1591
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ChannelState.cs" company="Dan Barua">
// (C) Dan Barua and contributors. Licensed under the Mozilla Public License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NEventSocket.FreeSwitch
{
/// <summary>
/// Represents the state of a Channel
/// </summary>
public enum ChannelState
{
#pragma warning disable 1591
New,
Init,
Routing,
SoftExecute,
Execute,
ExchangeMedia,
Park,
ConsumeMedia,
Hibernate,
Reset,
Hangup,
Done,
Destroy,
Reporting,
None
#pragma warning restore 1591
}
} |
Fix for no soldier foudn on nav component | using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Models
{
public class NavigationViewComponent : ViewComponent
{
private readonly Database db;
public Soldier Soldier { get; private set; }
public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);
public NavigationViewComponent(Database db)
{
this.db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);
return View(this);
}
}
} | using BatteryCommander.Web.Controllers;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Models
{
public class NavigationViewComponent : ViewComponent
{
private readonly Database db;
public Soldier Soldier { get; private set; }
public Boolean ShowNavigation => Soldier != null && !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]);
public NavigationViewComponent(Database db)
{
this.db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
Soldier = await UserService.FindAsync(db, UserClaimsPrincipal);
return View(this);
}
}
} |
Copy change on the logged in page | @model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
ViewBag.PageID = "authorize-response";
ViewBag.Title = "Login Successful";
ViewBag.HideSigninLink = "true";
}
<h1 class="heading-xlarge">Login successful</h1>
<form id="mainForm" method="post" action="@Model.ResponseFormUri">
<div id="autoRedirect" style="display: none;">Please wait...</div>
@Html.Raw(Model.ResponseFormFields)
<div id="manualLoginContainer">
<p>It appears you do not have javascript enabled. Please click the continue button to complete your login.</p>
<button type="submit" class="button" autofocus="autofocus">Continue</button>
</div>
</form>
@section scripts
{
<script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script>
} | @model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
ViewBag.PageID = "authorize-response";
ViewBag.Title = "Login Successful";
ViewBag.HideSigninLink = "true";
}
<h1 class="heading-xlarge">Login successful</h1>
<form id="mainForm" method="post" action="@Model.ResponseFormUri">
<div id="autoRedirect" style="display: none;">Please wait...</div>
@Html.Raw(Model.ResponseFormFields)
<div id="manualLoginContainer">
<p>Please click the continue button to complete your login.</p>
<button type="submit" class="button" autofocus="autofocus">Continue</button>
</div>
</form>
@section scripts
{
<script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script>
} |
Move request changed for uniformity | using System;
using System.Net;
using System.Text;
using YaR.MailRuCloud.Api.Base.Requests.Repo;
namespace YaR.MailRuCloud.Api.Base.Requests.WebM1
{
class MoveRequest : BaseRequestJson<WebV2.CopyRequest.Result>
{
private readonly string _sourceFullPath;
private readonly string _destinationPath;
public MoveRequest(IWebProxy proxy, IAuth auth, string sourceFullPath, string destinationPath) : base(proxy, auth)
{
_sourceFullPath = sourceFullPath;
_destinationPath = destinationPath;
}
protected override string RelationalUri => $"/api/m1/file/move?access_token={Auth.AccessToken}";
protected override byte[] CreateHttpContent()
{
var data = Encoding.UTF8.GetBytes($"home={Uri.EscapeDataString(_sourceFullPath)}&email={Auth.Login}&conflict=rename&folder={Uri.EscapeDataString(_destinationPath)}");
return data;
}
}
}
| using System;
using System.Net;
using System.Text;
using YaR.MailRuCloud.Api.Base.Requests.Repo;
namespace YaR.MailRuCloud.Api.Base.Requests.WebM1
{
class MoveRequest : BaseRequestJson<WebV2.CopyRequest.Result>
{
private readonly string _sourceFullPath;
private readonly string _destinationPath;
public MoveRequest(IWebProxy proxy, IAuth auth, string sourceFullPath, string destinationPath) : base(proxy, auth)
{
_sourceFullPath = sourceFullPath;
_destinationPath = destinationPath;
}
protected override string RelationalUri => $"/api/m1/file/move?access_token={Auth.AccessToken}";
protected override byte[] CreateHttpContent()
{
var data = $"home={Uri.EscapeDataString(_sourceFullPath)}&email={Auth.Login}&conflict=rename&folder={Uri.EscapeDataString(_destinationPath)}";
return Encoding.UTF8.GetBytes(data);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.