Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Convert invoker proxy over to be internal | using Microsoft.AspNet.SignalR.Client;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent.Connection.Stream.Connection
{
public class StreamInvokerProxy : IStreamInvokerProxy
{
private readonly IHubProxy _hubProxy;
internal StreamInvokerProxy(IHubProxy hubProxy)
{
_hubProxy = hubProxy;
}
public Task Invoke(string method, params object[] args)
{
return _hubProxy.Invoke(method, args);
}
public Task<T> Invoke<T>(string method, params object[] args)
{
return _hubProxy.Invoke<T>(method, args);
}
}
} | using Microsoft.AspNet.SignalR.Client;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent.Connection.Stream.Connection
{
internal class StreamInvokerProxy : IStreamInvokerProxy
{
private readonly IHubProxy _hubProxy;
internal StreamInvokerProxy(IHubProxy hubProxy)
{
_hubProxy = hubProxy;
}
public Task Invoke(string method, params object[] args)
{
return _hubProxy.Invoke(method, args);
}
public Task<T> Invoke<T>(string method, params object[] args)
{
return _hubProxy.Invoke<T>(method, args);
}
}
} |
Use PlayMode instead of GameMode | using System;
using osu.Game.Beatmaps;
using SQLite;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey]
public int ID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public GameMode Mode { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
}
} | using System;
using osu.Game.GameModes.Play;
using SQLite;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey]
public int ID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public PlayMode Mode { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
}
} |
Fix spelling of .editorconfig option | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editing
{
internal class GenerationOptions
{
public static readonly PerLanguageOption<bool> PlaceSystemNamespaceFirst = new PerLanguageOption<bool>(nameof(GenerationOptions),
nameof(PlaceSystemNamespaceFirst), defaultValue: true,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"),
new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")});
public static readonly PerLanguageOption<bool> SeparateImportDirectiveGroups = new PerLanguageOption<bool>(
nameof(GenerationOptions), nameof(SeparateImportDirectiveGroups), defaultValue: false,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_seperate_import_directive_groups"),
new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")});
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editing
{
internal class GenerationOptions
{
public static readonly PerLanguageOption<bool> PlaceSystemNamespaceFirst = new PerLanguageOption<bool>(nameof(GenerationOptions),
nameof(PlaceSystemNamespaceFirst), defaultValue: true,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"),
new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")});
public static readonly PerLanguageOption<bool> SeparateImportDirectiveGroups = new PerLanguageOption<bool>(
nameof(GenerationOptions), nameof(SeparateImportDirectiveGroups), defaultValue: false,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_separate_import_directive_groups"),
new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")});
}
}
|
Fix formatting and remove unnecessary using | // 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.Framework.Graphics.OpenGL;
using System;
namespace osu.Framework.Graphics.Shaders
{
public class Uniform<T> : IUniformWithValue<T>
where T : struct, IEquatable<T>
{
public Shader Owner { get; }
public string Name { get; }
public int Location { get; }
public bool HasChanged { get; private set; } = true;
private T val;
public T Value
{
get => val;
set
{
if (value.Equals(val))
return;
val = value;
HasChanged = true;
if (Owner.IsBound)
Update();
}
}
public Uniform(Shader owner, string name, int uniformLocation)
{
Owner = owner;
Name = name;
Location = uniformLocation;
}
public void UpdateValue(ref T newValue)
{
if (newValue.Equals(val))
return;
val= newValue;
HasChanged = true;
if (Owner.IsBound)
Update();
}
public void Update()
{
if (!HasChanged) return;
GLWrapper.SetUniform(this);
HasChanged = false;
}
ref T IUniformWithValue<T>.GetValueByRef() => ref val;
T IUniformWithValue<T>.GetValue() => val;
}
}
| // 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.OpenGL;
using System;
namespace osu.Framework.Graphics.Shaders
{
public class Uniform<T> : IUniformWithValue<T>
where T : struct, IEquatable<T>
{
public Shader Owner { get; }
public string Name { get; }
public int Location { get; }
public bool HasChanged { get; private set; } = true;
private T val;
public T Value
{
get => val;
set
{
if (value.Equals(val))
return;
val = value;
HasChanged = true;
if (Owner.IsBound)
Update();
}
}
public Uniform(Shader owner, string name, int uniformLocation)
{
Owner = owner;
Name = name;
Location = uniformLocation;
}
public void UpdateValue(ref T newValue)
{
if (newValue.Equals(val))
return;
val = newValue;
HasChanged = true;
if (Owner.IsBound)
Update();
}
public void Update()
{
if (!HasChanged) return;
GLWrapper.SetUniform(this);
HasChanged = false;
}
ref T IUniformWithValue<T>.GetValueByRef() => ref val;
T IUniformWithValue<T>.GetValue() => val;
}
}
|
Append version number to title | using System.Windows;
using System.Windows.Controls;
using FlaUInspect.ViewModels;
namespace FlaUInspect.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly MainViewModel _vm;
public MainWindow()
{
InitializeComponent();
Height = 550;
Width = 700;
Loaded += MainWindow_Loaded;
_vm = new MainViewModel();
DataContext = _vm;
}
private void MainWindow_Loaded(object sender, System.EventArgs e)
{
if (!_vm.IsInitialized)
{
var dlg = new ChooseVersionWindow { Owner = this };
if (dlg.ShowDialog() != true)
{
Close();
}
_vm.Initialize(dlg.SelectedAutomationType);
Loaded -= MainWindow_Loaded;
}
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void TreeViewSelectedHandler(object sender, RoutedEventArgs e)
{
var item = sender as TreeViewItem;
if (item != null)
{
item.BringIntoView();
e.Handled = true;
}
}
}
}
| using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using FlaUInspect.ViewModels;
namespace FlaUInspect.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly MainViewModel _vm;
public MainWindow()
{
InitializeComponent();
AppendVersionToTitle();
Height = 550;
Width = 700;
Loaded += MainWindow_Loaded;
_vm = new MainViewModel();
DataContext = _vm;
}
private void AppendVersionToTitle()
{
var attr = Assembly.GetEntryAssembly().GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
if (attr != null)
{
Title += " v" + attr.InformationalVersion;
}
}
private void MainWindow_Loaded(object sender, System.EventArgs e)
{
if (!_vm.IsInitialized)
{
var dlg = new ChooseVersionWindow { Owner = this };
if (dlg.ShowDialog() != true)
{
Close();
}
_vm.Initialize(dlg.SelectedAutomationType);
Loaded -= MainWindow_Loaded;
}
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void TreeViewSelectedHandler(object sender, RoutedEventArgs e)
{
var item = sender as TreeViewItem;
if (item != null)
{
item.BringIntoView();
e.Handled = true;
}
}
}
}
|
Fix legacy control point precision having an adverse effect on 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Screens.Edit.Timing
{
internal class DifficultySection : Section<DifficultyControlPoint>
{
private SliderWithTextBoxInput<double> multiplierSlider;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new[]
{
multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier")
{
Current = new DifficultyControlPoint().SpeedMultiplierBindable,
KeyboardStep = 0.1f
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point)
{
if (point.NewValue != null)
{
multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable;
multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override DifficultyControlPoint CreatePoint()
{
var reference = Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time);
return new DifficultyControlPoint
{
SpeedMultiplier = reference.SpeedMultiplier,
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Screens.Edit.Timing
{
internal class DifficultySection : Section<DifficultyControlPoint>
{
private SliderWithTextBoxInput<double> multiplierSlider;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new[]
{
multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier")
{
Current = new DifficultyControlPoint().SpeedMultiplierBindable,
KeyboardStep = 0.1f
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point)
{
if (point.NewValue != null)
{
var selectedPointBindable = point.NewValue.SpeedMultiplierBindable;
// there may be legacy control points, which contain infinite precision for compatibility reasons (see LegacyDifficultyControlPoint).
// generally that level of precision could only be set by externally editing the .osu file, so at the point
// a user is looking to update this within the editor it should be safe to obliterate this additional precision.
double expectedPrecision = new DifficultyControlPoint().SpeedMultiplierBindable.Precision;
if (selectedPointBindable.Precision < expectedPrecision)
selectedPointBindable.Precision = expectedPrecision;
multiplierSlider.Current = selectedPointBindable;
multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override DifficultyControlPoint CreatePoint()
{
var reference = Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time);
return new DifficultyControlPoint
{
SpeedMultiplier = reference.SpeedMultiplier,
};
}
}
}
|
Add tag replacement on backup paths | using System.IO;
using System.IO.Compression;
namespace Ensconce.Console
{
internal static class Backup
{
internal static void DoBackup()
{
if (File.Exists(Arguments.BackupDestination) && Arguments.BackupOverwrite)
{
File.Delete(Arguments.BackupDestination);
}
ZipFile.CreateFromDirectory(Arguments.BackupSource, Arguments.BackupDestination, CompressionLevel.Optimal, false);
}
}
}
| using System.IO;
using System.IO.Compression;
namespace Ensconce.Console
{
internal static class Backup
{
internal static void DoBackup()
{
var backupSource = Arguments.BackupSource.Render();
var backupDestination = Arguments.BackupDestination.Render();
if (File.Exists(backupDestination) && Arguments.BackupOverwrite)
{
File.Delete(backupDestination);
}
ZipFile.CreateFromDirectory(backupSource, backupDestination, CompressionLevel.Optimal, false);
}
}
}
|
Increment projects copyright year to 2020 | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2019")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2020")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
|
Add a stronger dependency on UnityEngine for testing. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PluginTest
{
public class TestPlugin
{
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace PluginTest
{
public class TestPlugin : MonoBehaviour
{
private void Start()
{
Debug.Log("Start called");
}
}
}
|
Add handling for missing / | @{
string baseEditUrl = Context.String(DocsKeys.BaseEditUrl);
FilePath editFilePath = Model.FilePath(Wyam.Web.WebKeys.EditFilePath);
if(!string.IsNullOrWhiteSpace(baseEditUrl) && editFilePath != null)
{
string editUrl = baseEditUrl + editFilePath.FullPath;
<div><p><a href="@editUrl"><i class="fa fa-pencil-square" aria-hidden="true"></i> Edit Content</a></p></div>
}
<div id="infobar-headings"></div>
} | @{
string baseEditUrl = Context.String(DocsKeys.BaseEditUrl);
FilePath editFilePath = Model.FilePath(Wyam.Web.WebKeys.EditFilePath);
if(!string.IsNullOrWhiteSpace(baseEditUrl) && editFilePath != null)
{
if (!baseEditUrl[baseEditUrl.Length - 1].equals('/'))
{
baseEditUrl += "/";
}
string editUrl = baseEditUrl + editFilePath.FullPath;
<div><p><a href="@editUrl"><i class="fa fa-pencil-square" aria-hidden="true"></i> Edit Content</a></p></div>
}
<div id="infobar-headings"></div>
}
|
Fix problems with launching and exiting the app | using System;
using System.Net;
namespace a
{
class Program
{
//Code is dirty, who cares, it's C#.
static void Main(string[] args)
{
//IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName());
//foreach (IPAddress curAdd in heserver.AddressList)
//{
Server server = new Server(IPAddress.Loopback, 5000);
server.Start();
Console.WriteLine("Press q to exit");
while (true)
{
try
{
char c = (char)Console.ReadLine()[0];
if (c == 'q')
{
server.Stop();
break;
}
}
catch (Exception)
{
//who cares ?
}
}
//}
}
}
}
| using System;
using System.Net;
namespace a
{
class Program
{
//Code is dirty, who cares, it's C#.
static void Main(string[] args)
{
Server server = new Server(IPAddress.Any, 5000);
server.Start();
Console.WriteLine("Press q to exit");
while (true)
{
try
{
if (Console.ReadKey().KeyChar == 'q')
{
server.Stop();
return;
}
}
catch (Exception)
{
//who cares ?
}
}
}
}
}
|
Add unit test for complex types. | using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace BobTheBuilder.Tests
{
public class BuildFacts
{
[Fact]
public void CreateADynamicInstanceOfTheRequestedType()
{
var sut = A.BuilderFor<SampleType>();
var result = sut.Build();
Assert.IsAssignableFrom<dynamic>(result);
Assert.IsAssignableFrom<SampleType>(result);
}
[Theory, AutoData]
public void SetStringStateByName(string expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithStringProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.StringProperty);
}
[Theory, AutoData]
public void SetIntStateByName(int expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithIntProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.IntProperty);
}
}
}
| using System;
using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace BobTheBuilder.Tests
{
public class BuildFacts
{
[Fact]
public void CreateADynamicInstanceOfTheRequestedType()
{
var sut = A.BuilderFor<SampleType>();
var result = sut.Build();
Assert.IsAssignableFrom<dynamic>(result);
Assert.IsAssignableFrom<SampleType>(result);
}
[Theory, AutoData]
public void SetStringStateByName(string expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithStringProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.StringProperty);
}
[Theory, AutoData]
public void SetIntStateByName(int expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithIntProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.IntProperty);
}
[Theory, AutoData]
public void SetComplexStateByName(Exception expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithComplexProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.ComplexProperty);
}
}
}
|
Add additional script languages which use the arabic shaper | // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using SixLabors.Fonts.Unicode;
namespace SixLabors.Fonts.Tables.AdvancedTypographic.Shapers
{
internal static class ShaperFactory
{
/// <summary>
/// Creates a Shaper based on the given script language.
/// </summary>
/// <param name="script">The script language.</param>
/// <returns>A shaper for the given script.</returns>
public static BaseShaper Create(Script script)
{
switch (script)
{
case Script.Arabic:
return new ArabicShaper();
default:
return new DefaultShaper();
}
}
}
}
| // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using SixLabors.Fonts.Unicode;
namespace SixLabors.Fonts.Tables.AdvancedTypographic.Shapers
{
internal static class ShaperFactory
{
/// <summary>
/// Creates a Shaper based on the given script language.
/// </summary>
/// <param name="script">The script language.</param>
/// <returns>A shaper for the given script.</returns>
public static BaseShaper Create(Script script)
{
switch (script)
{
case Script.Arabic:
case Script.Mongolian:
case Script.Syriac:
case Script.Nko:
case Script.PhagsPa:
case Script.Mandaic:
case Script.Manichaean:
case Script.PsalterPahlavi:
return new ArabicShaper();
default:
return new DefaultShaper();
}
}
}
}
|
Fix a bug: When clean up disused images, the DefaultThumbnail.jpg could be removed by mistake if all books have their own images. | using Lbookshelf.Business;
using Microsoft.Expression.Interactivity.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Configuration;
using Lbookshelf.Utils;
using Lbookshelf.Models;
using Lapps.Utils;
using Lapps.Utils.Collections;
namespace Lbookshelf.ViewModels
{
public class SettingsFileSystemViewModel : ObservableObject
{
public SettingsFileSystemViewModel()
{
CleanCommand = new ActionCommand(
() =>
{
var used = BookManager.Instance.Books.Select(b => Path.Combine(Environment.CurrentDirectory, b.Thumbnail));
var cached = Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "Images"));
var disused = cached.Except(used).ToArray();
if (disused.Length > 0)
{
disused.ForEach(p => File.Delete(p));
DialogService.ShowDialog(String.Format("{0} disused thumbnails were removed.", disused.Length));
}
else
{
DialogService.ShowDialog("All thumbnails are in use.");
}
});
}
public string RootDirectory
{
get { return StorageManager.Instance.RootDirectory; }
set
{
StorageManager.Instance.RootDirectory = value;
SettingManager.Default.RootDirectory = StorageManager.Instance.RootDirectory;
SettingManager.Default.Save();
}
}
public ICommand CleanCommand { get; private set; }
}
}
| using Lbookshelf.Business;
using Microsoft.Expression.Interactivity.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Configuration;
using Lbookshelf.Utils;
using Lbookshelf.Models;
using Lapps.Utils;
using Lapps.Utils.Collections;
namespace Lbookshelf.ViewModels
{
public class SettingsFileSystemViewModel : ObservableObject
{
public SettingsFileSystemViewModel()
{
CleanCommand = new ActionCommand(
() =>
{
var used = BookManager.Instance.Books.Select(b => Path.Combine(Environment.CurrentDirectory, b.Thumbnail));
var cached = Directory
.GetFiles(Path.Combine(Environment.CurrentDirectory, "Images"))
.Where(p => Path.GetFileName(p) != "DefaultThumbnail.jpg");
var disused = cached.Except(used).ToArray();
if (disused.Length > 0)
{
disused.ForEach(p => File.Delete(p));
DialogService.ShowDialog(String.Format("{0} disused thumbnails were removed.", disused.Length));
}
else
{
DialogService.ShowDialog("All thumbnails are in use.");
}
});
}
public string RootDirectory
{
get { return StorageManager.Instance.RootDirectory; }
set
{
StorageManager.Instance.RootDirectory = value;
SettingManager.Default.RootDirectory = StorageManager.Instance.RootDirectory;
SettingManager.Default.Save();
}
}
public ICommand CleanCommand { get; private 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>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_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 questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
|
Update server side API for single multiple answer question | 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 : IQuestionRespository
{
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 model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_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 : IQuestionRespository
{
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 model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
|
Allow bind interface to be customized. | namespace MailTrace.Host.Selfhost
{
using System;
using MailTrace.Data.Postgresql;
using MailTrace.Host;
using MailTrace.Host.Data;
using Microsoft.Owin.Hosting;
internal static class Program
{
private static void Main(string[] args)
{
const string baseAddress = "http://localhost:9900/";
Startup.PostConfigureKernel += kernel => { kernel.Bind<TraceContext>().To<PostgresqlTraceContext>(); };
Console.WriteLine("Running Migration...");
var context = new PostgresqlTraceContext();
context.Migrate();
using (WebApp.Start<Startup>(baseAddress))
{
Console.WriteLine("Ready.");
Console.ReadLine();
}
}
}
} | namespace MailTrace.Host.Selfhost
{
using System;
using System.Linq;
using MailTrace.Data.Postgresql;
using MailTrace.Host.Data;
using Microsoft.Owin.Hosting;
internal static class Program
{
private static void Main(string[] args)
{
var baseAddress = args.FirstOrDefault() ?? "http://localhost:9900";
Startup.PostConfigureKernel += kernel => { kernel.Bind<TraceContext>().To<PostgresqlTraceContext>(); };
Console.WriteLine("Running Migration...");
var context = new PostgresqlTraceContext();
context.Migrate();
using (WebApp.Start<Startup>(baseAddress))
{
Console.WriteLine("Ready.");
Console.ReadLine();
}
}
}
} |
Add documentation for alpha format. | namespace Avalonia.Platform
{
public enum AlphaFormat
{
Premul,
Unpremul,
Opaque
}
}
| namespace Avalonia.Platform
{
/// <summary>
/// Describes how to interpret the alpha component of a pixel.
/// </summary>
public enum AlphaFormat
{
/// <summary>
/// All pixels have their alpha premultiplied in their color components.
/// </summary>
Premul,
/// <summary>
/// All pixels have their color components stored without any regard to the alpha. e.g. this is the default configuration for PNG images.
/// </summary>
Unpremul,
/// <summary>
/// All pixels are stored as opaque.
/// </summary>
Opaque
}
}
|
Add test for authorization requirement in TraktUserCustomListItemsRemoveRequest | namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Post.Users.CustomListItems;
using TraktApiSharp.Objects.Post.Users.CustomListItems.Responses;
[TestClass]
public class TraktUserCustomListItemsRemoveRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsNotAbstract()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsSealed()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsSubclassOfATraktUsersPostByIdRequest()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsSubclassOf(typeof(ATraktUsersPostByIdRequest<TraktUserCustomListItemsRemovePostResponse, TraktUserCustomListItemsPost>)).Should().BeTrue();
}
}
}
| namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Post.Users.CustomListItems;
using TraktApiSharp.Objects.Post.Users.CustomListItems.Responses;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserCustomListItemsRemoveRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsNotAbstract()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsSealed()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestIsSubclassOfATraktUsersPostByIdRequest()
{
typeof(TraktUserCustomListItemsRemoveRequest).IsSubclassOf(typeof(ATraktUsersPostByIdRequest<TraktUserCustomListItemsRemovePostResponse, TraktUserCustomListItemsPost>)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListItemsRemoveRequestHasAuthorizationRequired()
{
var request = new TraktUserCustomListItemsRemoveRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
|
Revert "Change controller action to debug Kudu issue .." | using System.Web.Mvc;
using Amry.Gst.Properties;
using WebMarkupMin.Mvc.ActionFilters;
namespace Amry.Gst.Web.Controllers
{
public class HomeController : Controller
{
const int OneWeek = 604800;
const int OneYear = 31536000;
[Route, MinifyHtml, OutputCache(Duration = OneWeek)]
public ActionResult Index()
{
return View();
}
[Route("about"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult About()
{
return View();
}
[Route("api"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult Api()
{
return View();
}
[Route("ver")]
public ActionResult Version()
{
return Content("Version: " + AssemblyInfoConstants.Version, "text/plain");
}
}
} | using System.Web.Mvc;
using Amry.Gst.Properties;
using WebMarkupMin.Mvc.ActionFilters;
namespace Amry.Gst.Web.Controllers
{
public class HomeController : Controller
{
const int OneWeek = 604800;
const int OneYear = 31536000;
[Route, MinifyHtml, OutputCache(Duration = OneWeek)]
public ActionResult Index()
{
return View();
}
[Route("about"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult About()
{
return View();
}
[Route("api"), MinifyHtml, OutputCache(Duration = OneYear)]
public ActionResult Api()
{
return View();
}
[Route("ver")]
public ActionResult Version()
{
return Content(AssemblyInfoConstants.Version, "text/plain");
}
}
} |
Fix uploading files with uppercase extensions | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using CefSharp;
namespace TweetDuck.Core.Handling.General{
sealed class FileDialogHandler : IDialogHandler{
public bool OnFileDialog(IWebBrowser browserControl, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback){
CefFileDialogMode dialogType = mode & CefFileDialogMode.TypeMask;
if (dialogType == CefFileDialogMode.Open || dialogType == CefFileDialogMode.OpenMultiple){
string allFilters = string.Join(";", acceptFilters.Select(filter => "*"+filter));
using(OpenFileDialog dialog = new OpenFileDialog{
AutoUpgradeEnabled = true,
DereferenceLinks = true,
Multiselect = dialogType == CefFileDialogMode.OpenMultiple,
Title = "Open Files",
Filter = $"All Supported Formats ({allFilters})|{allFilters}|All Files (*.*)|*.*"
}){
if (dialog.ShowDialog() == DialogResult.OK){
callback.Continue(acceptFilters.FindIndex(filter => filter == Path.GetExtension(dialog.FileName)), dialog.FileNames.ToList());
}
else{
callback.Cancel();
}
callback.Dispose();
}
return true;
}
else{
callback.Dispose();
return false;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using CefSharp;
namespace TweetDuck.Core.Handling.General{
sealed class FileDialogHandler : IDialogHandler{
public bool OnFileDialog(IWebBrowser browserControl, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback){
CefFileDialogMode dialogType = mode & CefFileDialogMode.TypeMask;
if (dialogType == CefFileDialogMode.Open || dialogType == CefFileDialogMode.OpenMultiple){
string allFilters = string.Join(";", acceptFilters.Select(filter => "*"+filter));
using(OpenFileDialog dialog = new OpenFileDialog{
AutoUpgradeEnabled = true,
DereferenceLinks = true,
Multiselect = dialogType == CefFileDialogMode.OpenMultiple,
Title = "Open Files",
Filter = $"All Supported Formats ({allFilters})|{allFilters}|All Files (*.*)|*.*"
}){
if (dialog.ShowDialog() == DialogResult.OK){
string ext = Path.GetExtension(dialog.FileName);
callback.Continue(acceptFilters.FindIndex(filter => filter.Equals(ext, StringComparison.OrdinalIgnoreCase)), dialog.FileNames.ToList());
}
else{
callback.Cancel();
}
callback.Dispose();
}
return true;
}
else{
callback.Dispose();
return false;
}
}
}
}
|
Correct builder path - .Net Framework folder starts from "v" | using System;
using System.Diagnostics;
namespace Bridge.Translator
{
public partial class Translator
{
protected static readonly char ps = System.IO.Path.DirectorySeparatorChar;
protected virtual string GetBuilderPath()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return Environment.GetEnvironmentVariable("windir") + ps + "Microsoft.NET" + ps + "Framework" + ps +
this.MSBuildVersion + ps + "msbuild";
default:
throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform);
}
}
protected virtual string GetBuilderArguments()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return String.Format(" \"{0}\" /t:Rebuild /p:Configuation={1}", Location, this.Configuration);
default:
throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform);
}
}
protected virtual void BuildAssembly()
{
var info = new ProcessStartInfo()
{
FileName = this.GetBuilderPath(),
Arguments = this.GetBuilderArguments()
};
info.WindowStyle = ProcessWindowStyle.Hidden;
using (var p = Process.Start(info))
{
p.WaitForExit();
if (p.ExitCode != 0)
{
Bridge.Translator.Exception.Throw("Compilation was not successful, exit code - " + p.ExitCode);
}
}
}
}
}
| using System;
using System.Diagnostics;
namespace Bridge.Translator
{
public partial class Translator
{
protected static readonly char ps = System.IO.Path.DirectorySeparatorChar;
protected virtual string GetBuilderPath()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return Environment.GetEnvironmentVariable("windir") + ps + "Microsoft.NET" + ps + "Framework" + ps +
"v" + this.MSBuildVersion + ps + "msbuild";
default:
throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform);
}
}
protected virtual string GetBuilderArguments()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
return String.Format(" \"{0}\" /t:Rebuild /p:Configuation={1}", Location, this.Configuration);
default:
throw (Exception)Bridge.Translator.Exception.Create("Unsupported platform - {0}", Environment.OSVersion.Platform);
}
}
protected virtual void BuildAssembly()
{
var info = new ProcessStartInfo()
{
FileName = this.GetBuilderPath(),
Arguments = this.GetBuilderArguments(),
UseShellExecute = true
};
info.WindowStyle = ProcessWindowStyle.Hidden;
using (var p = Process.Start(info))
{
p.WaitForExit();
if (p.ExitCode != 0)
{
Bridge.Translator.Exception.Throw("Compilation was not successful, exit code - " + p.ExitCode);
}
}
}
}
}
|
Fix for assuming any legacy call is 32-bit | namespace RedGate.AppHost.Server
{
public class ChildProcessFactory
{
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit, bool monitorHostProcess)
{
IProcessStartOperation processStarter;
if (is64Bit)
{
processStarter = new ProcessStarter64Bit();
}
else
{
processStarter = new ProcessStarter32Bit();
}
return new RemotedProcessBootstrapper(
new StartProcessWithTimeout(
new StartProcessWithJobSupport(
processStarter))).Create(assemblyName, openDebugConsole, monitorHostProcess);
}
// the methods below are to support legacy versions of the API to the Create() method
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit)
{
return Create(assemblyName, openDebugConsole, false, false);
}
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole)
{
return Create(assemblyName, openDebugConsole, false);
}
public IChildProcessHandle Create(string assemblyName)
{
return Create(assemblyName, false, false);
}
}
}
| namespace RedGate.AppHost.Server
{
public class ChildProcessFactory
{
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit, bool monitorHostProcess)
{
IProcessStartOperation processStarter;
if (is64Bit)
{
processStarter = new ProcessStarter64Bit();
}
else
{
processStarter = new ProcessStarter32Bit();
}
return new RemotedProcessBootstrapper(
new StartProcessWithTimeout(
new StartProcessWithJobSupport(
processStarter))).Create(assemblyName, openDebugConsole, monitorHostProcess);
}
// the methods below are to support legacy versions of the API to the Create() method
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole, bool is64Bit)
{
return Create(assemblyName, openDebugConsole, is64Bit, false);
}
public IChildProcessHandle Create(string assemblyName, bool openDebugConsole)
{
return Create(assemblyName, openDebugConsole, false);
}
public IChildProcessHandle Create(string assemblyName)
{
return Create(assemblyName, false, false);
}
}
}
|
Use of metadata proxies to generate table. | using System.Text;
using Models = EntityCore.Initialization.Metadata.Models;
namespace EntityCore.DynamicEntity
{
internal class EntityDatabaseStructure
{
public static string GenerateCreateTableSqlQuery(Models.Entity entity)
{
var createTable = new StringBuilder();
createTable.AppendFormat("CREATE TABLE [{0}] (Id int IDENTITY(1,1) NOT NULL, ", entity.Name);
foreach (var attribute in entity.Attributes)
{
createTable.AppendFormat("{0} {1}{2} {3} {4}, ", attribute.Name,
attribute.Type.SqlServerName,
attribute.Length == null ? string.Empty : "(" + attribute.Length.ToString() + ")",
attribute.IsNullable ? "NULL" : string.Empty,
attribute.DefaultValue != null ? "DEFAULT(" + attribute.DefaultValue + ")" : string.Empty);
}
createTable.AppendFormat("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED", entity.Name);
createTable.AppendFormat("(Id ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF," +
"ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
return createTable.ToString();
}
}
}
| using EntityCore.Proxy.Metadata;
using System.Text;
namespace EntityCore.DynamicEntity
{
internal class EntityDatabaseStructure
{
public static string GenerateCreateTableSqlQuery(IEntity entity)
{
var createTable = new StringBuilder();
createTable.AppendFormat("CREATE TABLE [{0}] (Id int IDENTITY(1,1) NOT NULL, ", entity.Name);
foreach (var attribute in entity.Attributes)
{
createTable.AppendFormat("{0} {1}{2} {3} {4}, ", attribute.Name,
attribute.Type.SqlServerName,
attribute.Length == null ? string.Empty : "(" + attribute.Length.ToString() + ")",
(attribute.IsNullable ?? true) ? "NULL" : string.Empty,
attribute.DefaultValue != null ? "DEFAULT(" + attribute.DefaultValue + ")" : string.Empty);
}
createTable.AppendFormat("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED", entity.Name);
createTable.AppendFormat("(Id ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF," +
"ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
return createTable.ToString();
}
}
}
|
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;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Configuration")]
[assembly: AssemblyDescription("Autofac XML Configuration Support")]
[assembly: InternalsVisibleTo("Autofac.Tests.Configuration, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Configuration")]
[assembly: InternalsVisibleTo("Autofac.Tests.Configuration, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
|
Update deprecated code in iOS main entry | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using UIKit;
namespace osu.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, "GameUIApplication", "AppDelegate");
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.iOS;
using UIKit;
namespace osu.iOS
{
public static class Application
{
public static void Main(string[] args)
{
UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
}
}
}
|
Update assembly info for development of the next version | 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("AltFunding")]
[assembly: AssemblyDescription("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AltFunding")]
[assembly: AssemblyCopyright("Copyright © 2016 nanathan")]
[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("2c84adb4-a8b2-453a-941a-dca4e9383182")]
// 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("0.1")]
[assembly: AssemblyFileVersion("0.1.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("AltFunding")]
[assembly: AssemblyDescription("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AltFunding")]
[assembly: AssemblyCopyright("Copyright © 2016 nanathan")]
[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("2c84adb4-a8b2-453a-941a-dca4e9383182")]
// 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("0.2")]
[assembly: AssemblyFileVersion("0.2.0")]
|
Add credentials class for user authorization | using System;
using Microsoft.SPOT;
namespace Idiot.Net
{
class Credentials
{
}
}
| using System;
using Microsoft.SPOT;
using System.Text;
using GHIElectronics.NETMF.Net;
namespace Idiot.Net
{
public class Credentials
{
private string username;
private string password;
public Credentials(string username, string password)
{
this.username = username;
this.password = password;
this.AuthorizationHeader = this.toAuthorizationHeader();
}
/// <summary>
/// Basic authorization header value to be used for server authentication
/// </summary>
public string AuthorizationHeader { get; private set; }
private string toAuthorizationHeader()
{
return "Basic " + ConvertBase64.ToBase64String(Encoding.UTF8.GetBytes(this.username + ":" + this.password));
}
}
}
|
Remove use of obsolete function | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class DriftUe4PluginServerTarget : TargetRules
{
public DriftUe4PluginServerTarget(TargetInfo Target)
{
Type = TargetType.Server;
}
//
// TargetRules interface.
//
public override void SetupBinaries(
TargetInfo Target,
ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
ref List<string> OutExtraModuleNames
)
{
base.SetupBinaries(Target, ref OutBuildBinaryConfigurations, ref OutExtraModuleNames);
OutExtraModuleNames.Add("DriftUe4Plugin");
}
public override bool GetSupportedPlatforms(ref List<UnrealTargetPlatform> OutPlatforms)
{
// It is valid for only server platforms
return UnrealBuildTool.UnrealBuildTool.GetAllServerPlatforms(ref OutPlatforms, false);
}
}
| // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class DriftUe4PluginServerTarget : TargetRules
{
public DriftUe4PluginServerTarget(TargetInfo Target)
{
Type = TargetType.Server;
}
//
// TargetRules interface.
//
public override void SetupBinaries(
TargetInfo Target,
ref List<UEBuildBinaryConfiguration> OutBuildBinaryConfigurations,
ref List<string> OutExtraModuleNames
)
{
base.SetupBinaries(Target, ref OutBuildBinaryConfigurations, ref OutExtraModuleNames);
OutExtraModuleNames.Add("DriftUe4Plugin");
}
}
|
Add beginnings of a method to parse TMD files | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LBD2OBJ
{
class Program
{
static void Main(string[] args)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using LBD2OBJ.Types;
namespace LBD2OBJ
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("LBD2OBJ - Made by Figglewatts 2015");
foreach (string arg in args)
{
if (Path.GetExtension(arg).ToLower().Equals("tmd"))
{
// convert from tmd
}
else if (Path.GetExtension(arg).ToLower().Equals("lbd"))
{
// convert from lbd
}
else
{
Console.WriteLine("Invalid input file. Extension: {0} not recognized.", Path.GetExtension(arg));
}
}
Console.Write("Press ENTER to exit...");
Console.ReadLine();
}
public static void ConvertTMD(string path)
{
Console.WriteLine("Converting TMD...");
TMD tmd;
bool fixP; // if true, pointers are fixed i.e. non-relative
using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
{
tmd.header = readHeader(b);
fixP = (tmd.header.flags & 1) == 1 ? true : false;
tmd.objTable = new OBJECT[tmd.header.numObjects];
for (int i = 0; i < tmd.header.numObjects; i++)
{
tmd.objTable[i] = readObject(b);
}
}
}
private static TMDHEADER readHeader(BinaryReader b)
{
TMDHEADER tmdHeader;
tmdHeader.ID = b.ReadUInt32();
tmdHeader.flags = b.ReadUInt32();
tmdHeader.numObjects = b.ReadUInt32();
return tmdHeader;
}
private static OBJECT readObject(BinaryReader b)
{
OBJECT obj;
obj.vertTop = b.ReadUInt32();
obj.numVerts = b.ReadUInt32();
obj.normTop = b.ReadUInt32();
obj.numNorms = b.ReadUInt32();
obj.primTop = b.ReadUInt32();
obj.numPrims = b.ReadUInt32();
obj.scale = b.ReadInt32();
return obj;
}
}
}
|
Allow publish without outputting a .md file | using System;
namespace GitReleaseNotes
{
public class ArgumentVerifier
{
public static bool VerifyArguments(GitReleaseNotesArguments arguments)
{
if (arguments.IssueTracker == null)
{
Console.WriteLine("The IssueTracker argument must be provided, see help (/?) for possible options");
{
return false;
}
}
if (string.IsNullOrEmpty(arguments.OutputFile) || !arguments.OutputFile.EndsWith(".md"))
{
Console.WriteLine("Specify an output file (*.md) [/OutputFile ...]");
{
return false;
}
}
return true;
}
}
} | using System;
namespace GitReleaseNotes
{
public class ArgumentVerifier
{
public static bool VerifyArguments(GitReleaseNotesArguments arguments)
{
if (arguments.IssueTracker == null)
{
Console.WriteLine("The IssueTracker argument must be provided, see help (/?) for possible options");
{
return false;
}
}
if ((string.IsNullOrEmpty(arguments.OutputFile) || !arguments.OutputFile.EndsWith(".md")) && !arguments.Publish)
{
Console.WriteLine("Specify an output file (*.md) [/OutputFile ...]");
{
return false;
}
}
return true;
}
}
} |
Add Ids to footer links | @model SiteOptions
<hr />
<footer>
<p>
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
| Built from
<a id="link-git" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub">
@string.Join(string.Empty, GitMetadata.Commit.Take(7))
</a>
on
<a href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub">
@GitMetadata.Branch
</a>
| Sponsored by
<a id="link-browserstack" href="https://www.browserstack.com/">
<noscript>
<img src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" />
</noscript>
<lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" />
</a>
</p>
</footer>
| @model SiteOptions
<hr />
<footer>
<p>
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
| Built from
<a id="link-git-commit" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub">
@string.Join(string.Empty, GitMetadata.Commit.Take(7))
</a>
on
<a id="link-git-branch" href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub">
@GitMetadata.Branch
</a>
| Sponsored by
<a id="link-browserstack" href="https://www.browserstack.com/">
<noscript>
<img src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" />
</noscript>
<lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" />
</a>
</p>
</footer>
|
Fix casing of warden service. | namespace IronFoundry.Warden.Service
{
public static class Constants
{
public const string DisplayName = "Iron Foundry Warden Service";
public const string ServiceName = "ironfoundry.warden";
}
}
| namespace IronFoundry.Warden.Service
{
public static class Constants
{
public const string DisplayName = "Iron Foundry Warden Service";
public const string ServiceName = "IronFoundry.Warden";
}
}
|
Fix flushing issue and added number of files being processed. | using System;
using System.IO;
using System.Text;
namespace KuduSync.NET
{
public class Logger : IDisposable
{
private const int KeepAliveLogTimeInSeconds = 20;
private int _logCounter = 0;
private StreamWriter _writer;
private int _maxLogLines;
private DateTime _nextLogTime;
/// <summary>
/// Logger class
/// </summary>
/// <param name="maxLogLines">sets the verbosity, 0 is verbose, less is quiet, more is the number of maximum log lines to write.</param>
public Logger(int maxLogLines)
{
var stream = Console.OpenStandardOutput();
_writer = new StreamWriter(stream);
_maxLogLines = maxLogLines;
}
public void Log(string format, params object[] args)
{
if (_maxLogLines == 0 || _logCounter < _maxLogLines)
{
_writer.WriteLine(format, args);
}
else if (_logCounter == _maxLogLines)
{
_writer.WriteLine("Omitting next output lines...");
}
else
{
// Make sure some output is still logged every 20 seconds
if (DateTime.Now >= _nextLogTime)
{
_writer.WriteLine("Working...");
_nextLogTime = DateTime.Now.Add(TimeSpan.FromSeconds(KeepAliveLogTimeInSeconds));
}
}
_logCounter++;
}
public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
}
}
}
| using System;
using System.IO;
using System.Text;
namespace KuduSync.NET
{
public class Logger : IDisposable
{
private const int KeepAliveLogTimeInSeconds = 20;
private int _logCounter = 0;
private StreamWriter _writer;
private int _maxLogLines;
private DateTime _nextLogTime;
/// <summary>
/// Logger class
/// </summary>
/// <param name="maxLogLines">sets the verbosity, 0 is verbose, less is quiet, more is the number of maximum log lines to write.</param>
public Logger(int maxLogLines)
{
var stream = Console.OpenStandardOutput();
_writer = new StreamWriter(stream);
_maxLogLines = maxLogLines;
}
public void Log(string format, params object[] args)
{
bool logged = false;
if (_maxLogLines == 0 || _logCounter < _maxLogLines)
{
_writer.WriteLine(format, args);
}
else if (_logCounter == _maxLogLines)
{
_writer.WriteLine("Omitting next output lines...");
logged = true;
}
else
{
// Make sure some output is still logged every 20 seconds
if (DateTime.Now >= _nextLogTime)
{
_writer.WriteLine("Processed {0} files...", _logCounter - 1);
logged = true;
}
}
if (logged)
{
_writer.Flush();
_nextLogTime = DateTime.Now.Add(TimeSpan.FromSeconds(KeepAliveLogTimeInSeconds));
}
_logCounter++;
}
public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
}
}
}
|
Remove unnecessary static method IsApplicable | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class Property : IPathElement
{
public static bool IsApplicable(string pathElement)
{
return Regex.IsMatch(pathElement, @"\w+");
}
private string property;
public Property(string property)
{
this.property = property;
}
public object Apply(object target)
{
PropertyInfo p = target.GetType().GetProperty(property);
if (p == null)
throw new ArgumentException($"The property {property} could not be found.");
var result = p.GetValue(target);
return result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class Property : IPathElement
{
private string property;
public Property(string property)
{
this.property = property;
}
public object Apply(object target)
{
PropertyInfo p = target.GetType().GetProperty(property);
if (p == null)
throw new ArgumentException($"The property {property} could not be found.");
var result = p.GetValue(target);
return result;
}
}
}
|
Add more quakes to map effect | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EOLib.IO.Map
{
public enum MapEffect : byte
{
None = 0,
HPDrain = 1,
TPDrain = 2,
Quake = 3
}
} | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
namespace EOLib.IO.Map
{
public enum MapEffect : byte
{
None = 0,
HPDrain = 1,
TPDrain = 2,
Quake1 = 3,
Quake2 = 4,
Quake3 = 5,
Quake4 = 6
}
} |
Return view from index action | using System;
using System.Web.Mvc;
namespace Foo.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Web.Mvc;
namespace Foo.Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
|
Make the ASP.NET demo more interesting | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreMvc.Models;
using Ooui;
using Ooui.AspNetCore;
namespace AspNetCoreMvc.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
var element = new Label { Text = "Hello Oooooui from Controller" };
return new ElementResult (element);
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreMvc.Models;
using Ooui;
using Ooui.AspNetCore;
namespace AspNetCoreMvc.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
var count = 0;
var head = new Heading { Text = "Ooui!" };
var label = new Label { Text = "0" };
var btn = new Button { Text = "Increase" };
btn.Clicked += (sender, e) => {
count++;
label.Text = count.ToString ();
};
var div = new Div ();
div.AppendChild (head);
div.AppendChild (label);
div.AppendChild (btn);
return new ElementResult (div);
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
Fix broken fail judgement test | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneFailJudgement : TestSceneAllRulesetPlayers
{
protected override Player CreatePlayer(Ruleset ruleset)
{
SelectedMods.Value = Array.Empty<Mod>();
return new FailPlayer();
}
protected override void AddCheckSteps()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for multiple judged objects", () => ((FailPlayer)Player).DrawableRuleset.Playfield.AllHitObjects.Count(h => h.AllJudged) > 1);
AddAssert("total judgements == 1", () => ((FailPlayer)Player).HealthProcessor.JudgedHits >= 1);
}
private class FailPlayer : TestPlayer
{
public new HealthProcessor HealthProcessor => base.HealthProcessor;
public FailPlayer()
: base(false, false)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
HealthProcessor.FailConditions += (_, __) => 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.
using System;
using System.Linq;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneFailJudgement : TestSceneAllRulesetPlayers
{
protected override Player CreatePlayer(Ruleset ruleset)
{
SelectedMods.Value = Array.Empty<Mod>();
return new FailPlayer();
}
protected override void AddCheckSteps()
{
AddUntilStep("wait for fail", () => Player.HasFailed);
AddUntilStep("wait for multiple judgements", () => ((FailPlayer)Player).ScoreProcessor.JudgedHits > 1);
AddAssert("total number of results == 1", () =>
{
var score = new ScoreInfo();
((FailPlayer)Player).ScoreProcessor.PopulateScore(score);
return score.Statistics.Values.Sum() == 1;
});
}
private class FailPlayer : TestPlayer
{
public new HealthProcessor HealthProcessor => base.HealthProcessor;
public FailPlayer()
: base(false, false)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
HealthProcessor.FailConditions += (_, __) => true;
}
}
}
}
|
Make sure you run the log after qemu starts... But it works. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Cosmos.Kernel.LogTail
{
public class ErrorStrippingFileStream : FileStream
{
public ErrorStrippingFileStream(string file)
: base(file, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete | FileShare.ReadWrite)
{
}
public override int ReadByte()
{
int result;
while ((result = base.ReadByte()) == 0) ;
return result;
}
public override int Read(byte[] array, int offset, int count)
{
int i;
for (i = 0; i < count; i++)
{
int b = ReadByte();
if (b == -1)
return i;
array[offset + i] = (byte) b;
}
return i;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Cosmos.Kernel.LogTail
{
public class ErrorStrippingFileStream : FileStream
{
public ErrorStrippingFileStream(string file)
: base(file, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)
{
}
public override int ReadByte()
{
int result;
while ((result = base.ReadByte()) == 0) ;
return result;
}
public override int Read(byte[] array, int offset, int count)
{
int i;
for (i = 0; i < count; i++)
{
int b = ReadByte();
if (b == -1)
return i;
array[offset + i] = (byte) b;
}
return i;
}
}
}
|
Revert "Switch Guid implementation temporarily to avoid compile time error" | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Input.Bindings;
using osu.Game.Database;
using Realms;
namespace osu.Game.Input.Bindings
{
[MapTo(nameof(KeyBinding))]
public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding
{
[PrimaryKey]
public string StringGuid { get; set; }
[Ignored]
public Guid ID
{
get => Guid.Parse(StringGuid);
set => StringGuid = value.ToString();
}
public int? RulesetID { get; set; }
public int? Variant { get; set; }
public KeyCombination KeyCombination
{
get => KeyCombinationString;
set => KeyCombinationString = value.ToString();
}
public object Action
{
get => ActionInt;
set => ActionInt = (int)value;
}
[MapTo(nameof(Action))]
public int ActionInt { get; set; }
[MapTo(nameof(KeyCombination))]
public string KeyCombinationString { get; set; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Input.Bindings;
using osu.Game.Database;
using Realms;
namespace osu.Game.Input.Bindings
{
[MapTo(nameof(KeyBinding))]
public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding
{
[PrimaryKey]
public Guid ID { get; set; }
public int? RulesetID { get; set; }
public int? Variant { get; set; }
public KeyCombination KeyCombination
{
get => KeyCombinationString;
set => KeyCombinationString = value.ToString();
}
public object Action
{
get => ActionInt;
set => ActionInt = (int)value;
}
[MapTo(nameof(Action))]
public int ActionInt { get; set; }
[MapTo(nameof(KeyCombination))]
public string KeyCombinationString { get; set; }
}
}
|
Fix non-generic dictionary serializer does not pack key value pair correctly. | using System;
using System.Collections;
namespace MsgPack.Serialization.DefaultSerializers
{
/// <summary>
/// Dictionary interface serializer.
/// </summary>
internal sealed class NonGenericDictionarySerializer : MessagePackSerializer<IDictionary>
{
private readonly System_Collections_DictionaryEntryMessagePackSerializer _entrySerializer;
private readonly IMessagePackSerializer _collectionDeserializer;
public NonGenericDictionarySerializer( SerializationContext ownerContext, Type targetType )
: base( ownerContext )
{
this._entrySerializer = new System_Collections_DictionaryEntryMessagePackSerializer( ownerContext );
this._collectionDeserializer = ownerContext.GetSerializer( targetType );
}
protected internal override void PackToCore( Packer packer, IDictionary objectTree )
{
packer.PackMapHeader( objectTree.Count );
foreach ( DictionaryEntry item in objectTree )
{
this._entrySerializer.PackToCore( packer, item );
}
}
protected internal override IDictionary UnpackFromCore( Unpacker unpacker )
{
return this._collectionDeserializer.UnpackFrom( unpacker ) as IDictionary;
}
}
} | using System;
using System.Collections;
using System.Runtime.Serialization;
namespace MsgPack.Serialization.DefaultSerializers
{
/// <summary>
/// Dictionary interface serializer.
/// </summary>
internal sealed class NonGenericDictionarySerializer : MessagePackSerializer<IDictionary>
{
private readonly IMessagePackSerializer _collectionDeserializer;
public NonGenericDictionarySerializer( SerializationContext ownerContext, Type targetType )
: base( ownerContext )
{
this._collectionDeserializer = ownerContext.GetSerializer( targetType );
}
protected internal override void PackToCore( Packer packer, IDictionary objectTree )
{
packer.PackMapHeader( objectTree.Count );
foreach ( DictionaryEntry item in objectTree )
{
if ( !( item.Key is MessagePackObject ) )
{
throw new SerializationException("Non generic dictionary may contain only MessagePackObject typed key.");
}
( item.Key as IPackable ).PackToMessage( packer, null );
if ( !( item.Value is MessagePackObject ) )
{
throw new SerializationException("Non generic dictionary may contain only MessagePackObject typed value.");
}
( item.Value as IPackable ).PackToMessage( packer, null ); }
}
protected internal override IDictionary UnpackFromCore( Unpacker unpacker )
{
return this._collectionDeserializer.UnpackFrom( unpacker ) as IDictionary;
}
}
} |
Add 10s delay for always failing worker | using BackOffice.Jobs.Interfaces;
using BackOffice.Jobs.Reports;
using System;
namespace BackOffice.Worker
{
public class CProductAlwaysFailingReportWorker : IJobWorker
{
private readonly AlwaysFailingReport report;
public CProductAlwaysFailingReportWorker(AlwaysFailingReport report)
{
this.report = report;
}
public void Start()
{
throw new NotImplementedException();
}
}
}
| using BackOffice.Jobs.Interfaces;
using BackOffice.Jobs.Reports;
using System;
using System.Threading;
namespace BackOffice.Worker
{
public class CProductAlwaysFailingReportWorker : IJobWorker
{
private readonly AlwaysFailingReport report;
public CProductAlwaysFailingReportWorker(AlwaysFailingReport report)
{
this.report = report;
}
public void Start()
{
Thread.Sleep(10 * 1000);
throw new NotImplementedException();
}
}
}
|
Make the discovery context null tests pass. | namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
throw new NotImplementedException();
}
}
} | namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
else if (discoveryContext == null)
{
throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null.");
}
throw new NotImplementedException();
}
}
} |
Reduce memory usage by using a hashset instead of a list | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Moq.Proxy
{
public class ProxyDiscoverer
{
public async Task<IImmutableSet<ImmutableArray<ITypeSymbol>>> DiscoverProxiesAsync(Project project, CancellationToken cancellationToken = default(CancellationToken))
{
var discoverer = project.LanguageServices.GetRequiredService<IProxyDiscoverer>();
var compilation = await project.GetCompilationAsync(cancellationToken);
var proxyGeneratorSymbol = compilation.GetTypeByMetadataName(typeof(ProxyGeneratorAttribute).FullName);
// TODO: message.
if (proxyGeneratorSymbol == null)
throw new InvalidOperationException();
var proxies = new List<ImmutableArray<ITypeSymbol>>();
foreach (var document in project.Documents)
{
var discovered = await discoverer.DiscoverProxiesAsync(document, proxyGeneratorSymbol, cancellationToken);
proxies.AddRange(discovered);
}
return proxies.ToImmutableHashSet(StructuralComparer<ImmutableArray<ITypeSymbol>>.Default);
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Moq.Proxy
{
public class ProxyDiscoverer
{
public async Task<IImmutableSet<ImmutableArray<ITypeSymbol>>> DiscoverProxiesAsync(Project project, CancellationToken cancellationToken = default(CancellationToken))
{
var discoverer = project.LanguageServices.GetRequiredService<IProxyDiscoverer>();
var compilation = await project.GetCompilationAsync(cancellationToken);
var proxyGeneratorSymbol = compilation.GetTypeByMetadataName(typeof(ProxyGeneratorAttribute).FullName);
// TODO: message.
if (proxyGeneratorSymbol == null)
throw new InvalidOperationException();
var proxies = new HashSet<ImmutableArray<ITypeSymbol>>(StructuralComparer<ImmutableArray<ITypeSymbol>>.Default);
foreach (var document in project.Documents)
{
var discovered = await discoverer.DiscoverProxiesAsync(document, proxyGeneratorSymbol, cancellationToken);
foreach (var proxy in discovered)
{
proxies.Add(proxy);
}
}
return proxies.ToImmutableHashSet(StructuralComparer<ImmutableArray<ITypeSymbol>>.Default);
}
}
}
|
Add separator before action item in tool bar | using System.Linq;
using JetBrains.ActionManagement;
using JetBrains.Annotations;
using JetBrains.Application.DataContext;
using JetBrains.ReSharper.Features.Inspections.Actions;
using JetBrains.UI.ActionsRevised;
namespace Roflcopter.Plugin.TodoItems
{
[Action(nameof(TodoItemsCountDummyAction), Id = 944208914)]
public class TodoItemsCountDummyAction : IExecutableAction, IInsertLast<TodoExplorerActionBarActionGroup>
{
public bool Update(IDataContext context, ActionPresentation presentation, [CanBeNull] DelegateUpdate nextUpdate)
{
var todoItemsCountProvider = context.GetComponent<TodoItemsCountProvider>();
var todoItemsCounts = todoItemsCountProvider.TodoItemsCounts;
if (todoItemsCounts == null)
presentation.Text = null;
else
presentation.Text = string.Join(", ", todoItemsCounts.Select(x => $"{x.Definition}: {x.Count}"));
return false;
}
public void Execute(IDataContext context, [CanBeNull] DelegateExecute nextExecute)
{
}
}
}
| using System.Linq;
using JetBrains.ActionManagement;
using JetBrains.Annotations;
using JetBrains.Application.DataContext;
using JetBrains.ReSharper.Features.Inspections.Actions;
using JetBrains.UI.ActionsRevised;
namespace Roflcopter.Plugin.TodoItems
{
[ActionGroup(nameof(TodoItemsCountDummyActionGroup), ActionGroupInsertStyles.Separated, Id = 944208910)]
public class TodoItemsCountDummyActionGroup : IAction, IInsertLast<TodoExplorerActionBarActionGroup>
{
public TodoItemsCountDummyActionGroup(TodoItemsCountDummyAction _)
{
}
}
[Action(nameof(TodoItemsCountDummyAction), Id = 944208920)]
public class TodoItemsCountDummyAction : IExecutableAction
{
public bool Update(IDataContext context, ActionPresentation presentation, [CanBeNull] DelegateUpdate nextUpdate)
{
var todoItemsCountProvider = context.GetComponent<TodoItemsCountProvider>();
var todoItemsCounts = todoItemsCountProvider.TodoItemsCounts;
if (todoItemsCounts == null)
presentation.Text = null;
else
presentation.Text = string.Join(", ", todoItemsCounts.Select(x => $"{x.Definition}: {x.Count}"));
return false;
}
public void Execute(IDataContext context, [CanBeNull] DelegateExecute nextExecute)
{
}
}
}
|
Fix mono bug in the FontHelper class | using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
}
}
}
| using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
Assert.IsTrue(true);
}
}
}
|
Replace the existing ProblemDetailsFactory from MVC | using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;
namespace Hellang.Middleware.ProblemDetails.Mvc
{
public static class MvcBuilderExtensions
{
/// <summary>
/// Adds conventions to turn off MVC's built-in <see cref="ApiBehaviorOptions.ClientErrorMapping"/>,
/// adds a <see cref="ProducesErrorResponseTypeAttribute"/> to all actions with in controllers with an
/// <see cref="ApiControllerAttribute"/> and a result filter that transforms <see cref="ObjectResult"/>
/// containing a <see cref="string"/> to <see cref="ProblemDetails"/> responses.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddProblemDetailsConventions(this IMvcBuilder builder)
{
// Forward the MVC problem details factory registration to the factory used by the middleware.
builder.Services.TryAddSingleton<MvcProblemDetailsFactory>(p => p.GetRequiredService<ProblemDetailsFactory>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<ApiBehaviorOptions>, ProblemDetailsApiBehaviorOptionsSetup>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, ProblemDetailsApplicationModelProvider>());
return builder;
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;
namespace Hellang.Middleware.ProblemDetails.Mvc
{
public static class MvcBuilderExtensions
{
/// <summary>
/// Adds conventions to turn off MVC's built-in <see cref="ApiBehaviorOptions.ClientErrorMapping"/>,
/// adds a <see cref="ProducesErrorResponseTypeAttribute"/> to all actions with in controllers with an
/// <see cref="ApiControllerAttribute"/> and a result filter that transforms <see cref="ObjectResult"/>
/// containing a <see cref="string"/> to <see cref="ProblemDetails"/> responses.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddProblemDetailsConventions(this IMvcBuilder builder)
{
// Forward the MVC problem details factory registration to the factory used by the middleware.
builder.Services.Replace(
ServiceDescriptor.Singleton<MvcProblemDetailsFactory>(p => p.GetRequiredService<ProblemDetailsFactory>()));
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<ApiBehaviorOptions>, ProblemDetailsApiBehaviorOptionsSetup>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, ProblemDetailsApplicationModelProvider>());
return builder;
}
}
}
|
Remove dead private and comments | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification
public static class DApplication
{
public static bool Dispatch (IOChannel source, IOCondition condition, IntPtr data)
{
//Console.Error.WriteLine ("Dispatch " + source.UnixFd + " " + condition);
connection.Iterate ();
//Console.Error.WriteLine ("Dispatch done");
return true;
}
public static Connection Connection
{
get {
return connection;
}
}
static Connection connection;
static Bus bus;
public static void Init ()
{
connection = new Connection ();
//ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
//string name = "org.freedesktop.DBus";
/*
bus = connection.GetObject<Bus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.Error.WriteLine ("NameAcquired: " + acquired_name);
};
string myName = bus.Hello ();
Console.Error.WriteLine ("myName: " + myName);
*/
IOChannel channel = new IOChannel ((int)connection.sock.Handle);
IO.AddWatch (channel, IOCondition.In, Dispatch);
}
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification
public static class DApplication
{
public static bool Dispatch (IOChannel source, IOCondition condition, IntPtr data)
{
//Console.Error.WriteLine ("Dispatch " + source.UnixFd + " " + condition);
connection.Iterate ();
//Console.Error.WriteLine ("Dispatch done");
return true;
}
static Connection connection;
public static Connection Connection
{
get {
return connection;
}
}
public static void Init ()
{
connection = new Connection ();
IOChannel channel = new IOChannel ((int)connection.sock.Handle);
IO.AddWatch (channel, IOCondition.In, Dispatch);
}
}
}
|
Make CodeFactor happy at the cost of my own happiness (code unfolding) | using System.Collections.Generic;
using System.Diagnostics;
namespace osu_database_reader.Components.HitObjects
{
public class HitObjectSlider : HitObject
{
public CurveType CurveType;
public List<Vector2> Points = new List<Vector2>(); //does not include initial point!
public int RepeatCount;
public double Length; //seems to be length in o!p, so it doesn't have to be calculated?
public void ParseSliderSegments(string sliderString)
{
string[] split = sliderString.Split('|');
foreach (var s in split) {
if (s.Length == 1) { //curve type
switch (s[0]) {
case 'L': CurveType = CurveType.Linear; break;
case 'C': CurveType = CurveType.Catmull; break;
case 'P': CurveType = CurveType.Perfect; break;
case 'B': CurveType = CurveType.Bezier; break;
}
continue;
}
string[] split2 = s.Split(':');
Debug.Assert(split2.Length == 2);
Points.Add(new Vector2(
int.Parse(split2[0]),
int.Parse(split2[1])));
}
}
}
}
| using System.Collections.Generic;
using System.Diagnostics;
namespace osu_database_reader.Components.HitObjects
{
public class HitObjectSlider : HitObject
{
public CurveType CurveType;
public List<Vector2> Points = new List<Vector2>(); //does not include initial point!
public int RepeatCount;
public double Length; //seems to be length in o!p, so it doesn't have to be calculated?
public void ParseSliderSegments(string sliderString)
{
string[] split = sliderString.Split('|');
foreach (var s in split) {
if (s.Length == 1) { //curve type
switch (s[0]) {
case 'L':
CurveType = CurveType.Linear;
break;
case 'C':
CurveType = CurveType.Catmull;
break;
case 'P':
CurveType = CurveType.Perfect;
break;
case 'B':
CurveType = CurveType.Bezier;
break;
}
continue;
}
string[] split2 = s.Split(':');
Debug.Assert(split2.Length == 2);
Points.Add(new Vector2(
int.Parse(split2[0]),
int.Parse(split2[1])));
}
}
}
}
|
Use separate output directories for debug and release builds | using Cake.Common;
using Cake.Frosting;
namespace Build
{
public sealed class Lifetime : FrostingLifetime<Context>
{
public override void Setup(Context context)
{
context.Configuration = context.Argument("configuration", "Release");
context.BaseDir = context.Environment.WorkingDirectory;
context.SourceDir = context.BaseDir.Combine("src");
context.BuildDir = context.BaseDir.Combine("build");
context.CakeToolsDir = context.BaseDir.Combine("tools/cake");
context.LibraryDir = context.SourceDir.Combine("VGAudio");
context.CliDir = context.SourceDir.Combine("VGAudio.Cli");
context.TestsDir = context.SourceDir.Combine("VGAudio.Tests");
context.BenchmarkDir = context.SourceDir.Combine("VGAudio.Benchmark");
context.UwpDir = context.SourceDir.Combine("VGAudio.Uwp");
context.SlnFile = context.SourceDir.CombineWithFilePath("VGAudio.sln");
context.TestsCsproj = context.TestsDir.CombineWithFilePath("VGAudio.Tests.csproj");
context.PublishDir = context.BaseDir.Combine("Publish");
context.LibraryPublishDir = context.PublishDir.Combine("NuGet");
context.CliPublishDir = context.PublishDir.Combine("cli");
context.UwpPublishDir = context.PublishDir.Combine("uwp");
context.ReleaseCertThumbprint = "2043012AE523F7FA0F77A537387633BEB7A9F4DD";
}
}
} | using Cake.Common;
using Cake.Frosting;
namespace Build
{
public sealed class Lifetime : FrostingLifetime<Context>
{
public override void Setup(Context context)
{
context.Configuration = context.Argument("configuration", "Release");
context.BaseDir = context.Environment.WorkingDirectory;
context.SourceDir = context.BaseDir.Combine("src");
context.BuildDir = context.BaseDir.Combine("build");
context.CakeToolsDir = context.BaseDir.Combine("tools/cake");
context.LibraryDir = context.SourceDir.Combine("VGAudio");
context.CliDir = context.SourceDir.Combine("VGAudio.Cli");
context.TestsDir = context.SourceDir.Combine("VGAudio.Tests");
context.BenchmarkDir = context.SourceDir.Combine("VGAudio.Benchmark");
context.UwpDir = context.SourceDir.Combine("VGAudio.Uwp");
context.SlnFile = context.SourceDir.CombineWithFilePath("VGAudio.sln");
context.TestsCsproj = context.TestsDir.CombineWithFilePath("VGAudio.Tests.csproj");
context.PublishDir = context.BaseDir.Combine($"bin/{(context.IsReleaseBuild ? "release" : "debug")}");
context.LibraryPublishDir = context.PublishDir.Combine("NuGet");
context.CliPublishDir = context.PublishDir.Combine("cli");
context.UwpPublishDir = context.PublishDir.Combine("uwp");
context.ReleaseCertThumbprint = "2043012AE523F7FA0F77A537387633BEB7A9F4DD";
}
}
} |
Fix test in the testproj | namespace testproj
{
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
dotMemory.Check(
memory =>
{
Assert.AreEqual(10, memory.ObjectsCount);
});
}
}
}
| namespace testproj
{
using System;
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
dotMemory.Check(
memory =>
{
var str1 = "1";
var str2 = "2";
var str3 = "3";
Assert.LessOrEqual(2, memory.ObjectsCount);
Console.WriteLine(str1 + str2 + str3);
});
}
}
}
|
Install service with "delayed auto start". | using System.ComponentModel;
using System.ServiceProcess;
using System.Configuration.Install;
namespace Graphite.System
{
public partial class ServiceInstaller
{
private IContainer components = null;
private global::System.ServiceProcess.ServiceInstaller serviceInstaller;
private ServiceProcessInstaller serviceProcessInstaller;
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.serviceInstaller = new global::System.ServiceProcess.ServiceInstaller();
this.serviceProcessInstaller = new ServiceProcessInstaller();
//
// serviceInstaller
//
this.serviceInstaller.Description = "Graphite System Monitoring";
this.serviceInstaller.DisplayName = "Graphite System Monitoring";
this.serviceInstaller.ServiceName = "GraphiteSystemMonitoring";
this.serviceInstaller.StartType = ServiceStartMode.Automatic;
//
// serviceProcessInstaller
//
this.serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.serviceProcessInstaller.Password = null;
this.serviceProcessInstaller.Username = null;
//
// ServiceInstaller
//
this.Installers.AddRange(new Installer[]
{
this.serviceInstaller,
this.serviceProcessInstaller
});
}
}
} | using System.ComponentModel;
using System.ServiceProcess;
using System.Configuration.Install;
namespace Graphite.System
{
public partial class ServiceInstaller
{
private IContainer components = null;
private global::System.ServiceProcess.ServiceInstaller serviceInstaller;
private ServiceProcessInstaller serviceProcessInstaller;
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.serviceInstaller = new global::System.ServiceProcess.ServiceInstaller();
this.serviceProcessInstaller = new ServiceProcessInstaller();
//
// serviceInstaller
//
this.serviceInstaller.Description = "Graphite System Monitoring";
this.serviceInstaller.DisplayName = "Graphite System Monitoring";
this.serviceInstaller.ServiceName = "GraphiteSystemMonitoring";
this.serviceInstaller.StartType = ServiceStartMode.Automatic;
this.serviceInstaller.DelayedAutoStart = true;
//
// serviceProcessInstaller
//
this.serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.serviceProcessInstaller.Password = null;
this.serviceProcessInstaller.Username = null;
//
// ServiceInstaller
//
this.Installers.AddRange(new Installer[]
{
this.serviceInstaller,
this.serviceProcessInstaller
});
}
}
} |
Fix wrong value for the Preview tag. | //
// Nikon3MakerNoteEntryTag.cs:
//
// Author:
// Ruben Vermeersch (ruben@savanne.be)
//
// Copyright (C) 2010 Ruben Vermeersch
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
namespace TagLib.IFD.Tags
{
/// <summary>
/// Nikon format 3 makernote tags.
/// Based on http://www.exiv2.org/tags-nikon.html
/// </summary>
public enum Nikon3MakerNoteEntryTag : ushort
{
/// <summary>
/// Offset to an IFD containing a preview image. (Hex: 0x0011)
/// </summary>
Preview = 16,
}
}
| //
// Nikon3MakerNoteEntryTag.cs:
//
// Author:
// Ruben Vermeersch (ruben@savanne.be)
//
// Copyright (C) 2010 Ruben Vermeersch
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
namespace TagLib.IFD.Tags
{
/// <summary>
/// Nikon format 3 makernote tags.
/// Based on http://www.exiv2.org/tags-nikon.html
/// </summary>
public enum Nikon3MakerNoteEntryTag : ushort
{
/// <summary>
/// Offset to an IFD containing a preview image. (Hex: 0x0011)
/// </summary>
Preview = 17,
}
}
|
Change version number to 1.1 | 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("IS24RestApi")]
[assembly: AssemblyDescription("Client for the Immobilienscout24 REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Ganss")]
[assembly: AssemblyProduct("IS24RestApi")]
[assembly: AssemblyCopyright("Copyright © 2013 IS24RestApi project contributors")]
[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("ce77545e-5fbe-4b4d-bf1f-1c5d4532070a")]
// 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.*")]
| 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("IS24RestApi")]
[assembly: AssemblyDescription("Client for the Immobilienscout24 REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Ganss")]
[assembly: AssemblyProduct("IS24RestApi")]
[assembly: AssemblyCopyright("Copyright © 2013 IS24RestApi project contributors")]
[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("ce77545e-5fbe-4b4d-bf1f-1c5d4532070a")]
// 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.1.*")]
|
Fix error with multithreaded UniversalDetector reseting | using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dokas.FluentStrings;
using Mozilla.CharDet;
namespace dokas.EncodingConverter.Logic
{
internal sealed class EncodingManager
{
private readonly FileManager _fileManager;
private static readonly IEnumerable<Encoding> _encodings;
private static readonly UniversalDetector _detector;
static EncodingManager()
{
_encodings = Encoding.GetEncodings().Select(e => e.GetEncoding()).ToArray();
_detector = new UniversalDetector();
}
public static IEnumerable<Encoding> Encodings
{
get { return _encodings; }
}
public EncodingManager(FileManager fileManager)
{
_fileManager = fileManager;
}
public async Task<Encoding> Resolve(string filePath)
{
_detector.Reset();
await Task.Factory.StartNew(() =>
{
var bytes = _fileManager.Load(filePath);
_detector.HandleData(bytes);
});
return !_detector.DetectedCharsetName.IsEmpty() ? Encoding.GetEncoding(_detector.DetectedCharsetName) : null;
}
public void Convert(string filePath, Encoding from, Encoding to)
{
var bytes = _fileManager.Load(filePath);
var convertedBytes = Encoding.Convert(from, to, bytes);
_fileManager.Save(filePath, convertedBytes);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dokas.FluentStrings;
using Mozilla.CharDet;
namespace dokas.EncodingConverter.Logic
{
internal sealed class EncodingManager
{
private readonly FileManager _fileManager;
private static readonly IEnumerable<Encoding> _encodings;
static EncodingManager()
{
_encodings = Encoding.GetEncodings().Select(e => e.GetEncoding()).ToArray();
}
public static IEnumerable<Encoding> Encodings
{
get { return _encodings; }
}
public EncodingManager(FileManager fileManager)
{
_fileManager = fileManager;
}
public async Task<Encoding> Resolve(string filePath)
{
UniversalDetector detector = null;
await Task.Factory.StartNew(() =>
{
var bytes = _fileManager.Load(filePath);
detector = new UniversalDetector();
detector.HandleData(bytes);
});
return !detector.DetectedCharsetName.IsEmpty() ? Encoding.GetEncoding(detector.DetectedCharsetName) : null;
}
public void Convert(string filePath, Encoding from, Encoding to)
{
if (from == null)
{
throw new ArgumentOutOfRangeException("from");
}
if (to == null)
{
throw new ArgumentOutOfRangeException("to");
}
var bytes = _fileManager.Load(filePath);
var convertedBytes = Encoding.Convert(from, to, bytes);
_fileManager.Save(filePath, convertedBytes);
}
}
}
|
Add Neon runtime information to NeonException | using System;
namespace csnex
{
[Serializable()]
public class NeonException: ApplicationException
{
public NeonException() {
}
public NeonException(string message) : base(message) {
}
public NeonException(string message, params object[] args) : base(string.Format(message, args)) {
}
public NeonException(string message, System.Exception innerException) : base(message, innerException) {
}
}
[Serializable]
public class InvalidOpcodeException: NeonException
{
public InvalidOpcodeException() {
}
public InvalidOpcodeException(string message) : base(message) {
}
}
[Serializable]
public class BytecodeException: NeonException
{
public BytecodeException() {
}
public BytecodeException(string message) : base(message) {
}
}
[Serializable]
public class NotImplementedException: NeonException
{
public NotImplementedException() {
}
public NotImplementedException(string message) : base(message) {
}
}
}
| using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace csnex
{
[Serializable()]
public class NeonException: ApplicationException
{
public NeonException() {
}
public NeonException(string name, string info) : base(name) {
Name = name;
Info = info;
}
public NeonException(string message) : base(message) {
}
public NeonException(string message, params object[] args) : base(string.Format(message, args)) {
}
public NeonException(string message, System.Exception innerException) : base(message, innerException) {
}
// Satisfy Warning CA2240 to implement a GetObjectData() to our custom exception type.
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null) {
throw new ArgumentNullException("info");
}
info.AddValue("NeonException", Name);
info.AddValue("NeonInfo", Info);
base.GetObjectData(info, context);
}
public string Name;
public string Info;
}
[Serializable]
public class InvalidOpcodeException: NeonException
{
public InvalidOpcodeException() {
}
public InvalidOpcodeException(string message) : base(message) {
}
}
[Serializable]
public class BytecodeException: NeonException
{
public BytecodeException() {
}
public BytecodeException(string message) : base(message) {
}
}
[Serializable]
public class NotImplementedException: NeonException
{
public NotImplementedException() {
}
public NotImplementedException(string message) : base(message) {
}
}
[Serializable]
public class NeonRuntimeException: NeonException
{
public NeonRuntimeException()
{
}
public NeonRuntimeException(string name, string info) : base(name, info)
{
}
}
}
|
Fix use of private addin registry | using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Addins;
namespace MonoDevelop.Addins.Tasks
{
public abstract class AddinTask : Task
{
[Required]
public string ConfigDir { get; set; }
[Required]
public string AddinsDir { get; set; }
[Required]
public string DatabaseDir { get; set; }
[Required]
public string BinDir { get; set; }
protected bool InitializeAddinRegistry ()
{
if (string.IsNullOrEmpty (ConfigDir))
Log.LogError ("ConfigDir must be specified");
if (string.IsNullOrEmpty (AddinsDir))
Log.LogError ("AddinsDir must be specified");
if (string.IsNullOrEmpty (DatabaseDir))
Log.LogError ("DatabaseDir must be specified");
if (string.IsNullOrEmpty (BinDir))
Log.LogError ("BinDir must be specified");
Registry = new AddinRegistry (
ConfigDir,
BinDir,
AddinsDir,
DatabaseDir
);
Log.LogMessage (MessageImportance.Normal, "Updating addin database at {0}", DatabaseDir);
Registry.Update (new LogProgressStatus (Log, 2));
return !Log.HasLoggedErrors;
}
protected AddinRegistry Registry { get; private set; }
}
}
| using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Addins;
namespace MonoDevelop.Addins.Tasks
{
public abstract class AddinTask : Task
{
[Required]
public string ConfigDir { get; set; }
[Required]
public string AddinsDir { get; set; }
[Required]
public string DatabaseDir { get; set; }
[Required]
public string BinDir { get; set; }
protected bool InitializeAddinRegistry ()
{
if (string.IsNullOrEmpty (ConfigDir))
Log.LogError ("ConfigDir must be specified");
if (string.IsNullOrEmpty (AddinsDir))
Log.LogError ("AddinsDir must be specified");
if (string.IsNullOrEmpty (DatabaseDir))
Log.LogError ("DatabaseDir must be specified");
if (string.IsNullOrEmpty (BinDir))
Log.LogError ("BinDir must be specified");
ConfigDir = Path.GetFullPath (ConfigDir);
BinDir = Path.GetFullPath (BinDir);
AddinsDir = Path.GetFullPath (AddinsDir);
DatabaseDir = Path.GetFullPath (DatabaseDir);
Registry = new AddinRegistry (
ConfigDir,
BinDir,
AddinsDir,
DatabaseDir
);
Log.LogMessage (MessageImportance.Normal, "Updating addin database at {0}", DatabaseDir);
Registry.Update (new LogProgressStatus (Log, 2));
return !Log.HasLoggedErrors;
}
protected AddinRegistry Registry { get; private set; }
}
}
|
Support fields and highlights in responses | using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace NElasticsearch.Models
{
/// <summary>
/// Individual hit response from ElasticSearch.
/// </summary>
[DebuggerDisplay("{_type} in {_index} id {_id}")]
public class Hit<T>
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public double? _score { get; set; }
public T _source { get; set; }
//public Dictionary<String, JToken> fields = new Dictionary<string, JToken>();
}
}
| using System.Collections.Generic;
using System.Diagnostics;
namespace NElasticsearch.Models
{
/// <summary>
/// Individual hit response from ElasticSearch.
/// </summary>
[DebuggerDisplay("{_type} in {_index} id {_id}")]
public class Hit<T>
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public double? _score { get; set; }
public T _source { get; set; }
public Dictionary<string, IEnumerable<object>> fields = new Dictionary<string, IEnumerable<object>>();
public Dictionary<string, IEnumerable<string>> highlight;
}
}
|
Update local echo server to work with binary messages | using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wslib;
using wslib.Protocol;
namespace LocalServer
{
class Program
{
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += LogUnobservedTaskException;
var listenerOptions = new WebSocketListenerOptions { Endpoint = new IPEndPoint(IPAddress.Loopback, 8080) };
using (var listener = new WebSocketListener(listenerOptions, appFunc))
{
listener.StartAccepting();
Console.ReadLine();
}
}
private static void LogUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
throw new NotImplementedException(); // TODO: log
}
private static async Task appFunc(IWebSocket webSocket)
{
while (webSocket.IsConnected())
{
using (var msg = await webSocket.ReadMessageAsync(CancellationToken.None))
{
if (msg != null)
{
using (var ms = new MemoryStream())
{
await msg.ReadStream.CopyToAsync(ms);
var text = Encoding.UTF8.GetString(ms.ToArray());
using (var w = await webSocket.CreateMessageWriter(MessageType.Text, CancellationToken.None))
{
await w.WriteMessageAsync(ms.ToArray(), 0, (int)ms.Length, CancellationToken.None);
}
}
}
}
}
}
}
} | using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using wslib;
namespace LocalServer
{
class Program
{
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += LogUnobservedTaskException;
var listenerOptions = new WebSocketListenerOptions { Endpoint = new IPEndPoint(IPAddress.Loopback, 8080) };
using (var listener = new WebSocketListener(listenerOptions, appFunc))
{
listener.StartAccepting();
Console.ReadLine();
}
}
private static void LogUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
//Console.WriteLine(unobservedTaskExceptionEventArgs.Exception);
}
private static async Task appFunc(IWebSocket webSocket)
{
while (webSocket.IsConnected())
{
using (var msg = await webSocket.ReadMessageAsync(CancellationToken.None))
{
if (msg == null) continue;
using (var ms = new MemoryStream())
{
await msg.ReadStream.CopyToAsync(ms);
byte[] array = ms.ToArray();
using (var w = await webSocket.CreateMessageWriter(msg.Type, CancellationToken.None))
{
await w.WriteMessageAsync(array, 0, array.Length, CancellationToken.None);
}
}
}
}
}
}
} |
Set Treenumerable version to 1.0.0 | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Toshiba")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Toshiba 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Toshiba")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Toshiba 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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")]
[assembly: AssemblyFileVersion("1.0.0")]
|
Add flow tree body to the function | namespace UnwindMC.Analysis
{
public class Function
{
public Function(ulong address)
{
Address = address;
Status = FunctionStatus.Created;
}
public ulong Address { get; }
public FunctionStatus Status { get; set; }
}
public enum FunctionStatus
{
Created,
BoundsResolved,
BoundsNotResolvedInvalidAddress,
BoundsNotResolvedIncompleteGraph,
}
}
| using System;
using System.Collections.Generic;
using UnwindMC.Analysis.Flow;
using UnwindMC.Analysis.IL;
namespace UnwindMC.Analysis
{
public class Function
{
private List<IBlock> _blocks;
public Function(ulong address)
{
Address = address;
Status = FunctionStatus.Created;
}
public ulong Address { get; }
public FunctionStatus Status { get; set; }
public IReadOnlyList<IBlock> Blocks => _blocks;
public ILInstruction FirstInstruction
{
get
{
if (_blocks == null || _blocks.Count == 0)
{
return null;
}
var seq = _blocks[0] as SequentialBlock;
if (seq != null)
{
return seq.Instructions[0];
}
var loop = _blocks[0] as LoopBlock;
if (loop != null)
{
return loop.Condition;
}
var cond = _blocks[0] as ConditionalBlock;
if (cond != null)
{
return cond.Condition;
}
throw new InvalidOperationException("Unknown block type");
}
}
public void ResolveBody(InstructionGraph graph)
{
if (Status != FunctionStatus.BoundsResolved)
{
throw new InvalidOperationException("Cannot resolve function body when bounds are not resolved");
}
_blocks = FlowAnalyzer.Analyze(ILDecompiler.Decompile(graph, Address));
Status = FunctionStatus.BodyResolved;
}
}
public enum FunctionStatus
{
Created,
BoundsResolved,
BoundsNotResolvedInvalidAddress,
BoundsNotResolvedIncompleteGraph,
BodyResolved,
}
}
|
Change example to contain default values | using System;
using System.Text;
namespace SCPI.Display
{
public class DISPLAY_GRID : ICommand
{
public string Description => "Set or query the grid type of screen display.";
public string Grid { get; private set; }
private readonly string[] gridRange = new string[] { "FULL", "HALF", "NONE" };
public string Command(params string[] parameters)
{
var cmd = ":DISPlay:GRID";
if (parameters.Length > 0)
{
var grid = parameters[0];
cmd = $"{cmd} {grid}";
}
else
{
cmd += "?";
}
return cmd;
}
public string HelpMessage()
{
var syntax = nameof(DISPLAY_GRID) + "\n" +
nameof(DISPLAY_GRID) + " <grid>";
var parameters = " <grid> = {"+ string.Join("|", gridRange) +"}\n";
var example = "Example: " + nameof(DISPLAY_GRID) + "?";
return $"{syntax}\n{parameters}\n{example}";
}
public bool Parse(byte[] data)
{
if (data != null)
{
Grid = Encoding.ASCII.GetString(data).Trim();
if (Array.Exists(gridRange, g => g.Equals(Grid)))
{
return true;
}
}
Grid = null;
return false;
}
}
}
| using System;
using System.Text;
namespace SCPI.Display
{
public class DISPLAY_GRID : ICommand
{
public string Description => "Set or query the grid type of screen display.";
public string Grid { get; private set; }
private readonly string[] gridRange = new string[] { "FULL", "HALF", "NONE" };
public string Command(params string[] parameters)
{
var cmd = ":DISPlay:GRID";
if (parameters.Length > 0)
{
var grid = parameters[0];
cmd = $"{cmd} {grid}";
}
else
{
cmd += "?";
}
return cmd;
}
public string HelpMessage()
{
var syntax = nameof(DISPLAY_GRID) + "\n" +
nameof(DISPLAY_GRID) + " <grid>";
var parameters = " <grid> = {"+ string.Join("|", gridRange) +"}\n";
var example = "Example: " + nameof(DISPLAY_GRID) + " FULL";
return $"{syntax}\n{parameters}\n{example}";
}
public bool Parse(byte[] data)
{
if (data != null)
{
Grid = Encoding.ASCII.GetString(data).Trim();
if (Array.Exists(gridRange, g => g.Equals(Grid)))
{
return true;
}
}
Grid = null;
return false;
}
}
}
|
Fix BCC for EOI emails | using CroquetAustralia.Domain.Features.TournamentEntry.Events;
namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
public class U21WorldsEOIEmailGenerator : BaseEmailGenerator
{
/* todo: remove hard coding of email addresses */
private static readonly EmailAddress U21Coordinator = new EmailAddress("ndu21c@croquet-australia.com.au", "Croquet Australia - National Co-ordinator Under 21 Croquet");
private static readonly EmailAddress[] BCC =
{
U21Coordinator,
new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia")
};
public U21WorldsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
: base(emailMessageSettings, U21Coordinator, BCC)
{
}
protected override string GetTemplateName(EntrySubmitted entrySubmitted)
{
return "EOI";
}
}
} | using System.Linq;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;
namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
public class U21WorldsEOIEmailGenerator : BaseEmailGenerator
{
/* todo: remove hard coding of email addresses */
private static readonly EmailAddress U21Coordinator = new EmailAddress("ndu21c@croquet-australia.com.au", "Croquet Australia - National Co-ordinator Under 21 Croquet");
private static readonly EmailAddress[] BCC =
{
U21Coordinator,
new EmailAddress("admin@croquet-australia.com.au", "Croquet Australia")
};
public U21WorldsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
: base(emailMessageSettings, U21Coordinator, GetBCC(emailMessageSettings))
{
}
protected override string GetTemplateName(EntrySubmitted entrySubmitted)
{
return "EOI";
}
private static EmailAddress[] GetBCC(EmailMessageSettings emailMessageSettings)
{
return emailMessageSettings.Bcc.Any() ? BCC : new EmailAddress[] {};
}
}
} |
Fix issues due to merge conflict. | namespace TraktApiSharp.Tests
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class TraktConfigurationTests
{
[TestMethod]
public void TestTraktConfigurationDefaultConstructor()
{
var client = new TraktClient();
client.Configuration.ApiVersion.Should().Be(2);
client.Configuration.UseStagingApi.Should().BeFalse();
client.Configuration.BaseUrl.Should().Be("https://api-v2launch.trakt.tv/");
client.Configuration.UseStagingApi = true;
client.Configuration.BaseUrl.Should().Be("https://api-staging.trakt.tv/");
}
}
}
| namespace TraktApiSharp.Tests
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class TraktConfigurationTests
{
[TestMethod]
public void TestTraktConfigurationDefaultConstructor()
{
var client = new TraktClient();
client.Configuration.ApiVersion.Should().Be(2);
client.Configuration.UseStagingUrl.Should().BeFalse();
client.Configuration.BaseUrl.Should().Be("https://api-v2launch.trakt.tv/");
client.Configuration.UseStagingUrl = true;
client.Configuration.BaseUrl.Should().Be("https://api-staging.trakt.tv/");
}
}
}
|
Update ModalitaPagamento validator with MP18..21 values | using BusinessObjects.Validators;
namespace FatturaElettronicaPA.Validators
{
/// <summary>
/// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
/// </summary>
public class FModalitaPagamentoValidator : DomainValidator
{
private const string BrokenDescription = "Valori ammessi [MP01], [MP02], [..], [MP17].";
/// <summary>
/// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
/// </summary>
public FModalitaPagamentoValidator() : this(null, BrokenDescription) { }
public FModalitaPagamentoValidator(string propertyName) : this(propertyName, BrokenDescription) { }
public FModalitaPagamentoValidator(string propertyName, string description) : base(propertyName, description)
{
Domain = new[]
{
"MP01", "MP02", "MP03", "MP04", "MP06", "MP07", "MP08", "MP09", "MP10", "MP11", "MP12", "MP13",
"MP14", "MP15", "MP16", "MP17"
};
}
}
}
| using BusinessObjects.Validators;
namespace FatturaElettronicaPA.Validators
{
/// <summary>
/// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
/// </summary>
public class FModalitaPagamentoValidator : DomainValidator
{
private const string BrokenDescription = "Valori ammessi [MP01], [MP02], [..], [MP21].";
/// <summary>
/// Validates FatturaElettronicaBody.DatiPagamento.DettaglioPagamento.ModalitaPagamento.
/// </summary>
public FModalitaPagamentoValidator() : this(null, BrokenDescription) { }
public FModalitaPagamentoValidator(string propertyName) : this(propertyName, BrokenDescription) { }
public FModalitaPagamentoValidator(string propertyName, string description) : base(propertyName, description)
{
Domain = new[]
{
"MP01", "MP02", "MP03", "MP04", "MP06", "MP07", "MP08", "MP09", "MP10", "MP11", "MP12", "MP13",
"MP14", "MP15", "MP16", "MP17", "MP18", "MP19", "MP20", "MP21"
};
}
}
}
|
Fix MonoMac/MonoTouch (for MonoMac builds) | // Copyright 2013 Xamarin Inc.
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSUrlCredential {
public NSUrlCredential (IntPtr trust, bool ignored) : base (NSObjectFlag.Empty)
{
if (IsDirectBinding) {
Handle = MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithTrust:"), trust);
} else {
Handle = MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithTrust:"), trust);
}
}
}
} | // Copyright 2013 Xamarin Inc.
using System;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSUrlCredential {
public NSUrlCredential (IntPtr trust, bool ignored) : base (NSObjectFlag.Empty)
{
if (IsDirectBinding) {
Handle = Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithTrust:"), trust);
} else {
Handle = Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithTrust:"), trust);
}
}
}
} |
Change "Countdown" syncing priority order | using System;
namespace DesktopWidgets.Helpers
{
public static class DateTimeSyncHelper
{
public static DateTime SyncNext(this DateTime dateTime, bool syncYear, bool syncMonth, bool syncDay,
bool syncHour, bool syncMinute, bool syncSecond)
{
var endDateTime = dateTime;
endDateTime = new DateTime(
syncYear
? DateTime.Now.Year
: endDateTime.Year,
syncMonth
? DateTime.Now.Month
: endDateTime.Month,
syncDay
? DateTime.Now.Day
: endDateTime.Day,
syncHour
? DateTime.Now.Hour
: endDateTime.Hour,
syncMinute
? DateTime.Now.Minute
: endDateTime.Minute,
syncSecond
? DateTime.Now.Second
: endDateTime.Second,
endDateTime.Kind);
if (syncYear && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddYears(1);
if (syncMonth && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddMonths(1);
if (syncDay && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddDays(1);
if (syncHour && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddHours(1);
if (syncMinute && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddMinutes(1);
if (syncSecond && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddSeconds(1);
return endDateTime;
}
}
} | using System;
namespace DesktopWidgets.Helpers
{
public static class DateTimeSyncHelper
{
public static DateTime SyncNext(this DateTime dateTime, bool syncYear, bool syncMonth, bool syncDay,
bool syncHour, bool syncMinute, bool syncSecond)
{
var endDateTime = dateTime;
endDateTime = new DateTime(
syncYear
? DateTime.Now.Year
: endDateTime.Year,
syncMonth
? DateTime.Now.Month
: endDateTime.Month,
syncDay
? DateTime.Now.Day
: endDateTime.Day,
syncHour
? DateTime.Now.Hour
: endDateTime.Hour,
syncMinute
? DateTime.Now.Minute
: endDateTime.Minute,
syncSecond
? DateTime.Now.Second
: endDateTime.Second,
endDateTime.Kind);
if (syncSecond && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddSeconds(1);
if (syncMinute && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddMinutes(1);
if (syncHour && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddHours(1);
if (syncDay && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddDays(1);
if (syncMonth && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddMonths(1);
if (syncYear && endDateTime < DateTime.Now)
endDateTime = endDateTime.AddYears(1);
return endDateTime;
}
}
} |
Add get top to service | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Services.Contracts;
namespace PhotoLife.Services
{
public class PostsService: IPostService
{
private readonly IRepository<Post> postsRepository;
private readonly IUnitOfWork unitOfWork;
public PostsService(
IRepository<Post> postsRepository,
IUnitOfWork unitOfWork)
{
if (postsRepository == null)
{
throw new ArgumentNullException("postsRepository");
}
if (unitOfWork == null)
{
throw new ArgumentNullException("unitOfWorks");
}
this.postsRepository = postsRepository;
this.unitOfWork = unitOfWork;
}
public Post GetPostById(string id)
{
return this.postsRepository.GetById(id);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Services.Contracts;
namespace PhotoLife.Services
{
public class PostsService : IPostService
{
private readonly IRepository<Post> postsRepository;
private readonly IUnitOfWork unitOfWork;
public PostsService(
IRepository<Post> postsRepository,
IUnitOfWork unitOfWork)
{
if (postsRepository == null)
{
throw new ArgumentNullException("postsRepository");
}
if (unitOfWork == null)
{
throw new ArgumentNullException("unitOfWorks");
}
this.postsRepository = postsRepository;
this.unitOfWork = unitOfWork;
}
public Post GetPostById(string id)
{
return this.postsRepository.GetById(id);
}
public IEnumerable<Post> GetTopPosts(int countOfPosts)
{
var res =
this.postsRepository.GetAll(
(Post post) => true,
(Post post) => post.Votes, true)
.Take(countOfPosts);
return res;
}
}
}
|
Use ISO encoding, for cross platform | namespace SilentHunter
{
public static class Encoding
{
/// <summary>
/// The default encoding to use for parsing Silent Hunter game files.
/// </summary>
public static System.Text.Encoding ParseEncoding { get; } = System.Text.Encoding.GetEncoding(1252);
}
} | namespace SilentHunter
{
public static class Encoding
{
/// <summary>
/// The default encoding to use for parsing Silent Hunter game files.
/// </summary>
public static System.Text.Encoding ParseEncoding { get; } = System.Text.Encoding.GetEncoding("ISO-8859-1");
}
} |
Correct to print right result | using MQTTnet.Client.Connecting;
using MQTTnet.Exceptions;
namespace MQTTnet.Adapter
{
public class MqttConnectingFailedException : MqttCommunicationException
{
public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode)
: base($"Connecting with MQTT server failed ({resultCode.ToString()}).")
{
Result = resultCode;
}
public MqttClientAuthenticateResult Result { get; }
public MqttClientConnectResultCode ResultCode => Result.ResultCode;
}
}
| using MQTTnet.Client.Connecting;
using MQTTnet.Exceptions;
namespace MQTTnet.Adapter
{
public class MqttConnectingFailedException : MqttCommunicationException
{
public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode)
: base($"Connecting with MQTT server failed ({resultCode.ResultCode.ToString()}).")
{
Result = resultCode;
}
public MqttClientAuthenticateResult Result { get; }
public MqttClientConnectResultCode ResultCode => Result.ResultCode;
}
}
|
Use more proper name for test | using System;
using Xunit;
namespace CSharpInternals.ExceptionHandling
{
public class Basics
{
[Fact]
public void Test()
{
Assert.Throws<NullReferenceException>(() => ThrowsNullReferenceException());
}
// Fact - ToString allocates a lot, especially with AggregateException
// http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,448
private static void ThrowsNullReferenceException() => throw null;
}
} | using System;
using Xunit;
namespace CSharpInternals.ExceptionHandling
{
public class Basics
{
[Fact]
public void ThrowsNull()
{
Assert.Throws<NullReferenceException>(() => ThrowsNullReferenceException());
}
// Fact - ToString allocates a lot, especially with AggregateException
// http://referencesource.microsoft.com/#mscorlib/system/AggregateException.cs,448
private static void ThrowsNullReferenceException() => throw null;
}
} |
Fix resource leak that occurred when any GFX files were missing from GFX folder | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using PELoaderLib;
namespace EOLib.Graphics
{
public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection
{
public void PopulateCollectionWithStandardGFX()
{
var gfxTypes = Enum.GetValues(typeof(GFXTypes)).OfType<GFXTypes>();
var modules = gfxTypes.ToDictionary(type => type, CreateGFXFile);
foreach(var modulePair in modules)
Add(modulePair.Key, modulePair.Value);
}
private IPEFile CreateGFXFile(GFXTypes file)
{
var number = ((int)file).ToString("D3");
var fName = Path.Combine("gfx", "gfx" + number + ".egf");
return new PEFile(fName);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~PEFileCollection()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
foreach (var pair in this)
pair.Value.Dispose();
}
}
public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable
{
void PopulateCollectionWithStandardGFX();
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using System.Collections.Generic;
using System.IO;
using PELoaderLib;
namespace EOLib.Graphics
{
public sealed class PEFileCollection : Dictionary<GFXTypes, IPEFile>, IPEFileCollection
{
public void PopulateCollectionWithStandardGFX()
{
var gfxTypes = (GFXTypes[])Enum.GetValues(typeof(GFXTypes));
foreach (var type in gfxTypes)
Add(type, CreateGFXFile(type));
}
private IPEFile CreateGFXFile(GFXTypes file)
{
var number = ((int)file).ToString("D3");
var fName = Path.Combine("gfx", "gfx" + number + ".egf");
return new PEFile(fName);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~PEFileCollection()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
foreach (var pair in this)
pair.Value.Dispose();
}
}
public interface IPEFileCollection : IDictionary<GFXTypes, IPEFile>, IDisposable
{
void PopulateCollectionWithStandardGFX();
}
}
|
Remove one more nullable disable | // 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 osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Localisation;
using osu.Game.Overlays.Settings.Sections.Maintenance;
namespace osu.Game.Overlays.Settings.Sections
{
public class MaintenanceSection : SettingsSection
{
public override LocalisableString Header => MaintenanceSettingsStrings.MaintenanceSectionHeader;
public override Drawable CreateIcon() => new SpriteIcon
{
Icon = FontAwesome.Solid.Wrench
};
public MaintenanceSection()
{
Children = new Drawable[]
{
new BeatmapSettings(),
new SkinSettings(),
new CollectionsSettings(),
new ScoreSettings()
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Localisation;
using osu.Game.Overlays.Settings.Sections.Maintenance;
namespace osu.Game.Overlays.Settings.Sections
{
public class MaintenanceSection : SettingsSection
{
public override LocalisableString Header => MaintenanceSettingsStrings.MaintenanceSectionHeader;
public override Drawable CreateIcon() => new SpriteIcon
{
Icon = FontAwesome.Solid.Wrench
};
public MaintenanceSection()
{
Children = new Drawable[]
{
new BeatmapSettings(),
new SkinSettings(),
new CollectionsSettings(),
new ScoreSettings()
};
}
}
}
|
Stop spurious VS "cannot override ExecuteAsync" errors even if you don't specify a base class | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/*
* Currently if you have a .cshtml file in a project with <Project Sdk="Microsoft.NET.Sdk.Web">,
* Visual Studio will run design-time builds for the .cshtml file that assume certain ASP.NET MVC
* APIs exist. Since those namespaces and types wouldn't normally exist for Blazor client apps,
* this leads to spurious errors in the Errors List pane, even though there aren't actually any
* errors on build. As a workaround, we define here a minimal set of namespaces/types that satisfy
* the design-time build.
*
* TODO: Track down what is triggering the unwanted design-time build and find out how to disable it.
* Then this file can be removed entirely.
*/
using System;
namespace Microsoft.AspNetCore.Mvc
{
public interface IUrlHelper { }
public interface IViewComponentHelper { }
}
namespace Microsoft.AspNetCore.Mvc.Razor
{
public class RazorPage<T> { }
namespace Internal
{
public class RazorInjectAttributeAttribute : Attribute { }
}
}
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public interface IJsonHelper { }
public interface IHtmlHelper<T> { }
}
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public interface IModelExpressionProvider { }
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/*
* Currently if you have a .cshtml file in a project with <Project Sdk="Microsoft.NET.Sdk.Web">,
* Visual Studio will run design-time builds for the .cshtml file that assume certain ASP.NET MVC
* APIs exist. Since those namespaces and types wouldn't normally exist for Blazor client apps,
* this leads to spurious errors in the Errors List pane, even though there aren't actually any
* errors on build. As a workaround, we define here a minimal set of namespaces/types that satisfy
* the design-time build.
*
* TODO: Track down what is triggering the unwanted design-time build and find out how to disable it.
* Then this file can be removed entirely.
*/
using System;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Mvc
{
public interface IUrlHelper { }
public interface IViewComponentHelper { }
}
namespace Microsoft.AspNetCore.Mvc.Razor
{
public class RazorPage<T> {
// This needs to be defined otherwise the VS tooling complains that there's no ExecuteAsync method to override.
public virtual Task ExecuteAsync()
=> throw new NotImplementedException($"Blazor components do not implement {nameof(ExecuteAsync)}.");
}
namespace Internal
{
public class RazorInjectAttributeAttribute : Attribute { }
}
}
namespace Microsoft.AspNetCore.Mvc.Rendering
{
public interface IJsonHelper { }
public interface IHtmlHelper<T> { }
}
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public interface IModelExpressionProvider { }
}
|
Set thread culture to InvariantCulture on startup | using System.Windows;
namespace OpenSage.DataViewer
{
public partial class App : Application
{
}
}
| using System.Windows;
using System.Globalization;
using System.Threading;
namespace OpenSage.DataViewer
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
base.OnStartup(e);
}
}
}
|
Throw excpetion when type is not found | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Perspex;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using System;
using System.Collections.Generic;
namespace Core2D.Perspex.Presenters
{
public class CachedContentPresenter : ContentPresenter
{
private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>();
private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>();
public static void Register(Type type, Func<Control> create) => _factory[type] = create;
public CachedContentPresenter()
{
this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value));
}
public Control GetControl(Type type)
{
Control control;
_cache.TryGetValue(type, out control);
if (control == null)
{
Func<Control> createInstance;
_factory.TryGetValue(type, out createInstance);
control = createInstance?.Invoke();
if (control != null)
{
_cache[type] = control;
}
}
return control;
}
public void SetContent(object value)
{
Control control = null;
if (value != null)
{
control = GetControl(value.GetType());
}
this.Content = control;
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Perspex;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using System;
using System.Collections.Generic;
namespace Core2D.Perspex.Presenters
{
public class CachedContentPresenter : ContentPresenter
{
private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>();
private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>();
public static void Register(Type type, Func<Control> create) => _factory[type] = create;
public CachedContentPresenter()
{
this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value));
}
public Control GetControl(Type type)
{
Control control;
_cache.TryGetValue(type, out control);
if (control == null)
{
Func<Control> createInstance;
_factory.TryGetValue(type, out createInstance);
control = createInstance?.Invoke();
if (control != null)
{
_cache[type] = control;
}
else
{
throw new Exception($"Can not find factory method for type: {type}");
}
}
return control;
}
public void SetContent(object value)
{
Control control = null;
if (value != null)
{
control = GetControl(value.GetType());
}
this.Content = control;
}
}
}
|
Fix NoShrineRoom logic if shrine is null | using RimWorld;
using Verse;
namespace MTW_AncestorSpirits
{
class ThoughtWorker_NoShrineRoom : ThoughtWorker
{
private static RoomRoleDef shrineRoomDef = DefDatabase<RoomRoleDef>.GetNamed("MTW_ShrineRoom");
protected override ThoughtState CurrentStateInternal(Pawn p)
{
// TODO: There's gotta be a better way of doin' this!
if (!AncestorUtils.IsAncestor(p)) { return ThoughtState.Inactive; }
var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner;
if (shrine == null) { return ThoughtState.Inactive; }
// HACK ALERT! Change Shrines to have an Interaction cell, and use that instead of a random one!
var room = RoomQuery.RoomAtFast(shrine.RandomAdjacentCellCardinal());
if (room == null)
{
return ThoughtState.ActiveAtStage(1);
}
else if (room.Role != shrineRoomDef)
{
return ThoughtState.ActiveAtStage(1);
}
else
{
return ThoughtState.Inactive;
}
}
}
}
| using RimWorld;
using Verse;
namespace MTW_AncestorSpirits
{
class ThoughtWorker_NoShrineRoom : ThoughtWorker
{
private static RoomRoleDef shrineRoomDef = DefDatabase<RoomRoleDef>.GetNamed("MTW_ShrineRoom");
protected override ThoughtState CurrentStateInternal(Pawn p)
{
// TODO: There's gotta be a better way of doin' this!
if (!AncestorUtils.IsAncestor(p)) { return ThoughtState.Inactive; }
var shrine = Find.Map.GetComponent<MapComponent_AncestorTicker>().CurrentSpawner;
if (shrine == null) { return ThoughtState.ActiveAtStage(1); }
// HACK ALERT! Change Shrines to have an Interaction cell, and use that instead of a random one!
var room = RoomQuery.RoomAtFast(shrine.RandomAdjacentCellCardinal());
if (room == null)
{
return ThoughtState.ActiveAtStage(1);
}
else if (room.Role != shrineRoomDef)
{
return ThoughtState.ActiveAtStage(1);
}
else
{
return ThoughtState.Inactive;
}
}
}
}
|
Add a few more tests | using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using WeCantSpell.Tests.Utilities;
using Xunit;
namespace WeCantSpell.Tests.Integration.CSharp
{
public class CommentSpellingTests : CSharpTestBase
{
public static IEnumerable<object[]> can_find_mistakes_in_comments_data
{
get
{
yield return new object[] { "aardvark", 660 };
yield return new object[] { "simple", 1186 };
yield return new object[] { "under", 1235 };
}
}
[Theory, MemberData(nameof(can_find_mistakes_in_comments_data))]
public async Task can_find_mistakes_in_comments(string expectedWord, int expectedStart)
{
var expectedEnd = expectedStart + expectedWord.Length;
var analyzer = new SpellingAnalyzerCSharp(new WrongWordChecker(expectedWord));
var project = await ReadCodeFileAsProjectAsync("XmlDoc.SimpleExamples.cs");
var diagnostics = await GetDiagnosticsAsync(project, analyzer);
diagnostics.Should().ContainSingle()
.Subject.Should()
.HaveId("SP3112")
.And.HaveLocation(expectedStart, expectedEnd, "XmlDoc.SimpleExamples.cs")
.And.HaveMessageContaining(expectedWord);
}
}
}
| using System.Collections.Generic;
using System.Threading.Tasks;
using FluentAssertions;
using WeCantSpell.Tests.Utilities;
using Xunit;
namespace WeCantSpell.Tests.Integration.CSharp
{
public class CommentSpellingTests : CSharpTestBase
{
public static IEnumerable<object[]> can_find_mistakes_in_comments_data
{
get
{
yield return new object[] { "aardvark", 660 };
yield return new object[] { "simple", 1186 };
yield return new object[] { "under", 1235 };
yield return new object[] { "inline", 111 };
yield return new object[] { "tag", 320 };
yield return new object[] { "Here", 898 };
yield return new object[] { "Just", 1130 };
}
}
[Theory, MemberData(nameof(can_find_mistakes_in_comments_data))]
public async Task can_find_mistakes_in_comments(string expectedWord, int expectedStart)
{
var expectedEnd = expectedStart + expectedWord.Length;
var analyzer = new SpellingAnalyzerCSharp(new WrongWordChecker(expectedWord));
var project = await ReadCodeFileAsProjectAsync("XmlDoc.SimpleExamples.cs");
var diagnostics = await GetDiagnosticsAsync(project, analyzer);
diagnostics.Should().ContainSingle()
.Subject.Should()
.HaveId("SP3112")
.And.HaveLocation(expectedStart, expectedEnd, "XmlDoc.SimpleExamples.cs")
.And.HaveMessageContaining(expectedWord);
}
}
}
|
Fix a typo in const name | namespace WebScriptHook.Framework.Messages.Outputs
{
/// <summary>
/// Sent by the component to request a channel for itself on the server.
/// This tells the server the name of this component, as well as the maximum number of requests
/// the component can handle per tick.
/// Once the server receives this message, a channel will be created, registered under this component's name.
/// Inputs sent by web clients will then be delivered to this component.
/// </summary>
class ChannelRequest : WebOutput
{
const char HEADER_CACHE = 'n';
public ChannelRequest(string ComponentName, int InputQueueLimit)
: base(HEADER_CACHE, new object[] { ComponentName, InputQueueLimit }, null)
{
}
}
}
| namespace WebScriptHook.Framework.Messages.Outputs
{
/// <summary>
/// Sent by the component to request a channel for itself on the server.
/// This tells the server the name of this component, as well as the maximum number of requests
/// the component can handle per tick.
/// Once the server receives this message, a channel will be created, registered under this component's name.
/// Inputs sent by web clients will then be delivered to this component.
/// </summary>
class ChannelRequest : WebOutput
{
const char HEADER_CHANNEL = 'n';
public ChannelRequest(string ComponentName, int InputQueueLimit)
: base(HEADER_CHANNEL, new object[] { ComponentName, InputQueueLimit }, null)
{
}
}
}
|
Update default Max Body Size | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ComponentModel;
using Microsoft.AspNetCore.ResponseCaching.Internal;
namespace Microsoft.AspNetCore.Builder
{
public class ResponseCacheOptions
{
/// <summary>
/// The largest cacheable size for the response body in bytes. The default is set to 1 MB.
/// </summary>
public long MaximumBodySize { get; set; } = 1024 * 1024;
/// <summary>
/// <c>true</c> if request paths are case-sensitive; otherwise <c>false</c>. The default is to treat paths as case-insensitive.
/// </summary>
public bool UseCaseSensitivePaths { get; set; } = false;
/// <summary>
/// For testing purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal ISystemClock SystemClock { get; set; } = new SystemClock();
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ComponentModel;
using Microsoft.AspNetCore.ResponseCaching.Internal;
namespace Microsoft.AspNetCore.Builder
{
public class ResponseCacheOptions
{
/// <summary>
/// The largest cacheable size for the response body in bytes. The default is set to 64 MB.
/// </summary>
public long MaximumBodySize { get; set; } = 64 * 1024 * 1024;
/// <summary>
/// <c>true</c> if request paths are case-sensitive; otherwise <c>false</c>. The default is to treat paths as case-insensitive.
/// </summary>
public bool UseCaseSensitivePaths { get; set; } = false;
/// <summary>
/// For testing purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal ISystemClock SystemClock { get; set; } = new SystemClock();
}
}
|
Fix encounter url not opening | using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Data;
using Tera.Game;
namespace DamageMeter.UI
{
/// <summary>
/// Logique d'interaction pour HistoryLink.xaml
/// </summary>
public partial class HistoryLink
{
public HistoryLink(string link, NpcEntity boss)
{
InitializeComponent();
Boss.Content = boss.Info.Name;
Boss.Tag = link;
if (link.StartsWith("!"))
{
Boss.Foreground = Brushes.Red;
Boss.ToolTip = link;
return;
}
Link.Source = BasicTeraData.Instance.ImageDatabase.Link.Source;
}
private void Click_Link(object sender, MouseButtonEventArgs e)
{
if (Boss.Tag.ToString().StartsWith("http://"))
Process.Start("explorer.exe", Boss.Tag.ToString());
}
private void Sender_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var w = Window.GetWindow(this);
try
{
w?.DragMove();
}
catch
{
Console.WriteLine(@"Exception move");
}
}
}
} | using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Data;
using Tera.Game;
namespace DamageMeter.UI
{
/// <summary>
/// Logique d'interaction pour HistoryLink.xaml
/// </summary>
public partial class HistoryLink
{
public HistoryLink(string link, NpcEntity boss)
{
InitializeComponent();
Boss.Content = boss.Info.Name;
Boss.Tag = link;
if (link.StartsWith("!"))
{
Boss.Foreground = Brushes.Red;
Boss.ToolTip = link;
return;
}
Link.Source = BasicTeraData.Instance.ImageDatabase.Link.Source;
}
private void Click_Link(object sender, MouseButtonEventArgs e)
{
if (Boss.Tag.ToString().StartsWith("http://"))
Process.Start("explorer.exe", "\""+Boss.Tag+"\"");
}
private void Sender_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var w = Window.GetWindow(this);
try
{
w?.DragMove();
}
catch
{
Console.WriteLine(@"Exception move");
}
}
}
} |
Fix single core batch processing | using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
// ReSharper disable AccessToDisposedClosure
namespace VGAudio.Cli
{
internal static class Batch
{
public static bool BatchConvert(Options options)
{
if (options.Job != JobType.Batch) return false;
SearchOption searchOption = options.Recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
string[] files = ContainerTypes.ExtensionList
.SelectMany(x => Directory.GetFiles(options.InDir, $"*.{x}", searchOption))
.ToArray();
using (var progress = new ProgressBar())
{
progress.SetTotal(files.Length);
Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount - 1 }, inPath =>
{
string relativePath = inPath.Substring(options.InDir.Length).TrimStart('\\');
string outPath = Path.ChangeExtension(Path.Combine(options.OutDir, relativePath), options.OutTypeName);
var jobFiles = new JobFiles();
jobFiles.InFiles.Add(new AudioFile(inPath));
jobFiles.OutFiles.Add(new AudioFile(outPath));
try
{
progress.LogMessage(Path.GetFileName(inPath));
Convert.ConvertFile(options, jobFiles, false);
}
catch (Exception ex)
{
progress.LogMessage($"Error converting {Path.GetFileName(inPath)}");
progress.LogMessage(ex.ToString());
}
progress.ReportAdd(1);
});
}
return true;
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
// ReSharper disable AccessToDisposedClosure
namespace VGAudio.Cli
{
internal static class Batch
{
public static bool BatchConvert(Options options)
{
if (options.Job != JobType.Batch) return false;
SearchOption searchOption = options.Recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
string[] files = ContainerTypes.ExtensionList
.SelectMany(x => Directory.GetFiles(options.InDir, $"*.{x}", searchOption))
.ToArray();
using (var progress = new ProgressBar())
{
progress.SetTotal(files.Length);
Parallel.ForEach(files,
new ParallelOptions { MaxDegreeOfParallelism = Math.Max(Environment.ProcessorCount - 1, 1) },
inPath =>
{
string relativePath = inPath.Substring(options.InDir.Length).TrimStart('\\');
string outPath = Path.ChangeExtension(Path.Combine(options.OutDir, relativePath), options.OutTypeName);
var jobFiles = new JobFiles();
jobFiles.InFiles.Add(new AudioFile(inPath));
jobFiles.OutFiles.Add(new AudioFile(outPath));
try
{
progress.LogMessage(Path.GetFileName(inPath));
Convert.ConvertFile(options, jobFiles, false);
}
catch (Exception ex)
{
progress.LogMessage($"Error converting {Path.GetFileName(inPath)}");
progress.LogMessage(ex.ToString());
}
progress.ReportAdd(1);
});
}
return true;
}
}
}
|
Fix enumerable not being consumed | // 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 BenchmarkDotNet.Attributes;
using osu.Game.Online.API;
using osu.Game.Rulesets.Osu;
namespace osu.Game.Benchmarks
{
public class BenchmarkRuleset : BenchmarkTest
{
private OsuRuleset ruleset;
private APIMod apiModDoubleTime;
private APIMod apiModDifficultyAdjust;
public override void SetUp()
{
base.SetUp();
ruleset = new OsuRuleset();
apiModDoubleTime = new APIMod { Acronym = "DT" };
apiModDifficultyAdjust = new APIMod { Acronym = "DA" };
}
[Benchmark]
public void BenchmarkToModDoubleTime()
{
apiModDoubleTime.ToMod(ruleset);
}
[Benchmark]
public void BenchmarkToModDifficultyAdjust()
{
apiModDifficultyAdjust.ToMod(ruleset);
}
[Benchmark]
public void BenchmarkGetAllMods()
{
ruleset.GetAllMods();
}
}
}
| // 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 BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using osu.Game.Online.API;
using osu.Game.Rulesets.Osu;
namespace osu.Game.Benchmarks
{
public class BenchmarkRuleset : BenchmarkTest
{
private OsuRuleset ruleset;
private APIMod apiModDoubleTime;
private APIMod apiModDifficultyAdjust;
public override void SetUp()
{
base.SetUp();
ruleset = new OsuRuleset();
apiModDoubleTime = new APIMod { Acronym = "DT" };
apiModDifficultyAdjust = new APIMod { Acronym = "DA" };
}
[Benchmark]
public void BenchmarkToModDoubleTime()
{
apiModDoubleTime.ToMod(ruleset);
}
[Benchmark]
public void BenchmarkToModDifficultyAdjust()
{
apiModDifficultyAdjust.ToMod(ruleset);
}
[Benchmark]
public void BenchmarkGetAllMods()
{
ruleset.GetAllMods().Consume(new Consumer());
}
}
}
|
Fix target file name generation | using System.IO;
namespace DevTyr.Gullap.Model
{
public static class MetaContentExtensions
{
public static string GetTargetFileName(this MetaContent content, SitePaths paths)
{
var isPage = content.Page != null;
string userDefinedFileName = content.GetOverriddenFileName();
string targetFileName = string.IsNullOrWhiteSpace(userDefinedFileName) ? Path.GetFileNameWithoutExtension(content.FileName) + ".html" : userDefinedFileName;
string targetDirectory;
if (isPage)
{
targetDirectory = Path.GetDirectoryName(targetFileName.Replace(paths.PagesPath, paths.OutputPath));
}
else
{
targetDirectory =
Path.GetDirectoryName(content.FileName.Replace(paths.PostsPath,
Path.Combine(paths.OutputPath, SitePaths.PostsDirectoryName)));
}
var targetPath = Path.Combine(targetDirectory, targetFileName);
return targetPath;
}
}
}
| using System.IO;
namespace DevTyr.Gullap.Model
{
public static class MetaContentExtensions
{
public static string GetTargetFileName(this MetaContent content, SitePaths paths)
{
var isPage = content.Page != null;
string userDefinedFileName = content.GetOverriddenFileName();
string targetFileName = string.IsNullOrWhiteSpace(userDefinedFileName) ? Path.GetFileNameWithoutExtension(content.FileName) + ".html" : userDefinedFileName;
string targetDirectory;
if (isPage)
{
targetDirectory = Path.GetDirectoryName(content.FileName.Replace(paths.PagesPath, paths.OutputPath));
}
else
{
targetDirectory =
Path.GetDirectoryName(content.FileName.Replace(paths.PostsPath,
Path.Combine(paths.OutputPath, SitePaths.PostsDirectoryName)));
}
var targetPath = Path.Combine(targetDirectory, targetFileName);
return targetPath;
}
}
}
|
Add example of using fixed provider | using Glimpse.Agent.Web;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.Agent.AspNet.Sample
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddGlimpse()
.RunningAgent()
.ForWeb()
.Configure<GlimpseAgentWebOptions>(options =>
{
//options.IgnoredStatusCodes.Add(200);
})
.WithRemoteStreamAgent();
//.WithRemoteHttpAgent();
}
public void Configure(IApplicationBuilder app)
{
app.UseGlimpse();
app.UseWelcomePage();
}
}
}
| using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Framework;
using Glimpse.Agent.Web.Options;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.Agent.AspNet.Sample
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
/* Example of how to use fixed provider
TODO: This should be cleanned up with help of extenion methods
services.AddSingleton<IIgnoredRequestProvider>(x =>
{
var activator = x.GetService<ITypeActivator>();
var urlPolicy = activator.CreateInstances<IIgnoredRequestPolicy>(new []
{
typeof(UriIgnoredRequestPolicy).GetTypeInfo(),
typeof(ContentTypeIgnoredRequestPolicy).GetTypeInfo()
});
var provider = new FixedIgnoredRequestProvider(urlPolicy);
return provider;
});
*/
services.AddGlimpse()
.RunningAgent()
.ForWeb()
.Configure<GlimpseAgentWebOptions>(options =>
{
//options.IgnoredStatusCodes.Add(200);
})
.WithRemoteStreamAgent();
//.WithRemoteHttpAgent();
}
public void Configure(IApplicationBuilder app)
{
app.UseGlimpse();
app.UseWelcomePage();
}
}
}
|
Fix og:image path for home page | @{
Layout = "~/Views/Shared/_LayoutPublic.cshtml";
}
@section metaPage
{
<meta property="og:type" content="website">
<meta property="og:image" content="@(AppConfiguration.Value.SiteUrl + "/content/images/logo-og.jpg")">
}
@RenderBody() | @{
Layout = "~/Views/Shared/_LayoutPublic.cshtml";
}
@section metaPage
{
<meta property="og:type" content="website">
<meta property="og:image" content="@(AppConfiguration.Value.SiteUrl + "/images/logo-og.jpg")">
}
@RenderBody() |
Reorganize forms into project subfolder | using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SqlDiffFramework
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
} | using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SqlDiffFramework.Forms;
namespace SqlDiffFramework
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
} |
Read querystring instead of using route patterns | namespace WeatherDataFunctionApp
{
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
public static class WeatherDataService
{
private static readonly HttpClient WeatherDataHttpClient = new HttpClient();
private static readonly string ApiUrl;
static WeatherDataService()
{
string apiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];
ApiUrl = $"https://api.apixu.com/v1/current.json?key={apiKey}&q={{0}}";
}
[FunctionName("WeatherDataService")]
public static async Task<HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "WeatherDataService/Current/{location}")]HttpRequestMessage req, string location, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
HttpResponseMessage responseMessage = await GetCurrentWeatherDataForLocation(location);
if (responseMessage.IsSuccessStatusCode)
return req.CreateResponse(HttpStatusCode.OK, responseMessage.Content.ReadAsAsync(typeof(object)).Result);
log.Error($"Error occurred while trying to retrieve weather data for {req.Content.ReadAsStringAsync().Result}");
return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Internal Server Error.");
}
private static async Task<HttpResponseMessage> GetCurrentWeatherDataForLocation(string location)
{
return await WeatherDataHttpClient.GetAsync(String.Format(ApiUrl, location));
}
}
}
| namespace WeatherDataFunctionApp
{
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
public static class WeatherDataService
{
private static readonly HttpClient WeatherDataHttpClient = new HttpClient();
private static readonly string ApiUrl;
static WeatherDataService()
{
string apiKey = System.Configuration.ConfigurationManager.AppSettings["ApiKey"];
ApiUrl = $"https://api.apixu.com/v1/current.json?key={apiKey}&q={{0}}";
}
[FunctionName("WeatherDataService")]
public static async Task<HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var queryNameValuePairs = req.GetQueryNameValuePairs();
var location = queryNameValuePairs.Where(pair => pair.Key.Equals("location", StringComparison.InvariantCultureIgnoreCase)).Select(queryParam => queryParam.Value).FirstOrDefault();
HttpResponseMessage responseMessage = await GetCurrentWeatherDataForLocation(location);
if (responseMessage.IsSuccessStatusCode)
return req.CreateResponse(HttpStatusCode.OK, responseMessage.Content.ReadAsAsync(typeof(object)).Result);
log.Error($"Error occurred while trying to retrieve weather data for {req.Content.ReadAsStringAsync().Result}");
return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Internal Server Error.");
}
private static async Task<HttpResponseMessage> GetCurrentWeatherDataForLocation(string location)
{
return await WeatherDataHttpClient.GetAsync(String.Format(ApiUrl, location));
}
}
}
|
Add informational logging to launcher | using Microsoft.Web.Administration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace Launcher
{
public class ExecutionMetadata
{
[JsonProperty("start_command")]
public string DetectedStartCommand { get; set; }
[JsonProperty("start_command_args")]
public string[] StartCommandArgs { get; set; }
}
class Program
{
static int Main(string[] args)
{
if (args.Length < 3)
{
Console.Error.WriteLine("Launcher was run with insufficient arguments. The arguments were: {0}",
String.Join(" ", args));
return 1;
}
ExecutionMetadata executionMetadata = null;
try
{
executionMetadata = JsonConvert.DeserializeObject<ExecutionMetadata>(args[2]);
}
catch (Exception ex)
{
Console.Error.WriteLine(
"Launcher was run with invalid JSON for the metadata argument. The JSON was: {0}", args[2]);
return 1;
}
var startInfo = new ProcessStartInfo
{
UseShellExecute = false,
FileName = executionMetadata.DetectedStartCommand,
Arguments = ArgumentEscaper.Escape(executionMetadata.StartCommandArgs),
};
var process = Process.Start(startInfo);
process.WaitForExit();
return process.ExitCode;
}
}
}
| using Microsoft.Web.Administration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace Launcher
{
public class ExecutionMetadata
{
[JsonProperty("start_command")]
public string DetectedStartCommand { get; set; }
[JsonProperty("start_command_args")]
public string[] StartCommandArgs { get; set; }
}
class Program
{
static int Main(string[] args)
{
if (args.Length < 3)
{
Console.Error.WriteLine("Launcher was run with insufficient arguments. The arguments were: {0}",
String.Join(" ", args));
return 1;
}
ExecutionMetadata executionMetadata = null;
try
{
executionMetadata = JsonConvert.DeserializeObject<ExecutionMetadata>(args[2]);
}
catch (Exception ex)
{
Console.Error.WriteLine(
"Launcher was run with invalid JSON for the metadata argument. The JSON was: {0}", args[2]);
return 1;
}
var startInfo = new ProcessStartInfo
{
UseShellExecute = false,
FileName = executionMetadata.DetectedStartCommand,
Arguments = ArgumentEscaper.Escape(executionMetadata.StartCommandArgs),
};
Console.Out.WriteLine("Run {0} :with: {1}", startInfo.FileName, startInfo.Arguments);
var process = Process.Start(startInfo);
process.WaitForExit();
return process.ExitCode;
}
}
}
|
Refactor verbose log of SingleThreadScheduler. | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CreviceApp.Threading
{
// http://www.codeguru.com/csharp/article.php/c18931/Understanding-the-NET-Task-Parallel-Library-TaskScheduler.htm
public class SingleThreadScheduler : TaskScheduler, IDisposable
{
private readonly BlockingCollection<Task> tasks = new BlockingCollection<Task>();
private readonly Thread thread;
public SingleThreadScheduler() : this(ThreadPriority.Normal) { }
public SingleThreadScheduler(ThreadPriority priority)
{
this.thread = new Thread(new ThreadStart(Main));
this.thread.Priority = priority;
this.thread.Start();
}
private void Main()
{
Verbose.Print("SingleThreadScheduler was started; Thread ID: 0x{0:X}", Thread.CurrentThread.ManagedThreadId);
foreach (var t in tasks.GetConsumingEnumerable())
{
TryExecuteTask(t);
}
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return tasks.ToArray();
}
protected override void QueueTask(Task task)
{
tasks.Add(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false;
}
public void Dispose()
{
GC.SuppressFinalize(this);
tasks.CompleteAdding();
}
~SingleThreadScheduler()
{
Dispose();
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CreviceApp.Threading
{
// http://www.codeguru.com/csharp/article.php/c18931/Understanding-the-NET-Task-Parallel-Library-TaskScheduler.htm
public class SingleThreadScheduler : TaskScheduler, IDisposable
{
private readonly BlockingCollection<Task> tasks = new BlockingCollection<Task>();
private readonly Thread thread;
public SingleThreadScheduler() : this(ThreadPriority.Normal) { }
public SingleThreadScheduler(ThreadPriority priority)
{
this.thread = new Thread(new ThreadStart(Main));
this.thread.Priority = priority;
this.thread.Start();
}
private void Main()
{
Verbose.Print("SingleThreadScheduler(ThreadID: 0x{0:X}) was started.", Thread.CurrentThread.ManagedThreadId);
foreach (var t in tasks.GetConsumingEnumerable())
{
TryExecuteTask(t);
}
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return tasks.ToArray();
}
protected override void QueueTask(Task task)
{
tasks.Add(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false;
}
public void Dispose()
{
GC.SuppressFinalize(this);
tasks.CompleteAdding();
}
~SingleThreadScheduler()
{
Dispose();
}
}
}
|
Test case includes string with quotes. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ecologylab.serialization;
using ecologylab.attributes;
namespace ecologylabFundamentalTestCases.Polymorphic
{
/**
*
* <configuration>
<pref_double name="index_thumb_dist" value="200"/>
</configuration>
*
*/
public class Configuration : ElementState
{
[simpl_nowrap]
[simpl_scope("testScope")]
//[simpl_classes(new Type[] { typeof(Pref), typeof(PrefDouble) })]
[simpl_map]
public Dictionary<String, Pref> prefs = new Dictionary<string, Pref>();
#region GetterSetters
public Dictionary<String, Pref> Preferences
{
get { return prefs; }
set { prefs = value; }
}
#endregion
internal void fillDictionary()
{
PrefDouble prefDouble = new PrefDouble();
prefDouble.Name = "index_thumb_dist";
prefDouble.Value = 200;
Pref pref = new Pref();
pref.Name = "test_name";
prefs.Add(prefDouble.Name, prefDouble);
prefs.Add(pref.Name, pref);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ecologylab.serialization;
using ecologylab.attributes;
namespace ecologylabFundamentalTestCases.Polymorphic
{
/**
*
* <configuration>
<pref_double name="index_thumb_dist" value="200"/>
</configuration>
*
*/
public class Configuration : ElementState
{
[simpl_nowrap]
[simpl_scope("testScope")]
//[simpl_classes(new Type[] { typeof(Pref), typeof(PrefDouble) })]
[simpl_map]
public Dictionary<String, Pref> prefs = new Dictionary<string, Pref>();
#region GetterSetters
public Dictionary<String, Pref> Preferences
{
get { return prefs; }
set { prefs = value; }
}
#endregion
internal void fillDictionary()
{
PrefDouble prefDouble = new PrefDouble();
prefDouble.Name = "index_thumb_dist \"now with a double quote\" and a 'single quote' ";
prefDouble.Value = 200;
Pref pref = new Pref();
pref.Name = "test_name";
prefs.Add(prefDouble.Name, prefDouble);
prefs.Add(pref.Name, pref);
}
}
}
|
Fix checkbox not updating correctly. | using System;
using osu.Framework.Configuration;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Overlays.Options
{
public class CheckBoxOption : BasicCheckBox
{
private Bindable<bool> bindable;
public Bindable<bool> Bindable
{
set
{
if (bindable != null)
bindable.ValueChanged -= bindableValueChanged;
bindable = value;
if (bindable != null)
{
bool state = State == CheckBoxState.Checked;
if (state != bindable.Value)
State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked;
bindable.ValueChanged += bindableValueChanged;
}
}
}
private void bindableValueChanged(object sender, EventArgs e)
{
State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked;
}
protected override void Dispose(bool isDisposing)
{
if (bindable != null)
bindable.ValueChanged -= bindableValueChanged;
base.Dispose(isDisposing);
}
protected override void OnChecked()
{
if (bindable != null)
bindable.Value = true;
base.OnChecked();
}
protected override void OnUnchecked()
{
if (bindable != null)
bindable.Value = false;
base.OnChecked();
}
}
} | using System;
using osu.Framework.Configuration;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Overlays.Options
{
public class CheckBoxOption : BasicCheckBox
{
private Bindable<bool> bindable;
public Bindable<bool> Bindable
{
set
{
if (bindable != null)
bindable.ValueChanged -= bindableValueChanged;
bindable = value;
if (bindable != null)
{
bool state = State == CheckBoxState.Checked;
if (state != bindable.Value)
State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked;
bindable.ValueChanged += bindableValueChanged;
}
}
}
private void bindableValueChanged(object sender, EventArgs e)
{
State = bindable.Value ? CheckBoxState.Checked : CheckBoxState.Unchecked;
}
protected override void Dispose(bool isDisposing)
{
if (bindable != null)
bindable.ValueChanged -= bindableValueChanged;
base.Dispose(isDisposing);
}
protected override void OnChecked()
{
if (bindable != null)
bindable.Value = true;
base.OnChecked();
}
protected override void OnUnchecked()
{
if (bindable != null)
bindable.Value = false;
base.OnUnchecked();
}
}
}
|
Increase toleranceSeconds in SafeWait_PollingInterval_GreaterThanTimeout test | using System;
using System.Threading;
using NUnit.Framework;
namespace Atata.WebDriverExtras.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class SafeWaitTests
{
private SafeWait<object> wait;
[SetUp]
public void SetUp()
{
wait = new SafeWait<object>(new object())
{
Timeout = TimeSpan.FromSeconds(.3),
PollingInterval = TimeSpan.FromSeconds(.05)
};
}
[Test]
public void SafeWait_Success_Immediate()
{
using (StopwatchAsserter.Within(0, .01))
wait.Until(_ =>
{
return true;
});
}
[Test]
public void SafeWait_Timeout()
{
using (StopwatchAsserter.Within(.3, .015))
wait.Until(_ =>
{
return false;
});
}
[Test]
public void SafeWait_PollingInterval()
{
using (StopwatchAsserter.Within(.3, .2))
wait.Until(_ =>
{
Thread.Sleep(TimeSpan.FromSeconds(.1));
return false;
});
}
[Test]
public void SafeWait_PollingInterval_GreaterThanTimeout()
{
wait.PollingInterval = TimeSpan.FromSeconds(1);
using (StopwatchAsserter.Within(.3, .015))
wait.Until(_ =>
{
return false;
});
}
}
}
| using System;
using System.Threading;
using NUnit.Framework;
namespace Atata.WebDriverExtras.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class SafeWaitTests
{
private SafeWait<object> wait;
[SetUp]
public void SetUp()
{
wait = new SafeWait<object>(new object())
{
Timeout = TimeSpan.FromSeconds(.3),
PollingInterval = TimeSpan.FromSeconds(.05)
};
}
[Test]
public void SafeWait_Success_Immediate()
{
using (StopwatchAsserter.Within(0, .01))
wait.Until(_ =>
{
return true;
});
}
[Test]
public void SafeWait_Timeout()
{
using (StopwatchAsserter.Within(.3, .015))
wait.Until(_ =>
{
return false;
});
}
[Test]
public void SafeWait_PollingInterval()
{
using (StopwatchAsserter.Within(.3, .2))
wait.Until(_ =>
{
Thread.Sleep(TimeSpan.FromSeconds(.1));
return false;
});
}
[Test]
public void SafeWait_PollingInterval_GreaterThanTimeout()
{
wait.PollingInterval = TimeSpan.FromSeconds(1);
using (StopwatchAsserter.Within(.3, .02))
wait.Until(_ =>
{
return false;
});
}
}
}
|
Use locale's decimal separator instead of hardcoding period. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Paymetheus
{
/// <summary>
/// Interaction logic for Send.xaml
/// </summary>
public partial class Send : Page
{
public Send()
{
InitializeComponent();
}
private void OutputAmountTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = e.Text.All(ch => !((ch >= '0' && ch <= '9') || ch == '.'));
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Paymetheus
{
/// <summary>
/// Interaction logic for Send.xaml
/// </summary>
public partial class Send : Page
{
string decimalSep = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
public Send()
{
InitializeComponent();
}
private void OutputAmountTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = e.Text.All(ch => !((ch >= '0' && ch <= '9') || decimalSep.Contains(ch)));
}
}
}
|
Set WinApiNet assembly as CLS-compliant | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="WinAPI.NET">
// Copyright (c) Marek Dzikiewicz, All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WinApiNet")]
[assembly: AssemblyDescription("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")] | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="WinAPI.NET">
// Copyright (c) Marek Dzikiewicz, All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WinApiNet")]
[assembly: AssemblyDescription("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")]
// Assembly is CLS-compliant
[assembly: CLSCompliant(true)] |
Add an API for getting the result of an operation without knowing it's type. | using Silk.Data.SQL.Expressions;
using Silk.Data.SQL.Queries;
using System.Threading.Tasks;
namespace Silk.Data.SQL.ORM.Operations
{
public abstract class DataOperation
{
/// <summary>
/// Gets a value indicating if the operation can be executed as part of a batch operation.
/// </summary>
public abstract bool CanBeBatched { get; }
/// <summary>
/// Gets the SQL query needed to run the DataOperation.
/// </summary>
/// <returns></returns>
public abstract QueryExpression GetQuery();
/// <summary>
/// Process the result QueryResult set to the correct result set.
/// </summary>
public abstract void ProcessResult(QueryResult queryResult);
/// <summary>
/// Process the result QueryResult set to the correct result set.
/// </summary>
public abstract Task ProcessResultAsync(QueryResult queryResult);
}
public abstract class DataOperationWithResult<T> : DataOperation
{
/// <summary>
/// Gets the result of the data operation.
/// </summary>
public abstract T Result { get; }
}
}
| using Silk.Data.SQL.Expressions;
using Silk.Data.SQL.Queries;
using System.Threading.Tasks;
namespace Silk.Data.SQL.ORM.Operations
{
public abstract class DataOperation
{
/// <summary>
/// Gets a value indicating if the operation can be executed as part of a batch operation.
/// </summary>
public abstract bool CanBeBatched { get; }
/// <summary>
/// Gets the SQL query needed to run the DataOperation.
/// </summary>
/// <returns></returns>
public abstract QueryExpression GetQuery();
/// <summary>
/// Process the result QueryResult set to the correct result set.
/// </summary>
public abstract void ProcessResult(QueryResult queryResult);
/// <summary>
/// Process the result QueryResult set to the correct result set.
/// </summary>
public abstract Task ProcessResultAsync(QueryResult queryResult);
}
public abstract class DataOperationWithResult : DataOperation
{
/// <summary>
/// Gets the result of the data operation without a known static type.
/// </summary>
public abstract object UntypedResult { get; }
}
public abstract class DataOperationWithResult<T> : DataOperationWithResult
{
/// <summary>
/// Gets the result of the data operation.
/// </summary>
public abstract T Result { get; }
public override object UntypedResult => Result;
}
}
|
Remove xml encoding in reports. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace SimpleReport.Model.Replacers
{
/// <summary>
/// Used to replace xml code and remove styling from rtf text
/// </summary>
public class ValueReplacer : IValueReplacer
{
public string Replace(string inputstring)
{
var value = IsRtf(inputstring) ? RtfToText(inputstring) : inputstring;
value = XmlTextEncoder.Encode(value);
return value;
}
private static bool IsRtf(string text)
{
return text.TrimStart().StartsWith("{\\rtf1", StringComparison.Ordinal);
}
private static string RtfToText(string text)
{
try
{
var rtBox = new System.Windows.Forms.RichTextBox {Rtf = text};
text = rtBox.Text;
} catch (Exception ex)
{
// do nothing, just return faulty rtf
}
return text;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace SimpleReport.Model.Replacers
{
/// <summary>
/// Used to replace xml code and remove styling from rtf text
/// </summary>
public class ValueReplacer : IValueReplacer
{
public string Replace(string inputstring)
{
var value = IsRtf(inputstring) ? RtfToText(inputstring) : inputstring;
return value;
}
private static bool IsRtf(string text)
{
return text.TrimStart().StartsWith("{\\rtf1", StringComparison.Ordinal);
}
private static string RtfToText(string text)
{
try
{
var rtBox = new System.Windows.Forms.RichTextBox {Rtf = text};
text = rtBox.Text;
} catch (Exception ex)
{
// do nothing, just return faulty rtf
}
return text;
}
}
}
|
Read parameters from command line arguments | using static System.Console;
namespace ConsoleApp
{
class Program
{
private static void Main()
{
var connectionString = @"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;";
var schemaName = "dbo";
var tableName = "Book";
var columnsProvider = new ColumnsProvider(connectionString);
var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult();
new Table(tableName, columns).OutputMigrationCode(Out);
}
}
}
| using static System.Console;
namespace ConsoleApp
{
class Program
{
private static void Main(string[] args)
{
if (args.Length != 3)
{
WriteLine("Usage: schema2fm.exe connectionstring schema table");
return;
}
var connectionString = args[0];//@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;";
var schemaName = args[1];//"dbo";
var tableName = args[2];//"Book";
var columnsProvider = new ColumnsProvider(connectionString);
var columns = columnsProvider.GetColumnsAsync(schemaName, tableName).GetAwaiter().GetResult();
new Table(tableName, columns).OutputMigrationCode(Out);
}
}
}
|
Update the Empty module template. | #region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using Kooboo.CMS.Sites.Extension.ModuleArea;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.CMS.Sites.Extension;
using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models;
namespace Kooboo.CMS.ModuleArea.Areas.Empty
{
[Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = SampleAreaRegistration.ModuleName)]
public class ModuleAction : IModuleAction
{
public void OnExcluded(Sites.Models.Site site)
{
// Add code here that will be executed when the module was excluded to the site.
}
public void OnIncluded(Sites.Models.Site site)
{
// Add code here that will be executed when the module was included to the site.
}
public void OnInstalling(ControllerContext controllerContext)
{
var moduleInfo = ModuleInfo.Get(SampleAreaRegistration.ModuleName);
var installModel = new InstallModel();
Kooboo.CMS.Sites.Extension.PagePluginHelper.BindModel<InstallModel>(installModel, controllerContext);
moduleInfo.DefaultSettings.CustomSettings["DatabaseServer"] = installModel.DatabaseServer;
moduleInfo.DefaultSettings.CustomSettings["UserName"] = installModel.UserName;
moduleInfo.DefaultSettings.CustomSettings["Password"] = installModel.Password;
ModuleInfo.Save(moduleInfo);
// Add code here that will be executed when the module installing.
}
public void OnUninstalling(ControllerContext controllerContext)
{
// Add code here that will be executed when the module uninstalling.
}
}
}
| #region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using Kooboo.CMS.Sites.Extension.ModuleArea;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.CMS.Sites.Extension;
using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models;
namespace Kooboo.CMS.ModuleArea.Areas.Empty
{
[Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = ModuleAreaRegistration.ModuleName)]
public class ModuleAction : IModuleAction
{
public void OnExcluded(Sites.Models.Site site)
{
// Add code here that will be executed when the module was excluded to the site.
}
public void OnIncluded(Sites.Models.Site site)
{
// Add code here that will be executed when the module was included to the site.
}
public void OnInstalling(ControllerContext controllerContext)
{
// Add code here that will be executed when the module installing.
}
public void OnUninstalling(ControllerContext controllerContext)
{
// Add code here that will be executed when the module uninstalling.
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.