doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
9a0d4854-de44-4d56-b158-ed4ff43a792e
{ "language": "C#" }
```c# using System; using Polly.Utilities; namespace Polly.Retry { internal partial class RetryPolicyStateWithSleepDurationProvider : IRetryPolicyState { private int _errorCount; private readonly Func<int, TimeSpan> _sleepDurationProvider; private readonly Action<Exception, TimeSpan, Context> _onRetry; private readonly Context _context; public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan, Context> onRetry, Context context) { this._sleepDurationProvider = sleepDurationProvider; _onRetry = onRetry; _context = context; } public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan> onRetry) : this(sleepDurationProvider, (exception, timespan, context) => onRetry(exception, timespan), null) { } public bool CanRetry(Exception ex) { if (_errorCount < int.MaxValue) { _errorCount += 1; } else { } var currentTimeSpan = _sleepDurationProvider(_errorCount); _onRetry(ex, currentTimeSpan, _context); SystemClock.Sleep(currentTimeSpan); return true; } } } ``` Check for int.MaxValue when incrementing retry counter
```c# using System; using Polly.Utilities; namespace Polly.Retry { internal partial class RetryPolicyStateWithSleepDurationProvider : IRetryPolicyState { private int _errorCount; private readonly Func<int, TimeSpan> _sleepDurationProvider; private readonly Action<Exception, TimeSpan, Context> _onRetry; private readonly Context _context; public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan, Context> onRetry, Context context) { this._sleepDurationProvider = sleepDurationProvider; _onRetry = onRetry; _context = context; } public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan> onRetry) : this(sleepDurationProvider, (exception, timespan, context) => onRetry(exception, timespan), null) { } public bool CanRetry(Exception ex) { if (_errorCount < int.MaxValue) { _errorCount += 1; } var currentTimeSpan = _sleepDurationProvider(_errorCount); _onRetry(ex, currentTimeSpan, _context); SystemClock.Sleep(currentTimeSpan); return true; } } } ```
348d4823-1d77-4973-919c-77a287b7b7bf
{ "language": "C#" }
```c# using System; using System.Net.Http; using System.Threading.Tasks; namespace Glimpse.Agent { public class HttpChannelSender : IChannelSender, IDisposable { private readonly HttpClient _httpClient; private readonly HttpClientHandler _httpHandler; public HttpChannelSender() { _httpHandler = new HttpClientHandler(); _httpClient = new HttpClient(_httpHandler); } public async void PublishMessage(IMessage message) { // TODO: Needs error handelling // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync try { var response = await _httpClient.PostAsJsonAsync("http://localhost:5210/Glimpse/Agent", message); // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); // Read response asynchronously as JsonValue and write out top facts for each country var result = await response.Content.ReadAsStringAsync(); } catch (Exception e) { // TODO: Bad thing happened } } public void Dispose() { _httpClient.Dispose(); _httpHandler.Dispose(); } } }``` Remove the reading of the response... extra overhead not needed
```c# using System; using System.Net.Http; using System.Threading.Tasks; namespace Glimpse.Agent { public class HttpChannelSender : IChannelSender, IDisposable { private readonly HttpClient _httpClient; private readonly HttpClientHandler _httpHandler; public HttpChannelSender() { _httpHandler = new HttpClientHandler(); _httpClient = new HttpClient(_httpHandler); } public async void PublishMessage(IMessage message) { // TODO: Needs error handelling // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync try { var response = await _httpClient.PostAsJsonAsync("http://localhost:5210/Glimpse/Agent", message); // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); } catch (Exception e) { // TODO: Bad thing happened } } public void Dispose() { _httpClient.Dispose(); _httpHandler.Dispose(); } } }```
81924bfd-7427-475b-916d-55aff8b424bb
{ "language": "C#" }
```c# @inject BowerVersions Bower @inject SiteOptions Options @{ ViewBag.Title = ".NET Development Tools"; ViewBag.MetaDescription = ".NET Development Tools for generating GUIDs, machine keys and hashing text."; var clipboardVersion = Bower["clipboard"]; var toolsUri = Options.ExternalLinks.Api.AbsoluteUri + "tools"; } @section meta { <link rel="api-guid" href="@toolsUri/guid" /> <link rel="api-hash" href="@toolsUri/hash" /> <link rel="api-machine-key" href="@toolsUri/machinekey" /> } @section scripts { <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/@clipboardVersion/clipboard.min.js" integrity="sha256-COWXDc7n7PAqsE3y1r4CVopxWU9JI0kenz6K4zBqhT8=" crossorigin="anonymous" asp-fallback-src="~/lib/clipboard/dist/clipboard.min.js" asp-fallback-test="window.Clipboard"> </script> } <h1>@ViewBag.Title</h1> <div class="panel panel-default"> <div class="panel-body">This page contains tools and links to common development tools.</div> </div> <div> @await Html.PartialAsync("_GenerateGuid") </div> <div> @await Html.PartialAsync("_GenerateHash") </div> <div> @await Html.PartialAsync("_GenerateMachineKey") </div> ``` Add warning to /tools if JavaScript disabled
```c# @inject BowerVersions Bower @inject SiteOptions Options @{ ViewBag.Title = ".NET Development Tools"; ViewBag.MetaDescription = ".NET Development Tools for generating GUIDs, machine keys and hashing text."; var clipboardVersion = Bower["clipboard"]; var toolsUri = Options.ExternalLinks.Api.AbsoluteUri + "tools"; } @section meta { <link rel="api-guid" href="@toolsUri/guid" /> <link rel="api-hash" href="@toolsUri/hash" /> <link rel="api-machine-key" href="@toolsUri/machinekey" /> } @section scripts { <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/@clipboardVersion/clipboard.min.js" integrity="sha256-COWXDc7n7PAqsE3y1r4CVopxWU9JI0kenz6K4zBqhT8=" crossorigin="anonymous" asp-fallback-src="~/lib/clipboard/dist/clipboard.min.js" asp-fallback-test="window.Clipboard"> </script> } <h1>@ViewBag.Title</h1> <div class="panel panel-default"> <div class="panel-body">This page contains tools and links to common development tools.</div> </div> <noscript> <div class="alert alert-warning" role="alert">JavaScript must be enabled in your browser to use these tools.</div> </noscript> <div> @await Html.PartialAsync("_GenerateGuid") </div> <div> @await Html.PartialAsync("_GenerateHash") </div> <div> @await Html.PartialAsync("_GenerateMachineKey") </div> ```
746aeb70-1636-427b-af65-de08308c9a6e
{ "language": "C#" }
```c# 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.Media; namespace DotNetKit.Windows.Media { public static class VisualTreeModule { public static FrameworkElement FindChild(DependencyObject obj, string childName) { if (obj == null) return null; var queue = new Queue<DependencyObject>(); queue.Enqueue(obj); while (queue.Count > 0) { obj = queue.Dequeue(); var childCount = VisualTreeHelper.GetChildrenCount(obj); for (var i = 0; i < childCount; i++) { var child = VisualTreeHelper.GetChild(obj, i); var fe = child as FrameworkElement; if (fe != null && fe.Name == childName) { return fe; } queue.Enqueue(child); } } return null; } } } ``` Hide a defintion for internal use
```c# 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.Media; namespace DotNetKit.Windows.Media { static class VisualTreeModule { public static FrameworkElement FindChild(DependencyObject obj, string childName) { if (obj == null) return null; var queue = new Queue<DependencyObject>(); queue.Enqueue(obj); while (queue.Count > 0) { obj = queue.Dequeue(); var childCount = VisualTreeHelper.GetChildrenCount(obj); for (var i = 0; i < childCount; i++) { var child = VisualTreeHelper.GetChild(obj, i); var fe = child as FrameworkElement; if (fe != null && fe.Name == childName) { return fe; } queue.Enqueue(child); } } return null; } } } ```
bfdbcf35-846b-448e-a28b-793c1f01c932
{ "language": "C#" }
```c# using System; using System.IO; using System.Windows.Forms; using System.Windows.Media.Imaging; using Autodesk.Revit.UI; namespace AMEE_in_Revit.Addin { public class AMEEPanel : IExternalApplication { // ExternalCommands assembly path static string AddInPath = typeof(AMEEPanel).Assembly.Location; // Button icons directory static string ButtonIconsFolder = Path.GetDirectoryName(AddInPath); // uiApplication static UIApplication uiApplication = null; public Result OnStartup(UIControlledApplication application) { try { var panel = application.CreateRibbonPanel("AMEE"); AddAMEEConnectButton(panel); panel.AddSeparator(); return Result.Succeeded; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "AMEE-in-Revit error"); return Result.Failed; } } private void AddAMEEConnectButton(RibbonPanel panel) { var pushButton = panel.AddItem(new PushButtonData("launchAMEEConnect", "AMEE Connect", AddInPath, "AMEE_in_Revit.Addin.LaunchAMEEConnectCommand")) as PushButton; pushButton.ToolTip = "Say Hello World"; // Set the large image shown on button pushButton.LargeImage = new BitmapImage(new Uri(ButtonIconsFolder+ @"\AMEE.ico")); } public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } } } ``` Put AMEE Ribbon Panel under Analyze tab
```c# using System; using System.IO; using System.Windows.Forms; using System.Windows.Media.Imaging; using Autodesk.Revit.UI; namespace AMEE_in_Revit.Addin { public class AMEEPanel : IExternalApplication { // ExternalCommands assembly path static string AddInPath = typeof(AMEEPanel).Assembly.Location; // Button icons directory static string ButtonIconsFolder = Path.GetDirectoryName(AddInPath); // uiApplication static UIApplication uiApplication = null; public Result OnStartup(UIControlledApplication application) { try { var panel = application.CreateRibbonPanel(Tab.Analyze, "AMEE"); AddAMEEConnectButton(panel); panel.AddSeparator(); return Result.Succeeded; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "AMEE-in-Revit error"); return Result.Failed; } } private void AddAMEEConnectButton(RibbonPanel panel) { var pushButton = panel.AddItem(new PushButtonData("launchAMEEConnect", "AMEE Connect", AddInPath, "AMEE_in_Revit.Addin.LaunchAMEEConnectCommand")) as PushButton; pushButton.ToolTip = "Say Hello World"; // Set the large image shown on button pushButton.LargeImage = new BitmapImage(new Uri(ButtonIconsFolder+ @"\AMEE.ico")); } public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } } } ```
9a97c3a0-905d-44b3-a3fe-d0d703291d2f
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class Hourglass : Trigger { public Animator cutScene; public override void Activate() { UtilControls.Freeze(); cutScene.Play("cutscene"); GameObject.FindGameObjectWithTag("ThingsController").GetComponent<ThingsController>().ClearCurrentMemory(); } public override void Deactivate() { /* nothing */ } public override void Interact() { /* nothing */ } } ``` Update on hourglass script. Still not in action
```c# using UnityEngine; using System.Collections; public class Hourglass : Trigger { public GameObject cutsceneObject; public Animator cutScene; void Start() { //cutScene = cutsceneObject.GetComponent<Animator>(); } public override void Activate() { UtilControls.Freeze(); cutScene.Play("cutscene"); GameObject.FindGameObjectWithTag("ThingsController").GetComponent<ThingsController>().ClearCurrentMemory(); } public override void Deactivate() { /* nothing */ } public override void Interact() { /* nothing */ } } ```
613e3eaf-42ca-45f7-9348-47de9f2559da
{ "language": "C#" }
```c# namespace Fixie.Execution.Listeners { using System; using System.IO; using System.Xml.Linq; public class ReportListener<TXmlFormat> : Handler<AssemblyStarted>, Handler<ClassStarted>, Handler<CaseCompleted>, Handler<ClassCompleted>, Handler<AssemblyCompleted> where TXmlFormat : XmlFormat, new() { Report report; ClassReport currentClass; readonly Action<Report> save; public ReportListener(Action<Report> save) { this.save = save; } public ReportListener() : this(Save) { } public void Handle(AssemblyStarted message) { report = new Report(message.Assembly); } public void Handle(ClassStarted message) { currentClass = new ClassReport(message.Class); report.Add(currentClass); } public void Handle(CaseCompleted message) { currentClass.Add(message); } public void Handle(ClassCompleted message) { currentClass = null; } public void Handle(AssemblyCompleted message) { save(report); report = null; } static void Save(Report report) { var format = new TXmlFormat(); var xDocument = format.Transform(report); var filePath = Path.GetFullPath(report.Assembly.Location) + ".xml"; using (var stream = new FileStream(filePath, FileMode.Create)) using (var writer = new StreamWriter(stream)) xDocument.Save(writer, SaveOptions.None); } } }``` Save files as UTF-8 for consistency.
```c# namespace Fixie.Execution.Listeners { using System; using System.IO; using System.Xml.Linq; public class ReportListener<TXmlFormat> : Handler<AssemblyStarted>, Handler<ClassStarted>, Handler<CaseCompleted>, Handler<ClassCompleted>, Handler<AssemblyCompleted> where TXmlFormat : XmlFormat, new() { Report report; ClassReport currentClass; readonly Action<Report> save; public ReportListener(Action<Report> save) { this.save = save; } public ReportListener() : this(Save) { } public void Handle(AssemblyStarted message) { report = new Report(message.Assembly); } public void Handle(ClassStarted message) { currentClass = new ClassReport(message.Class); report.Add(currentClass); } public void Handle(CaseCompleted message) { currentClass.Add(message); } public void Handle(ClassCompleted message) { currentClass = null; } public void Handle(AssemblyCompleted message) { save(report); report = null; } static void Save(Report report) { var format = new TXmlFormat(); var xDocument = format.Transform(report); var filePath = Path.GetFullPath(report.Assembly.Location) + ".xml"; using (var stream = new FileStream(filePath, FileMode.Create)) using (var writer = new StreamWriter(stream)) xDocument.Save(writer, SaveOptions.None); } } }```
97f72252-7dbe-4dd3-82e6-94bfa3eb49b2
{ "language": "C#" }
```c# using System.Collections.Generic; namespace Common.Data { public class TemperatureOverlayState { public bool CustomRangesEnabled { get; set; } = true; public List<float> Temperatures => new List<float> { Aqua, Turquoise, Blue, Green, Lime, Orange, RedOrange, Red }; public float Red { get; set; } = 1800; public float RedOrange { get; set; } = 773; public float Orange { get; set; } = 373; public float Lime { get; set; } = 303; public float Green { get; set; } = 293; public float Blue { get; set; } = 0.1f; public float Turquoise { get; set; } = 273; public float Aqua { get; set; } = 0; public bool LogThresholds { get; set; } = false; } } ``` Fix default color temperature values
```c# using System.Collections.Generic; namespace Common.Data { public class TemperatureOverlayState { public bool CustomRangesEnabled { get; set; } = true; public List<float> Temperatures => new List<float> { Aqua, Turquoise, Blue, Green, Lime, Orange, RedOrange, Red }; public float Red { get; set; } = 1800; public float RedOrange { get; set; } = 0.1f; public float Orange { get; set; } = 323; public float Lime { get; set; } = 293; public float Green { get; set; } = 273; public float Blue { get; set; } = 0.2f; public float Turquoise { get; set; } = 0.1f; public float Aqua { get; set; } = 0; public bool LogThresholds { get; set; } = false; } } ```
c084d3e0-bcd2-428d-bb22-eedb90f01eb5
{ "language": "C#" }
```c# using Digirati.IIIF.Model.JsonLD; using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Service : JSONLDBase, IService { [JsonProperty(Order = 10, PropertyName = "profile")] public dynamic Profile { get; set; } [JsonProperty(Order = 11, PropertyName = "label")] public MetaDataValue Label { get; set; } } } ``` Add description to service resource
```c# using Digirati.IIIF.Model.JsonLD; using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Service : JSONLDBase, IService { [JsonProperty(Order = 10, PropertyName = "profile")] public dynamic Profile { get; set; } [JsonProperty(Order = 11, PropertyName = "label")] public MetaDataValue Label { get; set; } [JsonProperty(Order = 12, PropertyName = "description")] public MetaDataValue Description { get; set; } } } ```
5a6d3bc9-f697-4944-8e23-08ec532b1666
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SSMScripter.Runner; namespace SSMScripter.Config { public partial class RunnerConfigForm : Form { private RunConfig _runConfig; public RunnerConfigForm() { InitializeComponent(); } public RunnerConfigForm(RunConfig runConfig) : this() { _runConfig = runConfig; tbTool.Text = _runConfig.IsUndefined() ? String.Empty : (_runConfig.RunTool ?? String.Empty); tbArgs.Text = _runConfig.RunArgs ?? String.Empty; } private void btnOk_Click(object sender, EventArgs e) { _runConfig.RunTool = tbTool.Text; _runConfig.RunArgs = tbArgs.Text; DialogResult = DialogResult.OK; } private void btnTool_Click(object sender, EventArgs e) { using(OpenFileDialog dialog = new OpenFileDialog()) { dialog.InitialDirectory = Path.GetDirectoryName(tbTool.Text) ?? String.Empty; dialog.FileName = Path.GetFileName(tbTool.Text) ?? String.Empty; dialog.Filter = "Exe files (*.exe)|*.exe|All files (*.*)|*.*"; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { tbTool.Text = dialog.FileName; } } } } } ``` Fix exception caused by getting directory name from empty string in runner config editor
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SSMScripter.Runner; namespace SSMScripter.Config { public partial class RunnerConfigForm : Form { private RunConfig _runConfig; public RunnerConfigForm() { InitializeComponent(); } public RunnerConfigForm(RunConfig runConfig) : this() { _runConfig = runConfig; tbTool.Text = _runConfig.IsUndefined() ? String.Empty : (_runConfig.RunTool ?? String.Empty); tbArgs.Text = _runConfig.RunArgs ?? String.Empty; } private void btnOk_Click(object sender, EventArgs e) { _runConfig.RunTool = tbTool.Text; _runConfig.RunArgs = tbArgs.Text; DialogResult = DialogResult.OK; } private void btnTool_Click(object sender, EventArgs e) { using(OpenFileDialog dialog = new OpenFileDialog()) { if (!String.IsNullOrEmpty(tbTool.Text)) dialog.InitialDirectory = Path.GetDirectoryName(tbTool.Text); dialog.FileName = Path.GetFileName(tbTool.Text) ?? String.Empty; dialog.Filter = "Exe files (*.exe)|*.exe|All files (*.*)|*.*"; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { tbTool.Text = dialog.FileName; } } } } } ```
c9a926cc-5f3b-44db-aea8-6a85f29768fb
{ "language": "C#" }
```c# namespace NerdBank.GitVersioning.CloudBuildServices { using System; using System.Collections.Generic; using System.IO; using Nerdbank.GitVersioning; internal class GitHubActions : ICloudBuild { public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent"; public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null; public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null; public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA"); private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF"); public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } } } ``` Set env vars in GitHub Actions
```c# namespace NerdBank.GitVersioning.CloudBuildServices { using System; using System.Collections.Generic; using System.IO; using Nerdbank.GitVersioning; internal class GitHubActions : ICloudBuild { public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent"; public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null; public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null; public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA"); private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF"); public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr) { return new Dictionary<string, string>(); } public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr) { (stdout ?? Console.Out).WriteLine($"##[set-env name={name};]{value}"); return GetDictionaryFor(name, value); } private static IReadOnlyDictionary<string, string> GetDictionaryFor(string variableName, string value) { return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { GetEnvironmentVariableNameForVariable(variableName), value }, }; } private static string GetEnvironmentVariableNameForVariable(string name) => name.ToUpperInvariant().Replace('.', '_'); } } ```
65a23752-5e07-4232-881c-447faabec919
{ "language": "C#" }
```c# using System; using System.Data; using Dapper.FastCrud; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public class UnitOfWork : DbTransaction, IUnitOfWork { public SqlDialect SqlDialect { get; } private readonly Guid _guid = Guid.NewGuid(); public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable, bool sessionOnlyForThisUnitOfWork = false) : base(factory) { if (sessionOnlyForThisUnitOfWork) { Session = session; } Transaction = session.BeginTransaction(isolationLevel); SqlDialect = session.SqlDialect; } protected bool Equals(UnitOfWork other) { return _guid.Equals(other._guid); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((UnitOfWork) obj); } public override int GetHashCode() { return _guid.GetHashCode(); } public static bool operator ==(UnitOfWork left, UnitOfWork right) { return Equals(left, right); } public static bool operator !=(UnitOfWork left, UnitOfWork right) { return !Equals(left, right); } } } ``` Change uow to default to IsolationLevel.RepeatableRead
```c# using System; using System.Data; using Dapper.FastCrud; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data { public class UnitOfWork : DbTransaction, IUnitOfWork { public SqlDialect SqlDialect { get; } private readonly Guid _guid = Guid.NewGuid(); public UnitOfWork(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.RepeatableRead, bool sessionOnlyForThisUnitOfWork = false) : base(factory) { if (sessionOnlyForThisUnitOfWork) { Session = session; } Transaction = session.BeginTransaction(isolationLevel); SqlDialect = session.SqlDialect; } protected bool Equals(UnitOfWork other) { return _guid.Equals(other._guid); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((UnitOfWork) obj); } public override int GetHashCode() { return _guid.GetHashCode(); } public static bool operator ==(UnitOfWork left, UnitOfWork right) { return Equals(left, right); } public static bool operator !=(UnitOfWork left, UnitOfWork right) { return !Equals(left, right); } } } ```
4e82208f-9ceb-449b-9c36-b2936536c45d
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using Zenject; public class ScoreCounter : MonoBehaviour { [Inject] public StageStats Stats { get; private set; } void Start() { Stats.BallsTotal = Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length; StartCoroutine(Count()); } IEnumerator Count() { while (true) { yield return new WaitForSeconds(1); Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length; } } } ``` Revert to main menu on 0 balls left.
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using Zenject; public class ScoreCounter : MonoBehaviour { [Inject] public StageStats Stats { get; private set; } void Start() { Stats.BallsTotal = Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length; StartCoroutine(Count()); } IEnumerator Count() { while (true) { yield return new WaitForSeconds(1); Stats.BallsLeft = GetComponentsInChildren<Rigidbody>().Length; if (Stats.BallsLeft == 0) { SceneManager.LoadScene("MainMenu"); } } } } ```
b581524a-7118-4aea-993d-5cbf0350be89
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class ReloadScene : MonoBehaviour { GlobalControl globalController; bool allowLevelLoad = true; void OnEnable() { allowLevelLoad = true; } // Use this for initialization public void ReloadActiveScene () { if (allowLevelLoad) { allowLevelLoad = false; globalController = (GlobalControl)FindObjectOfType(typeof(GlobalControl)); globalController.globalMultiplayerManager.gameObject.SetActive(true); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } } } ``` Add delay for ReloadActiveScene to prevent stuck button
```c# using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class ReloadScene : MonoBehaviour { GlobalControl globalController; bool allowLevelLoad = true; void OnEnable() { allowLevelLoad = true; } // Use this for initialization public void ReloadActiveScene () { if (allowLevelLoad) { allowLevelLoad = false; Invoke("LoadScene", 0.33f); } } private void LoadScene() { globalController = (GlobalControl)FindObjectOfType(typeof(GlobalControl)); globalController.globalMultiplayerManager.gameObject.SetActive(true); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } } ```
09e3233a-b0e9-4a1e-b865-176bfb84b99b
{ "language": "C#" }
```c# using Nito.AsyncEx; using Octokit; using System; using System.Collections.Generic; using System.Linq; namespace Alteridem.GetChanges { class Program { static int Main(string[] args) { var options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine(options.GetUsage()); return -1; } AsyncContext.Run(() => MainAsync(options)); Console.WriteLine("*** Press ENTER to Exit ***"); Console.ReadLine(); return 0; } static async void MainAsync(Options options) { var github = new GitHubApi("nunit", "nunit"); var milestones = await github.GetAllMilestones(); var issues = await github.GetClosedIssues(); var noMilestoneIssues = from i in issues where i.Milestone == null select i; DisplayIssuesForMilestone("Issues with no milestone", noMilestoneIssues); foreach (var milestone in milestones) { var milestoneIssues = from i in issues where i.Milestone != null && i.Milestone.Number == milestone.Number select i; DisplayIssuesForMilestone(milestone.Title, milestoneIssues); } } static void DisplayIssuesForMilestone(string milestone, IEnumerable<Issue> issues) { Console.WriteLine("## {0}", milestone); Console.WriteLine(); foreach (var issue in issues) { Console.WriteLine(" * {0:####} {1}", issue.Number, issue.Title); } Console.WriteLine(); } } } ``` Use the options when connecting to GitHub
```c# using Nito.AsyncEx; using Octokit; using System; using System.Collections.Generic; using System.Linq; namespace Alteridem.GetChanges { class Program { static int Main(string[] args) { var options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine(options.GetUsage()); return -1; } AsyncContext.Run(() => MainAsync(options)); Console.WriteLine("*** Press ENTER to Exit ***"); Console.ReadLine(); return 0; } static async void MainAsync(Options options) { var github = new GitHubApi(options.Organization, options.Repository); var milestones = await github.GetAllMilestones(); var issues = await github.GetClosedIssues(); var noMilestoneIssues = from i in issues where i.Milestone == null select i; DisplayIssuesForMilestone("Issues with no milestone", noMilestoneIssues); foreach (var milestone in milestones) { var milestoneIssues = from i in issues where i.Milestone != null && i.Milestone.Number == milestone.Number select i; DisplayIssuesForMilestone(milestone.Title, milestoneIssues); } } static void DisplayIssuesForMilestone(string milestone, IEnumerable<Issue> issues) { Console.WriteLine("## {0}", milestone); Console.WriteLine(); foreach (var issue in issues) { Console.WriteLine(" * {0:####} {1}", issue.Number, issue.Title); } Console.WriteLine(); } } } ```
60591f60-7906-43d4-b1bf-82995d84f0ff
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; namespace Bugsnag { public class Event : Dictionary<string, object> { public Event(IConfiguration configuration, System.Exception exception, Severity severity) { this["payloadVersion"] = 2; this["exceptions"] = new Exceptions(exception).ToArray(); this["app"] = new App(configuration); switch (severity) { case Severity.Info: this["severity"] = "info"; break; case Severity.Warning: this["severity"] = "warning"; break; default: this["severity"] = "error"; break; } } public Exception[] Exceptions { get { return this["exceptions"] as Exception[]; } set { this.AddToPayload("exceptions", value); } } } } ``` Allow setting grouping hash and context
```c# using System.Collections.Generic; using System.Linq; namespace Bugsnag { public class Event : Dictionary<string, object> { public Event(IConfiguration configuration, System.Exception exception, Severity severity) { this["payloadVersion"] = 4; this["exceptions"] = new Exceptions(exception).ToArray(); this["app"] = new App(configuration); switch (severity) { case Severity.Info: this["severity"] = "info"; break; case Severity.Warning: this["severity"] = "warning"; break; default: this["severity"] = "error"; break; } } public Exception[] Exceptions { get { return this["exceptions"] as Exception[]; } set { this.AddToPayload("exceptions", value); } } public string Context { get { return this["context"] as string; } set { this.AddToPayload("context", value); } } public string GroupingHash { get { return this["groupingHash"] as string; } set { this.AddToPayload("groupingHash", value); } } } } ```
b87a8dc9-c4dd-4c3a-b366-492c91fa4445
{ "language": "C#" }
```c# /* * John.Hall <john.hall@camtechconsultants.com> * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved. */ using System; using System.Collections.Generic; namespace CTC.CvsntGitImporter.Utils { /// <summary> /// Extension methods for IEnumerable. /// </summary> static class IEnumerableExtensions { /// <summary> /// Perform the equivalent of String.Join on a sequence. /// </summary> /// <typeparam name="T">the type of the elements of source</typeparam> /// <param name="source">the sequence of values to join</param> /// <param name="separator">a string to insert between each item</param> /// <returns>a string containing the items in the sequence concenated and separated by the separator</returns> public static string StringJoin<T>(this IEnumerable<T> source, string separator) { return String.Join(separator, source); } } }``` Add ToHashSet extension methods on IEnumerable.
```c# /* * John.Hall <john.hall@camtechconsultants.com> * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved. */ using System; using System.Collections.Generic; namespace CTC.CvsntGitImporter.Utils { /// <summary> /// Extension methods for IEnumerable. /// </summary> static class IEnumerableExtensions { /// <summary> /// Perform the equivalent of String.Join on a sequence. /// </summary> /// <typeparam name="T">the type of the elements of source</typeparam> /// <param name="source">the sequence of values to join</param> /// <param name="separator">a string to insert between each item</param> /// <returns>a string containing the items in the sequence concenated and separated by the separator</returns> public static string StringJoin<T>(this IEnumerable<T> source, string separator) { return String.Join(separator, source); } /// <summary> /// Create a HashSet from a list of items. /// </summary> public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) { return new HashSet<T>(source); } /// <summary> /// Create a HashSet from a list of items. /// </summary> public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer) { return new HashSet<T>(source, comparer); } } }```
c9063681-665c-4b95-b035-dcfc52b8fa90
{ "language": "C#" }
```c# //----------------------------------------------------------------------- // <copyright file="ValidatingReceiver.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace CommSample { using System; using System.Threading.Tasks; internal sealed class ValidatingReceiver { private readonly Receiver receiver; private readonly DataOracle oracle; private byte lastSeen; private int lastCount; public ValidatingReceiver(MemoryChannel channel, Logger logger, int bufferSize, DataOracle oracle) { this.receiver = new Receiver(channel, logger, bufferSize); this.oracle = oracle; this.receiver.DataReceived += this.OnDataReceived; } public Task<long> RunAsync() { return this.receiver.RunAsync(); } private void OnDataReceived(object sender, DataEventArgs e) { for (int i = 0; i < e.BytesRead; ++i) { if (this.lastSeen != e.Buffer[i]) { if (this.lastSeen != 0) { this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount); } this.lastSeen = e.Buffer[i]; this.lastCount = 0; } ++this.lastCount; } } } } ``` Add missing final validation pass (bytes read == 0)
```c# //----------------------------------------------------------------------- // <copyright file="ValidatingReceiver.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace CommSample { using System; using System.Threading.Tasks; internal sealed class ValidatingReceiver { private readonly Receiver receiver; private readonly DataOracle oracle; private byte lastSeen; private int lastCount; public ValidatingReceiver(MemoryChannel channel, Logger logger, int bufferSize, DataOracle oracle) { this.receiver = new Receiver(channel, logger, bufferSize); this.oracle = oracle; this.receiver.DataReceived += this.OnDataReceived; } public Task<long> RunAsync() { return this.receiver.RunAsync(); } private void OnDataReceived(object sender, DataEventArgs e) { for (int i = 0; i < e.BytesRead; ++i) { if (this.lastSeen != e.Buffer[i]) { if (this.lastSeen != 0) { this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount); } this.lastSeen = e.Buffer[i]; this.lastCount = 0; } ++this.lastCount; } if (e.BytesRead == 0) { this.oracle.VerifyLastSeen(this.lastSeen, this.lastCount); } } } } ```
792a25bb-25c4-402e-a4a6-0c40c791d449
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ploeh.AutoFixture { public static class IFixtureExtensions { public static IEnumerable<T> Repeat<T>(this IFixture fixture, Func<T> function) { throw new NotImplementedException(); } } } ``` Implement code making the previously failing unit test pass.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ploeh.AutoFixture { public static class IFixtureExtensions { public static IEnumerable<T> Repeat<T>(this IFixture fixture, Func<T> function) { if (fixture == null) { throw new ArgumentNullException("fixture"); } throw new NotImplementedException(); } } } ```
01f1cb0d-a7b5-4234-9863-975e7b62e016
{ "language": "C#" }
```c# // Copyright 2016 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Microsoft.AspNetCore.Mvc; using NodaTime.TimeZones; using NodaTime.TzValidate.NodaDump; using System.IO; using System.Net; namespace NodaTime.Web.Controllers { public class TzValidateController : Controller { // This will do something soon :) [Route("/tzvalidate/generate")] public IActionResult Generate(int startYear = 1, int endYear = 2035) { var source = TzdbDateTimeZoneSource.Default; var writer = new StringWriter(); var options = new Options { FromYear = startYear, ToYear = endYear }; var dumper = new ZoneDumper(source, options); dumper.Dump(writer); return new ContentResult { Content = writer.ToString(), ContentType = "text/plain", StatusCode = (int) HttpStatusCode.OK }; } } } ``` Allow a zone and version to be specified in the tzvalidate controller
```c# // Copyright 2016 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Microsoft.AspNetCore.Mvc; using NodaTime.TimeZones; using NodaTime.TzValidate.NodaDump; using NodaTime.Web.Models; using System.IO; using System.Linq; using System.Net; namespace NodaTime.Web.Controllers { public class TzValidateController : Controller { private readonly ITzdbRepository repository; public TzValidateController(ITzdbRepository repository) => this.repository = repository; [Route("/tzvalidate/generate")] public IActionResult Generate(int startYear = 1, int endYear = 2035, string zone = null, string version = null) { if (startYear < 1 || endYear > 3000 || startYear > endYear) { return BadRequest("Invalid start/end year combination"); } var source = TzdbDateTimeZoneSource.Default; if (version != null) { var release = repository.GetRelease($"tzdb{version}.nzd"); if (release == null) { return BadRequest("Unknown version"); } source = TzdbDateTimeZoneSource.FromStream(release.GetContent()); } if (zone != null && !source.GetIds().Contains(zone)) { return BadRequest("Unknown zone"); } var writer = new StringWriter(); var options = new Options { FromYear = startYear, ToYear = endYear, ZoneId = zone }; var dumper = new ZoneDumper(source, options); dumper.Dump(writer); return new ContentResult { Content = writer.ToString(), ContentType = "text/plain", StatusCode = (int) HttpStatusCode.OK }; } } } ```
7a84128d-2a17-4c9c-aeca-145334529dd4
{ "language": "C#" }
```c# using Autofac; using Chassis.Features; using Chassis.Types; namespace Chassis.Startup { public class StartupFeature : Feature { public override void RegisterComponents(ContainerBuilder builder, TypePool pool) { builder.RegisterType<StartupBootstrapper>() .SingleInstance() .AsSelf(); var actions = pool.FindImplementorsOf<IStartupStep>(); foreach (var action in actions) { builder.RegisterType(action) .As<IStartupStep>() .AsSelf(); } var webActions = pool.FindImplementorsOf<IWebStartupStep>(); foreach (var action in webActions) { builder.RegisterType(action) .As<IWebStartupStep>() .AsSelf(); } } } }``` Change Scope to support multi-tenant scenarios
```c# using Autofac; using Chassis.Features; using Chassis.Types; namespace Chassis.Startup { public class StartupFeature : Feature { public override void RegisterComponents(ContainerBuilder builder, TypePool pool) { builder.RegisterType<StartupBootstrapper>() .InstancePerLifetimeScope() .AsSelf(); var actions = pool.FindImplementorsOf<IStartupStep>(); foreach (var action in actions) { builder.RegisterType(action) .As<IStartupStep>() .AsSelf(); } var webActions = pool.FindImplementorsOf<IWebStartupStep>(); foreach (var action in webActions) { builder.RegisterType(action) .As<IWebStartupStep>() .AsSelf(); } } } } ```
06ce4652-9fe1-4e52-88ff-801131ec04bc
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace CalSync.Infrastructure { class Config { public int SyncRangeDays { get; private set; } public string TargetEmailAddress { get; private set; } public bool Receive { get; private set; } public bool DetailedAppointment { get; private set; } public bool Send { get; private set; } public String ErrorMessage { get; private set; } public static Config Read() { try { return new Config() { SyncRangeDays = int.Parse(ConfigurationManager.AppSettings["SyncRangeDays"]), TargetEmailAddress = ConfigurationManager.AppSettings["TargetEmailAddress"], Receive = bool.Parse(ConfigurationManager.AppSettings["Receive"] ?? "true"), DetailedAppointment = bool.Parse(ConfigurationManager.AppSettings["DetailedAppointment"] ?? "true"), Send = bool.Parse(ConfigurationManager.AppSettings["Send"] ?? "true"), }; } catch(Exception e) { if(e is ConfigurationErrorsException || e is FormatException || e is OverflowException ) { return new Config() { ErrorMessage = e.Message }; } throw; } } } } ``` Change default for DetailedAppointments to 'false'
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace CalSync.Infrastructure { class Config { public int SyncRangeDays { get; private set; } public string TargetEmailAddress { get; private set; } public bool Receive { get; private set; } public bool Send { get; private set; } public bool DetailedAppointment { get; private set; } public String ErrorMessage { get; private set; } public static Config Read() { try { return new Config() { SyncRangeDays = int.Parse(ConfigurationManager.AppSettings["SyncRangeDays"]), TargetEmailAddress = ConfigurationManager.AppSettings["TargetEmailAddress"], Receive = bool.Parse(ConfigurationManager.AppSettings["Receive"] ?? "true"), Send = bool.Parse(ConfigurationManager.AppSettings["Send"] ?? "true"), DetailedAppointment = bool.Parse(ConfigurationManager.AppSettings["DetailedAppointment"] ?? "false"), }; } catch(Exception e) { if(e is ConfigurationErrorsException || e is FormatException || e is OverflowException ) { return new Config() { ErrorMessage = e.Message }; } throw; } } } } ```
c6ff3d06-b016-4345-a320-5c582d7790cc
{ "language": "C#" }
```c# using System; using System.Linq; using System.Web.Mvc; using FujiyBlog.Core.DomainObjects; namespace FujiyBlog.Web.Infrastructure { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizePermissionAttribute : AuthorizeAttribute { public AuthorizePermissionAttribute(params Permission[] permissions) { if (permissions == null) { throw new ArgumentNullException("permissions"); } Roles = string.Join(",", permissions.Select(r => r.ToString())); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); filterContext.HttpContext.Response.StatusCode = 401; filterContext.HttpContext.Response.WriteFile("~/errors/401.htm"); filterContext.HttpContext.Response.End(); } } }``` Fix to work with Anonymous Roles
```c# using System; using System.Linq; using System.Security.Principal; using System.Web; using System.Web.Mvc; using FujiyBlog.Core.DomainObjects; using FujiyBlog.Core.Extensions; namespace FujiyBlog.Web.Infrastructure { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizePermissionAttribute : AuthorizeAttribute { public AuthorizePermissionAttribute(params Permission[] permissions) { if (permissions == null) { throw new ArgumentNullException("permissions"); } Roles = string.Join(",", permissions.Select(r => r.ToString())); } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } IPrincipal user = httpContext.User; var usersSplit = SplitString(Users); var rolesSplit = SplitString(Roles).Select(x => (Permission) Enum.Parse(typeof (Permission), x)).ToArray(); if (usersSplit.Length > 0 && !usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) { return false; } if (rolesSplit.Length > 0 && !rolesSplit.Any(user.IsInRole)) { return false; } return true; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); filterContext.HttpContext.Response.StatusCode = 401; filterContext.HttpContext.Response.WriteFile("~/errors/401.htm"); filterContext.HttpContext.Response.End(); } static string[] SplitString(string original) { if (String.IsNullOrEmpty(original)) { return new string[0]; } var split = from piece in original.Split(',') let trimmed = piece.Trim() where !String.IsNullOrEmpty(trimmed) select trimmed; return split.ToArray(); } } }```
6cb63d98-5744-494c-9c0b-f86471870215
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NowinWebServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("NowinWebServer")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")] ``` Rename finished, Bumped version to 0.9
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Nowin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("Nowin")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")] ```
909082cc-69c3-41be-a8d0-c6e6e844b44e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RichardSzalay.MockHttp.Matchers { public class QueryStringMatcher : IMockedRequestMatcher { readonly IEnumerable<KeyValuePair<string, string>> values; public QueryStringMatcher(string queryString) : this(ParseQueryString(queryString)) { } public QueryStringMatcher(IEnumerable<KeyValuePair<string, string>> values) { this.values = values; } public bool Matches(System.Net.Http.HttpRequestMessage message) { var queryString = ParseQueryString(message.RequestUri.Query.TrimStart('?')); return values.All(matchPair => queryString.Any(p => p.Key == matchPair.Key && p.Value == matchPair.Value)); } internal static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string input) { return input.TrimStart('?').Split('&') .Select(pair => StringUtil.Split(pair, '=', 2)) .Select(pair => new KeyValuePair<string, string>( Uri.UnescapeDataString(pair[0]), pair.Length == 2 ? Uri.UnescapeDataString(pair[1]) : null )) .ToList(); } } } ``` Update key-only querystring comparisons to use "" rather than null to make it more compatible with form data
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RichardSzalay.MockHttp.Matchers { public class QueryStringMatcher : IMockedRequestMatcher { readonly IEnumerable<KeyValuePair<string, string>> values; public QueryStringMatcher(string queryString) : this(ParseQueryString(queryString)) { } public QueryStringMatcher(IEnumerable<KeyValuePair<string, string>> values) { this.values = values; } public bool Matches(System.Net.Http.HttpRequestMessage message) { var queryString = ParseQueryString(message.RequestUri.Query.TrimStart('?')); return values.All(matchPair => queryString.Any(p => p.Key == matchPair.Key && p.Value == matchPair.Value)); } internal static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string input) { return input.TrimStart('?').Split('&') .Select(pair => StringUtil.Split(pair, '=', 2)) .Select(pair => new KeyValuePair<string, string>( Uri.UnescapeDataString(pair[0]), pair.Length == 2 ? Uri.UnescapeDataString(pair[1]) : "" )) .ToList(); } } } ```
6cff1cc2-8651-4f26-b456-598ff6d95660
{ "language": "C#" }
```c# using System.Runtime.Serialization; namespace Omise.Models { public enum OffsiteTypes { [EnumMember(Value = null)] None, [EnumMember(Value = "internet_banking_scb")] InternetBankingSCB, [EnumMember(Value = "internet_banking_bbl")] InternetBankingBBL, [EnumMember(Value = "internet_banking_ktb")] InternetBankingKTB, [EnumMember(Value = "internet_banking_bay")] InternetBankingBAY, [EnumMember(Value = "alipay")] AlipayOnline, [EnumMember(Value = "installment_bay")] InstallmentBAY, [EnumMember(Value = "installment_kbank")] InstallmentKBank, [EnumMember(Value = "bill_payment_tesco_lotus")] BillPaymentTescoLotus, [EnumMember(Value = "barcode_alipay")] BarcodeAlipay, [EnumMember(Value = "paynow")] Paynow, [EnumMember(Value = "points_citi")] PointsCiti, [EnumMember(Value = "promptpay")] PromptPay, [EnumMember(Value = "truemoney")] TrueMoney } } ``` Add offsite types for installment citi
```c# using System.Runtime.Serialization; namespace Omise.Models { public enum OffsiteTypes { [EnumMember(Value = null)] None, [EnumMember(Value = "internet_banking_scb")] InternetBankingSCB, [EnumMember(Value = "internet_banking_bbl")] InternetBankingBBL, [EnumMember(Value = "internet_banking_ktb")] InternetBankingKTB, [EnumMember(Value = "internet_banking_bay")] InternetBankingBAY, [EnumMember(Value = "alipay")] AlipayOnline, [EnumMember(Value = "installment_bay")] InstallmentBAY, [EnumMember(Value = "installment_kbank")] InstallmentKBank, [EnumMember(Value = "installment_citi")] InstallmentCiti, [EnumMember(Value = "bill_payment_tesco_lotus")] BillPaymentTescoLotus, [EnumMember(Value = "barcode_alipay")] BarcodeAlipay, [EnumMember(Value = "paynow")] Paynow, [EnumMember(Value = "points_citi")] PointsCiti, [EnumMember(Value = "promptpay")] PromptPay, [EnumMember(Value = "truemoney")] TrueMoney } } ```
f675e058-3b0d-4e53-8526-e2c2c3a2570f
{ "language": "C#" }
```c# using System.IO; using System.Linq; using System.Windows.Forms; using GUI.Utils; namespace GUI.Types.Viewers { public class ByteViewer : IViewer { public static bool IsAccepted() => true; public TabPage Create(VrfGuiContext vrfGuiContext, byte[] input) { var tab = new TabPage(); var resTabs = new TabControl { Dock = DockStyle.Fill, }; tab.Controls.Add(resTabs); var bvTab = new TabPage("Hex"); var bv = new System.ComponentModel.Design.ByteViewer { Dock = DockStyle.Fill, }; bvTab.Controls.Add(bv); resTabs.TabPages.Add(bvTab); if (input == null) { input = File.ReadAllBytes(vrfGuiContext.FileName); } if (!input.Contains<byte>(0x00)) { var textTab = new TabPage("Text"); var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = System.Text.Encoding.UTF8.GetString(input), }; textTab.Controls.Add(text); resTabs.TabPages.Add(textTab); resTabs.SelectedTab = textTab; } Program.MainForm.Invoke((MethodInvoker)(() => { bv.SetBytes(input); })); return tab; } } } ``` Normalize line endings in text viewer
```c# using System.IO; using System.Linq; using System.Windows.Forms; using GUI.Utils; namespace GUI.Types.Viewers { public class ByteViewer : IViewer { public static bool IsAccepted() => true; public TabPage Create(VrfGuiContext vrfGuiContext, byte[] input) { var tab = new TabPage(); var resTabs = new TabControl { Dock = DockStyle.Fill, }; tab.Controls.Add(resTabs); var bvTab = new TabPage("Hex"); var bv = new System.ComponentModel.Design.ByteViewer { Dock = DockStyle.Fill, }; bvTab.Controls.Add(bv); resTabs.TabPages.Add(bvTab); if (input == null) { input = File.ReadAllBytes(vrfGuiContext.FileName); } if (!input.Contains<byte>(0x00)) { var textTab = new TabPage("Text"); var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = Utils.Utils.NormalizeLineEndings(System.Text.Encoding.UTF8.GetString(input)), }; textTab.Controls.Add(text); resTabs.TabPages.Add(textTab); resTabs.SelectedTab = textTab; } Program.MainForm.Invoke((MethodInvoker)(() => { bv.SetBytes(input); })); return tab; } } } ```
a99089cf-a954-4e12-ad91-a93292f9fde9
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Numerics; namespace ValveResourceFormat.ResourceTypes.ModelAnimation { public class Frame { public Dictionary<string, FrameBone> Bones { get; } public Frame() { Bones = new Dictionary<string, FrameBone>(); } public void SetAttribute(string bone, string attribute, object data) { switch (attribute) { case "Position": GetBone(bone).Position = (Vector3)data; break; case "Angle": GetBone(bone).Angle = (Quaternion)data; break; case "data": //ignore break; #if DEBUG default: Console.WriteLine($"Unknown frame attribute '{attribute}' encountered"); break; #endif } } private FrameBone GetBone(string name) { if (!Bones.TryGetValue(name, out var bone)) { bone = new FrameBone(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1)); Bones[name] = bone; } return bone; } } } ``` Add separate overloads for Vector3/Quaternion to remove casts
```c# using System; using System.Collections.Generic; using System.Numerics; namespace ValveResourceFormat.ResourceTypes.ModelAnimation { public class Frame { public Dictionary<string, FrameBone> Bones { get; } public Frame() { Bones = new Dictionary<string, FrameBone>(); } public void SetAttribute(string bone, string attribute, Vector3 data) { switch (attribute) { case "Position": GetBone(bone).Position = data; break; case "data": //ignore break; #if DEBUG default: Console.WriteLine($"Unknown frame attribute '{attribute}' encountered with Vector3 data"); break; #endif } } public void SetAttribute(string bone, string attribute, Quaternion data) { switch (attribute) { case "Angle": GetBone(bone).Angle = data; break; case "data": //ignore break; #if DEBUG default: Console.WriteLine($"Unknown frame attribute '{attribute}' encountered with Quaternion data"); break; #endif } } private FrameBone GetBone(string name) { if (!Bones.TryGetValue(name, out var bone)) { bone = new FrameBone(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1)); Bones[name] = bone; } return bone; } } } ```
08ac796c-1604-41fe-a3a8-c5c7df5f1cc9
{ "language": "C#" }
```c# using System; using Microsoft.Extensions.Options; namespace Meraki { /// <summary> /// Initialize a <see cref="MerakiDashboardClientSettings"/> object. /// </summary> internal class MerakiDashboardClientSettingsSetup : ConfigureOptions<MerakiDashboardClientSettings> { /// <summary> /// Create a new <see cref="MerakiDashboardClientSettingsSetup"/> object. /// </summary> public MerakiDashboardClientSettingsSetup() : base(ConfigureOptions) { // Do nothing } /// <summary> /// Configure the <see cref="MerakiDashboardClientSettings"/> object. /// </summary> /// <param name="options"> /// The <see cref="MerakiDashboardClientSettings"/> object to configure. /// </param> private static void ConfigureOptions(MerakiDashboardClientSettings options) { options.Address = new Uri("https://dashboard.meraki.com", UriKind.Absolute); options.Key = ""; } } }``` Move default Dashboard API base address to constant
```c# using System; using Microsoft.Extensions.Options; namespace Meraki { /// <summary> /// Initialize a <see cref="MerakiDashboardClientSettings"/> object. /// </summary> internal class MerakiDashboardClientSettingsSetup : ConfigureOptions<MerakiDashboardClientSettings> { public static readonly string DefaultMerakiDashboardApiBaseAddress = "https://dashboard.meraki.com"; /// <summary> /// Create a new <see cref="MerakiDashboardClientSettingsSetup"/> object. /// </summary> public MerakiDashboardClientSettingsSetup() : base(ConfigureOptions) { // Do nothing } /// <summary> /// Configure the <see cref="MerakiDashboardClientSettings"/> object. /// </summary> /// <param name="options"> /// The <see cref="MerakiDashboardClientSettings"/> object to configure. /// </param> private static void ConfigureOptions(MerakiDashboardClientSettings options) { options.Address = new Uri(DefaultMerakiDashboardApiBaseAddress, UriKind.Absolute); options.Key = ""; } } }```
6c64b970-bc87-449b-9681-9d65a9eef0e6
{ "language": "C#" }
```c# using System.Linq; using System.Xml.Linq; namespace Tests.Daterpillar.Helpers { public static class ConnectionString { private static readonly string _configFile = "database.config.xml"; public static string GetMySQLServerConnectionString() { return GetConnectionString("mysql"); } public static string GetSQLServerConnectionString() { return GetConnectionString("mssql"); } internal static string GetConnectionString(string name) { var doc = XDocument.Load(_configFile); var connectionStrings = doc.Element("connectionStrings"); var record = (from element in connectionStrings.Descendants("add") where element.Attribute("name").Value == name select element) .First(); var connStr = new System.Data.Common.DbConnectionStringBuilder(); connStr.Add("server", record.Attribute("server").Value); connStr.Add("user", record.Attribute("user").Value); connStr.Add("password", record.Attribute("password").Value); return connStr.ConnectionString; } } }``` Change user.config format to app.confg schema
```c# using System.Configuration; namespace Tests.Daterpillar.Helpers { public static class ConnectionString { public static string GetMySQLServerConnectionString() { return GetConnectionString("mysql"); } public static string GetSQLServerConnectionString() { return GetConnectionString("mssql"); } internal static string GetConnectionString(string name) { var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = "user.config" }; var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); return config.ConnectionStrings.ConnectionStrings[name].ConnectionString; } } }```
9585275c-ea7e-4a70-ad1a-a23e32b48666
{ "language": "C#" }
```c# using CefSharp; namespace TweetDuck.Core.Handling{ class RequestHandlerBrowser : RequestHandler{ public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){ browser.Reload(); } public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){ if (request.ResourceType == ResourceType.Script && request.Url.Contains("google_analytics.")){ return CefReturnValue.Cancel; } return CefReturnValue.Continue; } } } ``` Tweak google analytics detection to work on twitter.com
```c# using CefSharp; namespace TweetDuck.Core.Handling{ class RequestHandlerBrowser : RequestHandler{ public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){ browser.Reload(); } public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){ if (request.ResourceType == ResourceType.Script && request.Url.Contains("analytics.")){ return CefReturnValue.Cancel; } return CefReturnValue.Continue; } } } ```
bb264125-ce6c-4502-ba66-f988e5e8e136
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Audio; using osu.Framework.IO.Stores; using osuTK.Graphics; namespace osu.Game.Skinning { public class DefaultLegacySkin : LegacySkin { public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager) : base(Info, storage, audioManager, string.Empty) { Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255); } public static SkinInfo Info { get; } = new SkinInfo { ID = -1, // this is temporary until database storage is decided upon. Name = "osu!classic", Creator = "team osu!" }; } } ``` Add back combo colours for osu!classic
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Audio; using osu.Framework.IO.Stores; using osuTK.Graphics; namespace osu.Game.Skinning { public class DefaultLegacySkin : LegacySkin { public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager) : base(Info, storage, audioManager, string.Empty) { Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255); Configuration.ComboColours.AddRange(new[] { new Color4(255, 192, 0, 255), new Color4(0, 202, 0, 255), new Color4(18, 124, 255, 255), new Color4(242, 24, 57, 255), }); } public static SkinInfo Info { get; } = new SkinInfo { ID = -1, // this is temporary until database storage is decided upon. Name = "osu!classic", Creator = "team osu!" }; } } ```
09c6cfa2-55b0-4420-bb5f-ca5e9bcb153d
{ "language": "C#" }
```c# using MomWorld.DataContexts; using MomWorld.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MomWorld.Controllers { public class HomeController : Controller { private ArticleDb articleDb = new ArticleDb(); private IdentityDb identityDb = new IdentityDb(); public ActionResult Index() { List<Article> articles = articleDb.Articles.OrderBy(art=>art.PostedDate).Take(5).ToList(); ViewData["Top5Articles"] = articles; if (User.Identity.IsAuthenticated) { var user = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name)); ViewData["CurrentUser"] = user; } return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [HttpPost] public void uploadnow(HttpPostedFileWrapper upload) { if (upload != null) { string ImageName = upload.FileName; string path = System.IO.Path.Combine(Server.MapPath("~/Images/uploads"), ImageName); upload.SaveAs(path); } } } }``` Update tạm fix lỗi Home/Index
```c# using MomWorld.DataContexts; using MomWorld.Entities; using MomWorld.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MomWorld.Controllers { public class HomeController : Controller { private ArticleDb articleDb = new ArticleDb(); private IdentityDb identityDb = new IdentityDb(); public ActionResult Index() { List<Article> articles = articleDb.Articles.OrderBy(art=>art.PostedDate).Take(5).ToList(); ViewData["Top5Articles"] = articles; if (User.Identity.IsAuthenticated) { var user = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name)); ViewData["CurrentUser"] = user; } else { //Fix sau ViewData["CurrentUser"] = new ApplicationUser(); } return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [HttpPost] public void uploadnow(HttpPostedFileWrapper upload) { if (upload != null) { string ImageName = upload.FileName; string path = System.IO.Path.Combine(Server.MapPath("~/Images/uploads"), ImageName); upload.SaveAs(path); } } } }```
60ada5a1-e251-4090-a973-906c932bddf2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Merlin.Extensions { public static class WeatherExtensions { public static void EnableFog(this Weather weather) { weather.fogSummer = new MinMax(4f, 54f); weather.fogWinter = new MinMax(0f, 45f); weather.fogMapSelect = new MinMax(8f, 70f); weather.fogNormalRain = new MinMax(1f, 50f); weather.fogHeavyRain = new MinMax(0f, 45f); } public static void DisableFog(this Weather weather) { weather.fogSummer = new MinMax(100, 100); weather.fogWinter = new MinMax(100, 100); weather.fogMapSelect = new MinMax(100, 100); weather.fogHeavyRain = new MinMax(100, 100); } } } ``` Update fog values (new maps are bigger)
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Merlin.Extensions { public static class WeatherExtensions { public static void EnableFog(this Weather weather) { weather.fogSummer = new MinMax(4f, 54f); weather.fogWinter = new MinMax(0f, 45f); weather.fogMapSelect = new MinMax(8f, 70f); weather.fogNormalRain = new MinMax(1f, 50f); weather.fogHeavyRain = new MinMax(0f, 45f); } public static void DisableFog(this Weather weather) { weather.fogSummer = new MinMax(150, 150); weather.fogWinter = new MinMax(150, 150); weather.fogMapSelect = new MinMax(150, 150); weather.fogNormalRain = new MinMax(150, 150); weather.fogHeavyRain = new MinMax(150, 150); } } } ```
e94cb58c-7d8a-4a21-9900-021237824347
{ "language": "C#" }
```c# using System; using NSemble.Core.Nancy; using NSemble.Modules.ContentPages.Models; using Raven.Client; namespace NSemble.Modules.ContentPages { public class ContentPagesModule : NSembleModule { public static readonly string HomepageSlug = "home"; public ContentPagesModule(IDocumentSession session) : base("ContentPages") { Get["/{slug?" + HomepageSlug + "}"] = p => { var slug = (string)p.slug; // For fastest loading, we define the content page ID to be the slug. Therefore, slugs have to be < 50 chars, probably // much shorter for readability. var cp = session.Load<ContentPage>(DocumentPrefix + ContentPage.FullContentPageId(slug)); if (cp == null) return "<p>The requested content page was not found</p>"; // we will return a 404 instead once the system stabilizes... Model.ContentPage = cp; return View["Read", Model]; }; Get["/error"] = o => { throw new NotSupportedException("foo"); }; } } }``` Fix page titles for ContentPages module
```c# using System; using NSemble.Core.Models; using NSemble.Core.Nancy; using NSemble.Modules.ContentPages.Models; using Raven.Client; namespace NSemble.Modules.ContentPages { public class ContentPagesModule : NSembleModule { public static readonly string HomepageSlug = "home"; public ContentPagesModule(IDocumentSession session) : base("ContentPages") { Get["/{slug?" + HomepageSlug + "}"] = p => { var slug = (string)p.slug; // For fastest loading, we define the content page ID to be the slug. Therefore, slugs have to be < 50 chars, probably // much shorter for readability. var cp = session.Load<ContentPage>(DocumentPrefix + ContentPage.FullContentPageId(slug)); if (cp == null) return "<p>The requested content page was not found</p>"; // we will return a 404 instead once the system stabilizes... Model.ContentPage = cp; ((PageModel) Model.Page).Title = cp.Title; return View["Read", Model]; }; Get["/error"] = o => { throw new NotSupportedException("foo"); }; } } }```
5381cf06-a5a3-45f5-bbdd-811f5655124e
{ "language": "C#" }
```c# namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { Tensor<double> result = new Tensor<double>(); result.SetValue(tensor1.GetValue() + tensor2.GetValue()); return result; } } } ``` Refactor Add Doubles Operation to use GetValues and CloneWithValues
```c# namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { double[] values1 = tensor1.GetValues(); int l = values1.Length; double[] values2 = tensor2.GetValues(); double[] newvalues = new double[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] + values2[k]; return tensor1.CloneWithNewValues(newvalues); } } } ```
f57e3032-db42-4298-b6ed-0019dde1493a
{ "language": "C#" }
```c# using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Portal.CMS.Web.Areas.Admin.ViewModels.SettingManager { public class SetupViewModel { [Required] [DisplayName("Website Name")] public string WebsiteName { get; set; } [Required] [DisplayName("Website Description")] public string WebsiteDescription { get; set; } [DisplayName("Google Tracking Code")] public string GoogleAnalyticsId { get; set; } [DisplayName("Email From Address")] public string EmailFromAddress { get; set; } [DisplayName("SendGrid API Key")] public string SendGridApiKey { get; set; } [DisplayName("SendGrid Password")] public string SendGridPassword { get; set; } [DisplayName("CDN Address")] public string CDNAddress { get; set; } } }``` Remove Obselete ViewModel Property for SendGrid Password
```c# using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Portal.CMS.Web.Areas.Admin.ViewModels.SettingManager { public class SetupViewModel { [Required] [DisplayName("Website Name")] public string WebsiteName { get; set; } [Required] [DisplayName("Website Description")] public string WebsiteDescription { get; set; } [DisplayName("Google Tracking Code")] public string GoogleAnalyticsId { get; set; } [DisplayName("Email From Address")] public string EmailFromAddress { get; set; } [DisplayName("SendGrid API Key")] public string SendGridApiKey { get; set; } [DisplayName("CDN Address")] public string CDNAddress { get; set; } } }```
59769078-c91e-400d-9109-ca62d0e12cdd
{ "language": "C#" }
```c# using System; using System.IO; using System.Linq; using System.Text; namespace HandlebarsDotNet.Compiler.Lexer { internal class WordParser : Parser { private const string validWordStartCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$.@"; public override Token Parse(TextReader reader) { if (IsWord(reader)) { var buffer = AccumulateWord(reader); if (buffer.Contains("=")) { return Token.HashParameter(buffer); } else { return Token.Word(buffer); } } return null; } private bool IsWord(TextReader reader) { var peek = (char)reader.Peek(); return validWordStartCharacters.Contains(peek.ToString()); } private string AccumulateWord(TextReader reader) { StringBuilder buffer = new StringBuilder(); var inString = false; while (true) { if (!inString) { var peek = (char)reader.Peek(); if (peek == '}' || peek == '~' || peek == ')' || char.IsWhiteSpace(peek)) { break; } } var node = reader.Read(); if (node == -1) { throw new InvalidOperationException("Reached end of template before the expression was closed."); } if (node == '\'' || node == '"') { inString = !inString; } buffer.Append((char)node); } return buffer.ToString(); } } } ``` Fix whitespace bug with dictionary support
```c# using System; using System.IO; using System.Linq; using System.Text; namespace HandlebarsDotNet.Compiler.Lexer { internal class WordParser : Parser { private const string validWordStartCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$.@[]"; public override Token Parse(TextReader reader) { if (IsWord(reader)) { var buffer = AccumulateWord(reader); if (buffer.Contains("=")) { return Token.HashParameter(buffer); } else { return Token.Word(buffer); } } return null; } private bool IsWord(TextReader reader) { var peek = (char)reader.Peek(); return validWordStartCharacters.Contains(peek.ToString()); } private string AccumulateWord(TextReader reader) { StringBuilder buffer = new StringBuilder(); var inString = false; while (true) { if (!inString) { var peek = (char)reader.Peek(); if (peek == '}' || peek == '~' || peek == ')' || (char.IsWhiteSpace(peek) && !buffer.ToString().Contains("["))) { break; } } var node = reader.Read(); if (node == -1) { throw new InvalidOperationException("Reached end of template before the expression was closed."); } if (node == '\'' || node == '"') { inString = !inString; } buffer.Append((char)node); } return buffer.ToString().Trim(); } } } ```
8bcda700-1728-4949-aad5-7bd9f265b360
{ "language": "C#" }
```c# using System; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.IdGenerators; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver; using RightpointLabs.ConferenceRoom.Domain.Models; using RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Models; namespace RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Collections { public abstract class EntityCollectionDefinition<T> where T : Entity { protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler) { if (connectionHandler == null) throw new ArgumentNullException("connectionHandler"); // ReSharper disable once VirtualMemberCallInConstructor Collection = connectionHandler.Database.GetCollection<T>(CollectionName); // setup serialization if (!BsonClassMap.IsClassMapRegistered(typeof(Entity))) { try { BsonClassMap.RegisterClassMap<Entity>( cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(i => i.Id)); cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId)); }); } catch (ArgumentException) { // this fails with an argument exception at startup, but otherwise works fine. Probably should try to figure out why, but ignoring it is easier :( } } } public readonly MongoCollection<T> Collection; protected virtual string CollectionName => typeof(T).Name.Replace("Entity", "").ToLower() + "s"; } } ``` Enable Mongo entity auto-create and auto-ID
```c# using System; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.IdGenerators; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver; using RightpointLabs.ConferenceRoom.Domain.Models; using RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Models; namespace RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Collections { public abstract class EntityCollectionDefinition<T> where T : Entity { protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler) { if (connectionHandler == null) throw new ArgumentNullException("connectionHandler"); // ReSharper disable once VirtualMemberCallInConstructor Collection = connectionHandler.Database.GetCollection<T>(CollectionName, new MongoCollectionSettings() { AssignIdOnInsert = true}); // setup serialization if (!BsonClassMap.IsClassMapRegistered(typeof(Entity))) { if (!Collection.Exists()) { // ReSharper disable once VirtualMemberCallInConstructor Collection.Database.CreateCollection(CollectionName); } try { BsonClassMap.RegisterClassMap<Entity>( cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(i => i.Id)); cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId)); }); } catch (ArgumentException) { // this fails with an argument exception at startup, but otherwise works fine. Probably should try to figure out why, but ignoring it is easier :( } } } public readonly MongoCollection<T> Collection; protected virtual string CollectionName => typeof(T).Name.Replace("Entity", "").ToLower() + "s"; } } ```
42d466fb-7fa1-4659-8802-0fa515a9661d
{ "language": "C#" }
```c# using UnityEngine; public class AttackHandler : MonoBehaviour { [HideInInspector] public float damage; [HideInInspector] public float duration; [HideInInspector] public BoxCollider hitBox; private float timer = 0f; void Start() { hitBox = gameObject.GetComponent<BoxCollider>(); } void Update() { timer += Time.deltaTime; if(timer >= duration) { timer = 0f; hitBox.enabled = false; } } void OnTriggerEnter(Collider other) { bool isPlayer = other.GetComponent<Collider>().CompareTag("Player"); if(isPlayer) { // Debug.Log("ATTACK"); } } } ``` Add damage capabilities to the enemy
```c# using UnityEngine; public class AttackHandler : MonoBehaviour { [HideInInspector] public float damage; [HideInInspector] public float duration; [HideInInspector] public BoxCollider hitBox; private float timer = 0f; void Start() { hitBox = gameObject.GetComponent<BoxCollider>(); } void Update() { timer += Time.deltaTime; if(timer >= duration) { timer = 0f; hitBox.enabled = false; } } void OnTriggerEnter(Collider other) { bool isPlayer = other.GetComponent<Collider>().CompareTag("Player"); if(isPlayer) { other.gameObject.GetComponent<CharacterStatus>().life.decrease(damage); } } } ```
b783805a-9735-43a1-9a2d-99eef63acf5a
{ "language": "C#" }
```c# using NUnit.Framework; using tungsten.core.Elements; using tungsten.core.Search; using tungsten.nunit; namespace tungsten.sampletest { [TestFixture] public class CheckBoxTest : TestBase { [Test] public void Hupp() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.AssertThat(x => x.IsChecked(), Is.True); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } } }``` Split CheckBox test into two, give better name.
```c# using NUnit.Framework; using tungsten.core.Elements; using tungsten.core.Search; using tungsten.nunit; namespace tungsten.sampletest { [TestFixture] public class CheckBoxTest : TestBase { [Test] public void CheckBoxIsChecked() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.AssertThat(x => x.IsChecked(), Is.True); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } [Test] public void CheckBoxChangeIsChecked() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } } }```
3a11b3a1-8068-49fc-a266-40a791981eb1
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Exceptionless.Core.Pipeline; using Exceptionless.Core.Extensions; using Exceptionless.Core.Models; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; using Microsoft.Extensions.Logging; namespace Exceptionless.Core.Plugins.EventParser { [Priority(0)] public class JsonEventParserPlugin : PluginBase, IEventParserPlugin { private readonly JsonSerializerSettings _settings; private readonly JsonSerializer _serializer; public JsonEventParserPlugin(IOptions<AppOptions> options, JsonSerializerSettings settings) : base(options) { _settings = settings; _serializer = JsonSerializer.CreateDefault(_settings); } public List<PersistentEvent> ParseEvents(string input, int apiVersion, string userAgent) { if (apiVersion < 2) return null; var events = new List<PersistentEvent>(); var reader = new JsonTextReader(new StringReader(input)); reader.DateParseHandling = DateParseHandling.None; while (reader.Read()) { if (reader.TokenType == JsonToken.StartObject) { var ev = JToken.ReadFrom(reader); var data = ev["data"]; if (data != null) { foreach (var property in data.Children<JProperty>()) { // strip out large data entries if (property.Value.ToString().Length > 50000) { property.Value = "(Data Too Large)"; } } } try { events.Add(ev.ToObject<PersistentEvent>(_serializer)); } catch (Exception ex) { _logger.LogError(ex, "Error deserializing event."); } } } return events.Count > 0 ? events : null; } } } ``` Revert Strip large data values out of events
```c# using System; using System.Collections.Generic; using Exceptionless.Core.Pipeline; using Exceptionless.Core.Extensions; using Exceptionless.Core.Models; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Exceptionless.Core.Plugins.EventParser { [Priority(0)] public class JsonEventParserPlugin : PluginBase, IEventParserPlugin { private readonly JsonSerializerSettings _settings; public JsonEventParserPlugin(IOptions<AppOptions> options, JsonSerializerSettings settings) : base(options) { _settings = settings; } public List<PersistentEvent> ParseEvents(string input, int apiVersion, string userAgent) { if (apiVersion < 2) return null; var events = new List<PersistentEvent>(); switch (input.GetJsonType()) { case JsonType.Object: { if (input.TryFromJson(out PersistentEvent ev, _settings)) events.Add(ev); break; } case JsonType.Array: { if (input.TryFromJson(out PersistentEvent[] parsedEvents, _settings)) events.AddRange(parsedEvents); break; } } return events.Count > 0 ? events : null; } } } ```
de877c79-a8f3-4d54-8b38-a2915111c190
{ "language": "C#" }
```c# namespace elbsms_core { internal static class Extensions { internal static bool Bit(this byte v, int bit) { int mask = 1 << bit; return (v & mask) == mask; } internal static bool Bit(this int v, int bit) { int mask = 1 << bit; return (v & mask) == mask; } internal static bool EvenParity(this int v) { v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; return (v & 1) != 1; } } } ``` Update the mask check in the Bit() extension method
```c# namespace elbsms_core { internal static class Extensions { internal static bool Bit(this byte v, int bit) { int mask = 1 << bit; return (v & mask) != 0; } internal static bool Bit(this int v, int bit) { int mask = 1 << bit; return (v & mask) != 0; } internal static bool EvenParity(this int v) { v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; return (v & 1) != 1; } } } ```
756500d3-4aee-4cbc-a86f-26fc8bd40c18
{ "language": "C#" }
```c# using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using SoundCloud.Api; using SoundCloud.Api.Entities; using SoundCloud.Api.Entities.Enums; using SoundCloud.Api.QueryBuilders; namespace ConsoleApp { internal static class Program { private static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection.AddSoundCloudClient(string.Empty, args[0]); using (var provider = serviceCollection.BuildServiceProvider()) { var client = provider.GetService<SoundCloudClient>(); var entity = await client.Resolve.GetEntityAsync("https://soundcloud.com/diplo"); if (entity.Kind != Kind.User) { Console.WriteLine("Couldn't resolve account of diplo"); return; } var diplo = entity as User; Console.WriteLine($"Found: {diplo.Username} @ {diplo.PermalinkUrl}"); var tracks = await client.Users.GetTracksAsync(diplo, 10); Console.WriteLine(); Console.WriteLine("Latest 10 Tracks:"); foreach (var track in tracks) { Console.WriteLine(track.Title); } var majorLazerResults = await client.Tracks.GetAllAsync(new TrackQueryBuilder { SearchString = "Major Lazer", Limit = 10 }); Console.WriteLine(); Console.WriteLine("Found Major Lazer Tracks:"); foreach (var track in majorLazerResults) { Console.WriteLine(track.Title); } } } } }``` Move to .NET Standard - cleanup
```c# using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using SoundCloud.Api; using SoundCloud.Api.Entities; using SoundCloud.Api.Entities.Enums; using SoundCloud.Api.QueryBuilders; namespace ConsoleApp { internal static class Program { private static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection.AddSoundCloudClient(string.Empty, args[0]); using (var provider = serviceCollection.BuildServiceProvider()) { var client = provider.GetService<SoundCloudClient>(); var entity = await client.Resolve.GetEntityAsync("https://soundcloud.com/diplo"); if (entity.Kind != Kind.User) { Console.WriteLine("Couldn't resolve account of diplo"); return; } var diplo = entity as User; Console.WriteLine($"Found: {diplo.Username} @ {diplo.PermalinkUrl}"); var tracks = await client.Users.GetTracksAsync(diplo, 10); Console.WriteLine(); Console.WriteLine("Latest 10 Tracks:"); foreach (var track in tracks) { Console.WriteLine(track.Title); } var majorLazerResults = await client.Tracks.GetAllAsync(new TrackQueryBuilder { SearchString = "Major Lazer", Limit = 10 }); Console.WriteLine(); Console.WriteLine("Found Major Lazer Tracks:"); foreach (var track in majorLazerResults) { Console.WriteLine(track.Title); } } } } }```
664c0174-f428-442e-9f17-6e5285ec861a
{ "language": "C#" }
```c# using Bugsnag; using Bugsnag.Clients; using EarTrumpet.Extensions; using System; using System.Diagnostics; using System.IO; using Windows.ApplicationModel; namespace EarTrumpet.Services { class ErrorReportingService { internal static void Initialize() { try { #if DEBUG WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey"); #endif WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal"; WPFClient.Start(); WPFClient.Config.BeforeNotify(OnBeforeNotify); } catch (Exception ex) { Trace.WriteLine(ex); } } private static bool OnBeforeNotify(Event error) { error.Metadata.AddToTab("Device", "machineName", "<redacted>"); error.Metadata.AddToTab("Device", "hostname", "<redacted>"); return true; } } } ``` Add some settings to bugsnag
```c# using Bugsnag; using Bugsnag.Clients; using EarTrumpet.Extensions; using EarTrumpet.Misc; using System; using System.Diagnostics; using System.IO; using Windows.ApplicationModel; namespace EarTrumpet.Services { class ErrorReportingService { internal static void Initialize() { try { #if DEBUG WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey"); #endif WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal"; WPFClient.Start(); WPFClient.Config.BeforeNotify(OnBeforeNotify); } catch (Exception ex) { Trace.WriteLine(ex); } } private static bool OnBeforeNotify(Event error) { // Remove default metadata we don't need nor want. error.Metadata.AddToTab("Device", "machineName", "<redacted>"); error.Metadata.AddToTab("Device", "hostname", "<redacted>"); error.Metadata.AddToTab("AppSettings", "IsLightTheme", GetNoError(() => SystemSettings.IsLightTheme)); error.Metadata.AddToTab("AppSettings", "IsRTL", GetNoError(() => SystemSettings.IsRTL)); error.Metadata.AddToTab("AppSettings", "IsTransparencyEnabled", GetNoError(() => SystemSettings.IsTransparencyEnabled)); error.Metadata.AddToTab("AppSettings", "UseAccentColor", GetNoError(() => SystemSettings.UseAccentColor)); return true; } private static string GetNoError(Func<object> get) { try { var ret = get(); return ret == null ? "null" : ret.ToString(); } catch (Exception ex) { return $"{ex}"; } } } } ```
e0329c84-6b51-4893-ba94-ed16ef56bf3a
{ "language": "C#" }
```c# namespace Kudu.Contracts.Functions { public class FunctionTestData { // test shows test_data of size 8310000 bytes still delivers as an ARM package // whereas test_data of size 8388608 bytes fails public const long PackageMaxSizeInBytes = 8300000; public long BytesLeftInPackage { get; set; } = PackageMaxSizeInBytes; public bool DeductFromBytesLeftInPackage(long fileSize) { long spaceLeft = BytesLeftInPackage - fileSize; if (spaceLeft >= 0) { BytesLeftInPackage = spaceLeft; return true; } return false; } } } ``` Reduce size of test_data for ARM requests to 8MB/2
```c# namespace Kudu.Contracts.Functions { public class FunctionTestData { // ARM has a limit of 8 MB -> 8388608 bytes // divid by 2 to limit the over all size of test data to half of arm requirement to be safe. public const long PackageMaxSizeInBytes = 8388608 / 2; public long BytesLeftInPackage { get; set; } = PackageMaxSizeInBytes; public bool DeductFromBytesLeftInPackage(long fileSize) { long spaceLeft = BytesLeftInPackage - fileSize; if (spaceLeft >= 0) { BytesLeftInPackage = spaceLeft; return true; } return false; } } }```
09b35da9-b788-4ec9-b46f-d4b19d9a743e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using MetroTrilithon.Serialization; namespace TirkxDownloader.Models.Settings { public class DownloadingSetting { public static SerializableProperty<int> MaximumBytesPerSec { get; } = new SerializableProperty<int>(GetKey(), SettingsProviders.Local, 0); public static SerializableProperty<byte> MaxConcurrentDownload { get; } = new SerializableProperty<byte>(GetKey(), SettingsProviders.Local, 1); private static string GetKey([CallerMemberName] string caller = "") { return nameof(DownloadingSetting) + "." + caller; } } } ``` Change type of MaximumBytesPerSec to long
```c# using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using MetroTrilithon.Serialization; namespace TirkxDownloader.Models.Settings { public class DownloadingSetting { public static SerializableProperty<long> MaximumBytesPerSec { get; } = new SerializableProperty<long>(GetKey(), SettingsProviders.Local, 0); public static SerializableProperty<byte> MaxConcurrentDownload { get; } = new SerializableProperty<byte>(GetKey(), SettingsProviders.Local, 1); private static string GetKey([CallerMemberName] string caller = "") { return nameof(DownloadingSetting) + "." + caller; } } } ```
1c124c71-5cd2-4bc2-997f-d6094486dc23
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using NBi.Core.Etl; using NBi.Xml.Items; namespace NBi.Xml.Decoration.Command { public class EtlRunXml : DecorationCommandXml, IEtlRunCommand { [XmlAttribute("server")] public string Server { get; set; } [XmlAttribute("path")] public string Path { get; set; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("username")] public string UserName { get; set; } [XmlAttribute("password")] public string Password { get; set; } [XmlAttribute("catalog")] public string Catalog { get; set; } [XmlAttribute("folder")] public string Folder { get; set; } [XmlAttribute("project")] public string Project { get; set; } [XmlAttribute("bits-32")] public bool Is32Bits { get; set; } [XmlIgnore] public List<EtlParameter> Parameters { get { return InternalParameters.ToList<EtlParameter>(); } set { throw new NotImplementedException(); } } [XmlElement("parameter")] public List<EtlParameterXml> InternalParameters { get; set; } public EtlRunXml() { InternalParameters = new List<EtlParameterXml>(); } } } ``` Add timeout to decoration etl-run
```c# using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using NBi.Core.Etl; using NBi.Xml.Items; namespace NBi.Xml.Decoration.Command { public class EtlRunXml : DecorationCommandXml, IEtlRunCommand { [XmlAttribute("server")] public string Server { get; set; } [XmlAttribute("path")] public string Path { get; set; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("username")] public string UserName { get; set; } [XmlAttribute("password")] public string Password { get; set; } [XmlAttribute("catalog")] public string Catalog { get; set; } [XmlAttribute("folder")] public string Folder { get; set; } [XmlAttribute("project")] public string Project { get; set; } [XmlAttribute("bits-32")] public bool Is32Bits { get; set; } [XmlAttribute("timeout")] public int Timeout { get; set; } [XmlIgnore] public List<EtlParameter> Parameters { get { return InternalParameters.ToList<EtlParameter>(); } set { throw new NotImplementedException(); } } [XmlElement("parameter")] public List<EtlParameterXml> InternalParameters { get; set; } public EtlRunXml() { InternalParameters = new List<EtlParameterXml>(); } } } ```
753e4d25-829e-4210-8752-a8c732b4f0f7
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace PixelPet.Commands { internal class GenerateTilemapCmd : CliCommand { public GenerateTilemapCmd() : base("Generate-Tilemap", new Parameter[] { new Parameter("palette-size", "ps", false, new ParameterValue("count", "16")), new Parameter("no-reduce", "nr", false), }) { } public override void Run(Workbench workbench, Cli cli) { cli.Log("Generating tilemap..."); int palSize = FindNamedParameter("--palette-size").Values[0].ToInt32(); bool noReduce = FindNamedParameter("--no-reduce").IsPresent; workbench.Tilemap = new Tilemap(workbench.Bitmap, workbench.Tileset, workbench.Palette, palSize, !noReduce); } } } ``` Add cropping options into Generate-Tilemap directly.
```c# using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace PixelPet.Commands { internal class GenerateTilemapCmd : CliCommand { public GenerateTilemapCmd() : base("Generate-Tilemap", new Parameter("palette-size", "ps", false, new ParameterValue("count", "16")), new Parameter("no-reduce", "nr", false), new Parameter("x", "x", false, new ParameterValue("pixels", "0")), new Parameter("y", "y", false, new ParameterValue("pixels", "0")), new Parameter("width", "w", false, new ParameterValue("pixels", "-1")), new Parameter("height", "h", false, new ParameterValue("pixels", "-1")) ) { } public override void Run(Workbench workbench, Cli cli) { cli.Log("Generating tilemap..."); int palSize = FindNamedParameter("--palette-size").Values[0].ToInt32(); bool noReduce = FindNamedParameter("--no-reduce" ).IsPresent; int x = FindNamedParameter("--x" ).Values[0].ToInt32(); int y = FindNamedParameter("--y" ).Values[0].ToInt32(); int w = FindNamedParameter("--width" ).Values[0].ToInt32(); int h = FindNamedParameter("--height" ).Values[0].ToInt32(); using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, cli)) { workbench.Tilemap = new Tilemap(bmp, workbench.Tileset, workbench.Palette, palSize, !noReduce); } } } } ```
3bba9f91-db3a-4e6f-820f-6593a5ce95ac
{ "language": "C#" }
```c# using System.Drawing; namespace TileSharp.Symbolizers { /// <summary> /// https://github.com/mapnik/mapnik/wiki/TextSymbolizer /// </summary> public class TextSymbolizer : Symbolizer { public readonly string LabelAttribute; public readonly PlacementType Placement; public readonly ContentAlignment Alignment; public readonly int FontSize; public readonly Color TextColor; public readonly Color TextHaloColor; /// <summary> /// The distance between repeated labels. /// 0: A single label is placed in the center. /// Based on Mapnik Spacing /// </summary> public readonly int Spacing; public TextSymbolizer(string labelAttribute, PlacementType placement, int fontSize, ContentAlignment alignment = ContentAlignment.MiddleCenter, int spacing = 0, Color? textColor = null) { LabelAttribute = labelAttribute; Placement = placement; Alignment = alignment; Spacing = spacing; FontSize = fontSize; TextColor = textColor ?? Color.Black; TextHaloColor = Color.White; } public enum PlacementType { Line, Point } } } ``` Add ability to set text halo color.
```c# using System.Drawing; namespace TileSharp.Symbolizers { /// <summary> /// https://github.com/mapnik/mapnik/wiki/TextSymbolizer /// </summary> public class TextSymbolizer : Symbolizer { public readonly string LabelAttribute; public readonly PlacementType Placement; public readonly ContentAlignment Alignment; public readonly int FontSize; public readonly Color TextColor; public readonly Color TextHaloColor; /// <summary> /// The distance between repeated labels. /// 0: A single label is placed in the center. /// Based on Mapnik Spacing /// </summary> public readonly int Spacing; public TextSymbolizer(string labelAttribute, PlacementType placement, int fontSize, ContentAlignment alignment = ContentAlignment.MiddleCenter, int spacing = 0, Color? textColor = null, Color? textHaloColor = null) { LabelAttribute = labelAttribute; Placement = placement; Alignment = alignment; Spacing = spacing; FontSize = fontSize; TextColor = textColor ?? Color.Black; TextHaloColor = textHaloColor ?? Color.White; } public enum PlacementType { Line, Point } } } ```
74317804-8a1e-4d1a-a453-1eebc4244793
{ "language": "C#" }
```c# using System.Collections.Generic; using HarryPotterUnity.Cards.Generic; using JetBrains.Annotations; namespace HarryPotterUnity.Cards.Spells.Transfigurations { [UsedImplicitly] public class MiceToSnuffboxes : GenericSpell { public override List<GenericCard> GetValidTargets() { var validCards = Player.InPlay.GetCreaturesInPlay(); validCards.AddRange(Player.OppositePlayer.InPlay.GetCreaturesInPlay()); return validCards; } protected override void SpellAction(List<GenericCard> selectedCards) { foreach(var card in selectedCards) { card.Player.Hand.Add(card, false); card.Player.InPlay.Remove(card); } } } } ``` Fix an animation bug with Mice to Snuffboxes
```c# using System.Collections.Generic; using HarryPotterUnity.Cards.Generic; using JetBrains.Annotations; namespace HarryPotterUnity.Cards.Spells.Transfigurations { [UsedImplicitly] public class MiceToSnuffboxes : GenericSpell { public override List<GenericCard> GetValidTargets() { var validCards = Player.InPlay.GetCreaturesInPlay(); validCards.AddRange(Player.OppositePlayer.InPlay.GetCreaturesInPlay()); return validCards; } protected override void SpellAction(List<GenericCard> selectedCards) { int i = 0; foreach(var card in selectedCards) { card.Player.Hand.Add(card, preview: false, adjustSpacing: card.Player.IsLocalPlayer && i == 1); card.Player.InPlay.Remove(card); i++; } } } } ```
8754df81-5203-4efb-86f7-58f0bca449a8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using ProjectMarkdown.Annotations; namespace ProjectMarkdown.ViewModels { public class MainWindowViewModel : INotifyPropertyChanged { private string _currentDocumentPath; public string CurrentDocumentPath { get { return _currentDocumentPath; } set { if (value == _currentDocumentPath) return; _currentDocumentPath = value; OnPropertyChanged(nameof(CurrentDocumentPath)); } } public event PropertyChangedEventHandler PropertyChanged; public MainWindowViewModel() { if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { return; } CurrentDocumentPath = "Untitled.md"; } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } ``` Save feature added for testing.
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Documents; using System.Windows.Input; using ProjectMarkdown.Annotations; namespace ProjectMarkdown.ViewModels { public class MainWindowViewModel : INotifyPropertyChanged { private string _currentDocumentPath; private string _currentText; private string _currentHtml; public string CurrentDocumentPath { get { return _currentDocumentPath; } set { if (value == _currentDocumentPath) return; _currentDocumentPath = value; OnPropertyChanged(nameof(CurrentDocumentPath)); } } public string CurrentText { get { return _currentText; } set { if (value == _currentText) return; _currentText = value; OnPropertyChanged(nameof(CurrentText)); } } public string CurrentHtml { get { return _currentHtml; } set { if (value == _currentHtml) return; _currentHtml = value; OnPropertyChanged(nameof(CurrentHtml)); } } public event PropertyChangedEventHandler PropertyChanged; public ICommand SaveDocumentCommand { get; set; } public MainWindowViewModel() { if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { return; } using (var sr = new StreamReader("Example.html")) { CurrentHtml = sr.ReadToEnd(); } LoadCommands(); CurrentDocumentPath = "Untitled.md"; } private void LoadCommands() { SaveDocumentCommand = new RelayCommand(SaveDocument, CanSaveDocument); } public void SaveDocument(object obj) { using (var sr = new StreamReader("Example.html")) { CurrentHtml = sr.ReadToEnd(); } } public bool CanSaveDocument(object obj) { return true; } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } ```
63df304a-f93a-45c8-8bdb-105f7c06613c
{ "language": "C#" }
```c# using System; using System.Globalization; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Core.PropertyEditors.ValueConverters { [DefaultPropertyValueConverter] public class DecimalValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) => Constants.PropertyEditors.Aliases.Decimal.Equals(propertyType.EditorAlias); public override Type GetPropertyValueType(PublishedPropertyType propertyType) => typeof (decimal); public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType) => PropertyCacheLevel.Element; public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview) { if (source == null) return 0M; // in XML a decimal is a string if (source is string sourceString) { return decimal.TryParse(sourceString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal d) ? d : 0M; } // in the database an a decimal is an a decimal // default value is zero return source is decimal ? source : 0M; } } } ``` Make sure the decimal field value converter can handle double values when converting
```c# using System; using System.Globalization; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Core.PropertyEditors.ValueConverters { [DefaultPropertyValueConverter] public class DecimalValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) => Constants.PropertyEditors.Aliases.Decimal.Equals(propertyType.EditorAlias); public override Type GetPropertyValueType(PublishedPropertyType propertyType) => typeof (decimal); public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType) => PropertyCacheLevel.Element; public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview) { if (source == null) { return 0M; } // is it already a decimal? if(source is decimal) { return source; } // is it a double? if(source is double sourceDouble) { return Convert.ToDecimal(sourceDouble); } // is it a string? if (source is string sourceString) { return decimal.TryParse(sourceString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal d) ? d : 0M; } // couldn't convert the source value - default to zero return 0M; } } } ```
6069f474-0617-491c-bf33-706c92d480c9
{ "language": "C#" }
```c# using System; using System.IO; namespace Hangman { public class Hangman { public static void Main(string[] args) { var game = new Game("HANG THE MAN"); while (true) { string titleText = File.ReadAllText("title.txt"); Cell[] title = { new Cell(titleText, Cell.CentreAlign) }; string shownWord = game.ShownWord(); Cell[] word = { new Cell(shownWord, Cell.CentreAlign) }; Cell[] stats = { new Cell("Incorrect letters:\n A B I U"), new Cell("Lives remaining:\n 11/15", Cell.RightAlign) }; Cell[] status = { new Cell("Press any letter to guess!", Cell.CentreAlign) }; Row[] rows = { new Row(title), new Row(word), new Row(stats), new Row(status) }; var table = new Table( Math.Min(81, Console.WindowWidth), 2, rows ); var tableOutput = table.Draw(); Console.WriteLine(tableOutput); char key = Console.ReadKey(true).KeyChar; bool wasCorrect = game.GuessLetter(key); Console.Clear(); } } } } ``` Make key entry case insensitive
```c# using System; using System.IO; namespace Hangman { public class Hangman { public static void Main(string[] args) { var game = new Game("HANG THE MAN"); while (true) { string titleText = File.ReadAllText("title.txt"); Cell[] title = { new Cell(titleText, Cell.CentreAlign) }; string shownWord = game.ShownWord(); Cell[] word = { new Cell(shownWord, Cell.CentreAlign) }; Cell[] stats = { new Cell("Incorrect letters:\n A B I U"), new Cell("Lives remaining:\n 11/15", Cell.RightAlign) }; Cell[] status = { new Cell("Press any letter to guess!", Cell.CentreAlign) }; Row[] rows = { new Row(title), new Row(word), new Row(stats), new Row(status) }; var table = new Table( Math.Min(81, Console.WindowWidth), 2, rows ); var tableOutput = table.Draw(); Console.WriteLine(tableOutput); char key = Console.ReadKey(true).KeyChar; bool wasCorrect = game.GuessLetter(Char.ToUpper(key)); Console.Clear(); } } } } ```
0d38e9aa-0102-402c-8f56-f16145acbed8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CatchAllRule { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } } ``` Add a catch all route
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CatchAllRule { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Everything", "{*url}", new { controller = "Everything", action = "Index" } ); } } } ```
4aafce99-a332-43ef-8e9a-347a94bca137
{ "language": "C#" }
```c# using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using System; namespace Glimpse { public static class GlimpseServiceCollectionExtensions { public static IServiceCollection AddMvc(this IServiceCollection services) { return services.Add(GlimpseServices.GetDefaultServices()); } public static IServiceCollection AddMvc(this IServiceCollection services, IConfiguration configuration) { return services.Add(GlimpseServices.GetDefaultServices(configuration)); } } }``` Rename service collection extensions to be correct
```c# using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using System; namespace Glimpse { public static class GlimpseServiceCollectionExtensions { public static IServiceCollection AddGlimpse(this IServiceCollection services) { return services.Add(GlimpseServices.GetDefaultServices()); } public static IServiceCollection AddGlimpse(this IServiceCollection services, IConfiguration configuration) { return services.Add(GlimpseServices.GetDefaultServices(configuration)); } } }```
710537f1-47ff-4841-aa62-16c790c7c07b
{ "language": "C#" }
```c# using HelixToolkit.Wpf.SharpDX.Model.Scene; using HelixToolkit.Wpf.SharpDX.Render; using SharpDX; using System.Collections.Generic; using System.Windows; using System.Windows.Markup; namespace HelixToolkit.Wpf.SharpDX { [ContentProperty("Content")] public class Element3DPresenter : Element3D { /// <summary> /// Gets or sets the content. /// </summary> /// <value> /// The content. /// </value> public Element3D Content { get { return (Element3D)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// <summary> /// The content property /// </summary> public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(Element3D), typeof(Element3DPresenter), new PropertyMetadata(null, (d,e)=> { var model = d as Element3DPresenter; if(e.OldValue != null) { model.RemoveLogicalChild(e.OldValue); (model.SceneNode as GroupNode).RemoveChildNode(e.OldValue as Element3D); } if(e.NewValue != null) { model.AddLogicalChild(e.NewValue); (model.SceneNode as GroupNode).AddChildNode(e.NewValue as Element3D); } })); protected override SceneNode OnCreateSceneNode() { return new GroupNode(); } } } ``` Fix element3d presenter binding issue.
```c# using HelixToolkit.Wpf.SharpDX.Model.Scene; using HelixToolkit.Wpf.SharpDX.Render; using SharpDX; using System.Collections.Generic; using System.Windows; using System.Windows.Markup; namespace HelixToolkit.Wpf.SharpDX { [ContentProperty("Content")] public class Element3DPresenter : Element3D { /// <summary> /// Gets or sets the content. /// </summary> /// <value> /// The content. /// </value> public Element3D Content { get { return (Element3D)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// <summary> /// The content property /// </summary> public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(Element3D), typeof(Element3DPresenter), new PropertyMetadata(null, (d,e)=> { var model = d as Element3DPresenter; if(e.OldValue != null) { model.RemoveLogicalChild(e.OldValue); (model.SceneNode as GroupNode).RemoveChildNode(e.OldValue as Element3D); } if(e.NewValue != null) { model.AddLogicalChild(e.NewValue); (model.SceneNode as GroupNode).AddChildNode(e.NewValue as Element3D); } })); public Element3DPresenter() { Loaded += Element3DPresenter_Loaded; } protected override SceneNode OnCreateSceneNode() { return new GroupNode(); } private void Element3DPresenter_Loaded(object sender, RoutedEventArgs e) { if (Content != null) { RemoveLogicalChild(Content); AddLogicalChild(Content); } } } } ```
18264b16-d769-4674-90ff-49112652d1f2
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using NSubstitute; using Octokit.Tests.Helpers; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class TeamsClientTests { public class TheConstructor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new TeamsClient(null)); } } public class TheGetAllMethod { [Fact] public void RequestsTheCorrectUrl() { var client = Substitute.For<IApiConnection>(); var orgs = new TeamsClient(client); orgs.GetAllTeams("username"); client.Received().GetAll<Team>(Arg.Is<Uri>(u => u.ToString() == "users/username/orgs")); } [Fact] public async Task EnsuresNonNullArguments() { var teams = new TeamsClient(Substitute.For<IApiConnection>()); AssertEx.Throws<ArgumentNullException>(async () => await teams.GetAllTeams(null)); } } } } ``` Fix up the test to return correct type
```c# using System; using System.Threading.Tasks; using NSubstitute; using Octokit.Tests.Helpers; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class TeamsClientTests { public class TheConstructor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new TeamsClient(null)); } } public class TheGetAllMethod { [Fact] public void RequestsTheCorrectUrl() { var client = Substitute.For<IApiConnection>(); var orgs = new TeamsClient(client); orgs.GetAllTeams("username"); client.Received().GetAll<TeamItem>(Arg.Is<Uri>(u => u.ToString() == "users/username/orgs")); } [Fact] public async Task EnsuresNonNullArguments() { var teams = new TeamsClient(Substitute.For<IApiConnection>()); AssertEx.Throws<ArgumentNullException>(async () => await teams.GetAllTeams(null)); } } } } ```
830fce28-76c2-41a1-94d2-e9a29e36069e
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyCompany("Dimension Data")] [assembly: AssemblyProduct("Compute as a Service (CaaS) API client.")] [assembly: AssemblyCopyright("Copyright © Dimension Data 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.3.0.2")] ``` Update solution version to 1.3.1
```c# using System.Reflection; [assembly: AssemblyCompany("Dimension Data")] [assembly: AssemblyProduct("Compute as a Service (CaaS) API client.")] [assembly: AssemblyCopyright("Copyright © Dimension Data 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.3.1.0")] ```
39fb410e-b4ca-4e3b-91ba-0e507d311186
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private uint? _age; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name? name, uint? age, Organization? organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _age = age; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } } ``` Replace age with date of birth
```c# using System; using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private DateTime _dateOfBirth; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name? name, DateTime dateOfBirth, Organization? organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _dateOfBirth = dateOfBirth; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } } ```
97bd5dc7-276a-4b67-8531-e14e4cb238d8
{ "language": "C#" }
```c# // 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 Core2D.Shapes.Interfaces; namespace Core2D.UnitTests { public class TestPointShape : TestBaseShape, IPointShape { public double X { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public double Y { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public PointAlignment Alignment { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public IBaseShape Shape { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } } ``` Use default getters and setters
```c# // 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 Core2D.Shapes.Interfaces; namespace Core2D.UnitTests { public class TestPointShape : TestBaseShape, IPointShape { public double X { get; set; } public double Y { get; set; } public PointAlignment Alignment { get; set; } public IBaseShape Shape { get; set; } } } ```
56ace251-88b3-4fda-9219-86c9eeda6d66
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Runtime.InteropServices; using Microsoft.NET.TestFramework; using Microsoft.NET.TestFramework.Assertions; using Microsoft.NET.TestFramework.Commands; using Xunit; using static Microsoft.NET.TestFramework.Commands.MSBuildTest; namespace Microsoft.NET.Build.Tests { public class GivenThatWeWantToBuildASolutionWithNonAnyCPUPlatform { private TestAssetsManager _testAssetsManager = TestAssetsManager.TestProjectsAssetsManager; [Fact] public void It_builds_solusuccessfully() { var testAsset = _testAssetsManager .CopyTestAsset("x64SolutionBuild") .WithSource() .Restore(); var buildCommand = new BuildCommand(Stage0MSBuild, testAsset.TestRoot, "x64SolutionBuild.sln"); buildCommand .Execute() .Should() .Pass(); buildCommand.GetOutputDirectory("netcoreapp1.0", @"x64\Debug") .Should() .OnlyHaveFiles(new[] { "x64SolutionBuild.runtimeconfig.dev.json", "x64SolutionBuild.runtimeconfig.json", "x64SolutionBuild.deps.json", "x64SolutionBuild.dll", "x64SolutionBuild.pdb" }); } } } ``` Fix path separator on Linux
```c# // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Runtime.InteropServices; using Microsoft.NET.TestFramework; using Microsoft.NET.TestFramework.Assertions; using Microsoft.NET.TestFramework.Commands; using Xunit; using static Microsoft.NET.TestFramework.Commands.MSBuildTest; namespace Microsoft.NET.Build.Tests { public class GivenThatWeWantToBuildASolutionWithNonAnyCPUPlatform { private TestAssetsManager _testAssetsManager = TestAssetsManager.TestProjectsAssetsManager; [Fact] public void It_builds_solusuccessfully() { var testAsset = _testAssetsManager .CopyTestAsset("x64SolutionBuild") .WithSource() .Restore(); var buildCommand = new BuildCommand(Stage0MSBuild, testAsset.TestRoot, "x64SolutionBuild.sln"); buildCommand .Execute() .Should() .Pass(); buildCommand.GetOutputDirectory("netcoreapp1.0", Path.Combine("x64", "Debug")) .Should() .OnlyHaveFiles(new[] { "x64SolutionBuild.runtimeconfig.dev.json", "x64SolutionBuild.runtimeconfig.json", "x64SolutionBuild.deps.json", "x64SolutionBuild.dll", "x64SolutionBuild.pdb" }); } } } ```
48dce5cf-5df6-4d7b-b806-4fbf6b712cc8
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Graphics; namespace osu.Game.Rulesets.Mods { public abstract class ModHardRock : Mod, IApplicableToDifficulty { public override string Name => "Hard Rock"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_hardrock; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Everything just got a bit harder..."; public override Type[] IncompatibleMods => new[] { typeof(ModEasy) }; public void ApplyToDifficulty(BeatmapDifficulty difficulty) { const float ratio = 1.4f; difficulty.CircleSize *= ratio; difficulty.ApproachRate *= ratio; difficulty.DrainRate *= ratio; difficulty.OverallDifficulty *= ratio; } } }``` Adjust CS multiplier to match stable
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Graphics; namespace osu.Game.Rulesets.Mods { public abstract class ModHardRock : Mod, IApplicableToDifficulty { public override string Name => "Hard Rock"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_hardrock; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Everything just got a bit harder..."; public override Type[] IncompatibleMods => new[] { typeof(ModEasy) }; public void ApplyToDifficulty(BeatmapDifficulty difficulty) { const float ratio = 1.4f; difficulty.CircleSize *= 1.3f; // CS uses a custom 1.3 ratio. difficulty.ApproachRate *= ratio; difficulty.DrainRate *= ratio; difficulty.OverallDifficulty *= ratio; } } } ```
b2e79221-80ee-479e-b4b0-4a712ccdd3b6
{ "language": "C#" }
```c# @using Tracker @using Tracker.Models @using Tracker.ViewModels.Account @using Tracker.ViewModels.Manage @using Microsoft.AspNet.Identity @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" ``` Update starting solution with correct namespaces.
```c# @using ShatteredTemple.LegoDimensions.Tracker @using ShatteredTemple.LegoDimensions.Tracker.Models @using ShatteredTemple.LegoDimensions.Tracker.ViewModels.Account @using ShatteredTemple.LegoDimensions.Tracker.ViewModels.Manage @using Microsoft.AspNet.Identity @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" ```
42b86908-b678-49e6-8a83-6525df5bf562
{ "language": "C#" }
```c# // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Batch Management Library")] [assembly: AssemblyDescription("Provides management functions for Microsoft Azure Batch services.")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] ``` Update assembly version per feedback
```c# // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Batch Management Library")] [assembly: AssemblyDescription("Provides management functions for Microsoft Azure Batch services.")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] ```
5995f07a-606c-44bb-8bf7-bc04cfd1d686
{ "language": "C#" }
```c# using StockportWebapp.Models; using StockportWebapp.Parsers; using StockportWebapp.Utils; namespace StockportWebapp.ContentFactory { public class EventFactory { private readonly ISimpleTagParserContainer _simpleTagParserContainer; private readonly MarkdownWrapper _markdownWrapper; private readonly IDynamicTagParser<Document> _documentTagParser; public EventFactory(ISimpleTagParserContainer simpleTagParserContainer, MarkdownWrapper markdownWrapper, IDynamicTagParser<Document> documentTagParser) { _simpleTagParserContainer = simpleTagParserContainer; _markdownWrapper = markdownWrapper; _documentTagParser = documentTagParser; } public virtual ProcessedEvents Build(Event eventItem) { var description = _simpleTagParserContainer.ParseAll(eventItem.Description, eventItem.Title); description = _documentTagParser.Parse(description, eventItem.Documents); description = _markdownWrapper.ConvertToHtml(description ?? ""); return new ProcessedEvents(eventItem.Title, eventItem.Slug, eventItem.Teaser, eventItem.ImageUrl, eventItem.ThumbnailImageUrl, description, eventItem.Fee, eventItem.Location, eventItem.SubmittedBy, eventItem.EventDate, eventItem.StartTime, eventItem.EndTime, eventItem.Breadcrumbs); } } } ``` Fix event factory parsing of documents
```c# using StockportWebapp.Models; using StockportWebapp.Parsers; using StockportWebapp.Utils; namespace StockportWebapp.ContentFactory { public class EventFactory { private readonly ISimpleTagParserContainer _simpleTagParserContainer; private readonly MarkdownWrapper _markdownWrapper; private readonly IDynamicTagParser<Document> _documentTagParser; public EventFactory(ISimpleTagParserContainer simpleTagParserContainer, MarkdownWrapper markdownWrapper, IDynamicTagParser<Document> documentTagParser) { _simpleTagParserContainer = simpleTagParserContainer; _markdownWrapper = markdownWrapper; _documentTagParser = documentTagParser; } public virtual ProcessedEvents Build(Event eventItem) { var description = _simpleTagParserContainer.ParseAll(eventItem.Description, eventItem.Title); description = _markdownWrapper.ConvertToHtml(description ?? ""); description = _documentTagParser.Parse(description, eventItem.Documents); return new ProcessedEvents(eventItem.Title, eventItem.Slug, eventItem.Teaser, eventItem.ImageUrl, eventItem.ThumbnailImageUrl, description, eventItem.Fee, eventItem.Location, eventItem.SubmittedBy, eventItem.EventDate, eventItem.StartTime, eventItem.EndTime, eventItem.Breadcrumbs); } } } ```
d68c8980-c607-44c4-bff1-84f918c15484
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Game.Users; namespace osu.Game.Online.API { public class DummyAPIAccess : IAPIProvider { public Bindable<User> LocalUser { get; } = new Bindable<User>(new User { Username = @"Dummy", Id = 1001, }); public bool IsLoggedIn => true; public string ProvidedUsername => LocalUser.Value.Username; public string Endpoint => "http://localhost"; public APIState State => LocalUser.Value.Id == 1 ? APIState.Offline : APIState.Online; public virtual void Queue(APIRequest request) { } public void Register(IOnlineComponent component) { // todo: add support } public void Unregister(IOnlineComponent component) { // todo: add support } public void Login(string username, string password) { LocalUser.Value = new User { Username = @"Dummy", Id = 1, }; } public void Logout() { LocalUser.Value = new GuestUser(); } public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password) => null; } } ``` Use non-guest user ID for non-guest user
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Game.Users; namespace osu.Game.Online.API { public class DummyAPIAccess : IAPIProvider { public Bindable<User> LocalUser { get; } = new Bindable<User>(new User { Username = @"Dummy", Id = 1001, }); public bool IsLoggedIn => true; public string ProvidedUsername => LocalUser.Value.Username; public string Endpoint => "http://localhost"; public APIState State => LocalUser.Value.Id == 1 ? APIState.Offline : APIState.Online; public virtual void Queue(APIRequest request) { } public void Register(IOnlineComponent component) { // todo: add support } public void Unregister(IOnlineComponent component) { // todo: add support } public void Login(string username, string password) { LocalUser.Value = new User { Username = @"Dummy", Id = 1001, }; } public void Logout() { LocalUser.Value = new GuestUser(); } public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password) => null; } } ```
994d8078-a37a-4153-a2c1-4bed69b7bfe1
{ "language": "C#" }
```c# using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using JetBrains.Annotations; namespace Diadoc.Api { public static class XmlSerializerExtensions { public static byte[] SerializeToXml<T>(this T @object) { var serializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { XmlSerializerNamespaces namespaces = null; var ns = FindXmlNamespace<T>(); if (!IsNullOrWhiteSpace(ns)) { namespaces = new XmlSerializerNamespaces(); namespaces.Add("", ns); } serializer.Serialize(sw, @object, namespaces ?? new XmlSerializerNamespaces(new[] {new XmlQualifiedName(string.Empty)})); } return ms.ToArray(); } } [CanBeNull] private static string FindXmlNamespace<T>() { var root = typeof(T).GetCustomAttributes(typeof(XmlRootAttribute), true).Cast<XmlRootAttribute>().FirstOrDefault(); return root != null && !IsNullOrWhiteSpace(root.Namespace) ? root.Namespace : null; } private static bool IsNullOrWhiteSpace(string value) => string.IsNullOrEmpty(value) || value.Trim().Length == 0; } }``` Add overload SerializeToXml with object type
```c# using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using JetBrains.Annotations; namespace Diadoc.Api { public static class XmlSerializerExtensions { public static byte[] SerializeToXml<T>(this T @object) { var serializer = new XmlSerializer(typeof(T)); return SerializeToXml(@object, serializer); } public static byte[] SerializeToXml(object @object) { var serializer = new XmlSerializer(@object.GetType()); return SerializeToXml(@object, serializer); } private static byte[] SerializeToXml<T>(T @object, XmlSerializer serializer) { using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { XmlSerializerNamespaces namespaces = null; var ns = FindXmlNamespace<T>(); if (!IsNullOrWhiteSpace(ns)) { namespaces = new XmlSerializerNamespaces(); namespaces.Add("", ns); } serializer.Serialize(sw, @object, namespaces ?? new XmlSerializerNamespaces(new[] {new XmlQualifiedName(string.Empty)})); } return ms.ToArray(); } } [CanBeNull] private static string FindXmlNamespace<T>() { var root = typeof(T).GetCustomAttributes(typeof(XmlRootAttribute), true).Cast<XmlRootAttribute>().FirstOrDefault(); return root != null && !IsNullOrWhiteSpace(root.Namespace) ? root.Namespace : null; } private static bool IsNullOrWhiteSpace(string value) => string.IsNullOrEmpty(value) || value.Trim().Length == 0; } }```
91ddcd7b-f807-4de3-921a-fb573df5216a
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyTitle("GraphQL")] [assembly: AssemblyProduct("GraphQL")] [assembly: AssemblyDescription("GraphQL for .NET")] [assembly: AssemblyCopyright("Copyright 2015-2016 Joseph T. McBride, et al. All rights reserved.")] [assembly: AssemblyVersion("0.8.2.0")] [assembly: AssemblyFileVersion("0.8.2.0")] ``` Add assembly attribute to get rid of warnings
```c# using System; using System.Reflection; [assembly: AssemblyTitle("GraphQL")] [assembly: AssemblyProduct("GraphQL")] [assembly: AssemblyDescription("GraphQL for .NET")] [assembly: AssemblyCopyright("Copyright 2015-2016 Joseph T. McBride, et al. All rights reserved.")] [assembly: AssemblyVersion("0.8.2.0")] [assembly: AssemblyFileVersion("0.8.2.0")] [assembly: CLSCompliant(false)] ```
12a822f1-2a1f-4c59-9773-84c40e2e005a
{ "language": "C#" }
```c# using System.Threading.Tasks; namespace Upload.Security { public class ApiKeyValidator : IApiKeyValidator { public Task<bool> ValidateAsync(string apiKey) { return Task.FromResult(true); } } } ``` Read api key from env setting
```c# using System; using System.Threading.Tasks; namespace Upload.Security { public class ApiKeyValidator : IApiKeyValidator { public Task<bool> ValidateAsync(string apiKey) { return Task.FromResult(apiKey == Environment.GetEnvironmentVariable("APPSETTING_ApiKey")); } } } ```
b4993008-9bf9-4746-85f6-ca3f5e3f7396
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using BetterNotes.NoteClasses; namespace BetterNotes.NoteUIObjects { public class NoteExpButton : NoteUIObjectBase { private NotesExperiment expObject; private bool highlight; private void Start() { highlight = NotesMainMenu.Settings.HighLightPart; } protected override void OnLeftClick() { //Run Experiment } protected override void OnRightClick() { //Part Right-Click menu } protected override void OnMouseIn() { if (highlight) expObject.RootPart.SetHighlight(true, false); } protected override void OnMouseOut() { if (highlight) expObject.RootPart.SetHighlight(false, false); } protected override void ToolTip() { throw new NotImplementedException(); } } } ``` Add deploy experiment function to left-click on button
```c# using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using BetterNotes.NoteClasses; namespace BetterNotes.NoteUIObjects { public class NoteExpButton : NoteUIObjectBase { private NotesExperiment expObject; private bool highlight; private void Start() { highlight = NotesMainMenu.Settings.HighLightPart; } protected override bool assignObject(object obj) { if (obj == null || obj.GetType() != typeof(NotesExperiment)) { return false; } expObject = (NotesExperiment)obj; return true; } protected override void OnLeftClick() { if (expObject.deployExperiment()) { //log success } else { //log fail } } protected override void OnRightClick() { //Part Right-Click menu } protected override void OnMouseIn() { if (highlight) expObject.RootPart.SetHighlight(true, false); } protected override void OnMouseOut() { if (highlight) expObject.RootPart.SetHighlight(false, false); } protected override void ToolTip() { throw new NotImplementedException(); } } } ```
80ca87b4-ca25-4342-bcf2-2ba8e5862930
{ "language": "C#" }
```c# using System.Collections.Generic; namespace Esprima { public class ErrorHandler : IErrorHandler { public IList<ParserException> Errors { get; } public bool Tolerant { get; set; } public string Source { get; set; } public ErrorHandler() { Errors = new List<ParserException>(); Tolerant = false; } public void RecordError(ParserException error) { Errors.Add(error); } public void Tolerate(ParserException error) { if (Tolerant) { RecordError(error); } else { throw error; } } public ParserException CreateError(int index, int line, int col, string description) { var msg = $"Line {line}': {description}"; var error = new ParserException(msg) { Index = index, Column = col, LineNumber = line, Description = description, Source = Source }; return error; } public void TolerateError(int index, int line, int col, string description) { var error = this.CreateError(index, line, col, description); if (Tolerant) { this.RecordError(error); } else { throw error; } } } } ``` Remove apostrophe in parse error description
```c# using System.Collections.Generic; namespace Esprima { public class ErrorHandler : IErrorHandler { public IList<ParserException> Errors { get; } public bool Tolerant { get; set; } public string Source { get; set; } public ErrorHandler() { Errors = new List<ParserException>(); Tolerant = false; } public void RecordError(ParserException error) { Errors.Add(error); } public void Tolerate(ParserException error) { if (Tolerant) { RecordError(error); } else { throw error; } } public ParserException CreateError(int index, int line, int col, string description) { var msg = $"Line {line}: {description}"; var error = new ParserException(msg) { Index = index, Column = col, LineNumber = line, Description = description, Source = Source }; return error; } public void TolerateError(int index, int line, int col, string description) { var error = this.CreateError(index, line, col, description); if (Tolerant) { this.RecordError(error); } else { throw error; } } } } ```
fe6a1021-129e-4572-952c-1e58cfdb7404
{ "language": "C#" }
```c# using System.IO; using System.Net; namespace ServiceStack.Text { public static class WebRequestExtensions { public static string GetJsonFromUrl(this string url) { return url.GetStringFromUrl("application/json"); } public static string GetStringFromUrl(this string url, string acceptContentType) { var webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Accept = acceptContentType; using (var webRes = webReq.GetResponse()) using (var stream = webRes.GetResponseStream()) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } }``` Add helper WebRequest extensions, useful when playing with REST-ful APIs
```c# using System; using System.IO; using System.Net; namespace ServiceStack.Text { public static class WebRequestExtensions { public static string GetJsonFromUrl(this string url) { return url.GetStringFromUrl("application/json"); } public static string GetStringFromUrl(this string url, string acceptContentType="*/*") { var webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Accept = acceptContentType; using (var webRes = webReq.GetResponse()) using (var stream = webRes.GetResponseStream()) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } public static bool Is404(this Exception ex) { return HasStatus(ex as WebException, HttpStatusCode.NotFound); } public static HttpStatusCode? GetResponseStatus(this string url) { try { var webReq = (HttpWebRequest)WebRequest.Create(url); using (var webRes = webReq.GetResponse()) { var httpRes = webRes as HttpWebResponse; return httpRes != null ? httpRes.StatusCode : (HttpStatusCode?)null; } } catch (Exception ex) { return ex.GetStatus(); } } public static HttpStatusCode? GetStatus(this Exception ex) { return GetStatus(ex as WebException); } public static HttpStatusCode? GetStatus(this WebException webEx) { if (webEx == null) return null; var httpRes = webEx.Response as HttpWebResponse; return httpRes != null ? httpRes.StatusCode : (HttpStatusCode?) null; } public static bool HasStatus(this WebException webEx, HttpStatusCode statusCode) { return GetStatus(webEx) == statusCode; } } }```
1823ac9d-169e-4448-b33a-02640116f8cf
{ "language": "C#" }
```c# using Microsoft.Data.Entity; using System; using System.IO; using Windows.Storage; namespace UnicornPacker.Models { public class OrdersContext : DbContext { public DbSet<Order> Orders { get; set; } public DbSet<OrderLine> OrderLines { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string localDirectory = string.Empty; try { localDirectory = ApplicationData.Current.LocalFolder.Path; } catch (InvalidOperationException) { } optionsBuilder.UseSqlite($"Data source={Path.Combine(localDirectory, "Orders001.db")}"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>() .Property(o => o.OrderId) .ValueGeneratedNever(); modelBuilder.Entity<OrderLine>() .Key(l => new { l.OrderId, l.ProductId }); } } } ``` Clean up code for SQLite connection
```c# using Microsoft.Data.Entity; using System; using System.IO; using Windows.Storage; namespace UnicornPacker.Models { public class OrdersContext : DbContext { public DbSet<Order> Orders { get; set; } public DbSet<OrderLine> OrderLines { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite($"Data source={GetLocalDatabaseFile()}"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>() .Property(o => o.OrderId) .ValueGeneratedNever(); modelBuilder.Entity<OrderLine>() .Key(l => new { l.OrderId, l.ProductId }); } private static string GetLocalDatabaseFile() { string localDirectory = string.Empty; try { localDirectory = ApplicationData.Current.LocalFolder.Path; } catch (InvalidOperationException) { } return Path.Combine(localDirectory, "Orders.db"); } } } ```
f0a1bd18-48b0-407d-811e-78924a6e0c13
{ "language": "C#" }
```c# using System; using System.IO; using System.Text; namespace ValveResourceFormat.ResourceTypes { public class Sound : Blocks.ResourceData { private BinaryReader Reader; private long DataOffset; private NTRO NTROBlock; public override void Read(BinaryReader reader, Resource resource) { Reader = reader; reader.BaseStream.Position = Offset; if (resource.Blocks.ContainsKey(BlockType.NTRO)) { NTROBlock = new NTRO(); NTROBlock.Offset = Offset; NTROBlock.Size = Size; NTROBlock.Read(reader, resource); } DataOffset = Offset + Size; } public byte[] GetSound() { Reader.BaseStream.Position = DataOffset; return Reader.ReadBytes((int)Reader.BaseStream.Length); } public override string ToString() { if (NTROBlock != null) { return NTROBlock.ToString(); } return "This is a sound."; } } } ``` Read sound until the end of file correctly
```c# using System; using System.IO; using System.Text; namespace ValveResourceFormat.ResourceTypes { public class Sound : Blocks.ResourceData { private BinaryReader Reader; private NTRO NTROBlock; public override void Read(BinaryReader reader, Resource resource) { Reader = reader; reader.BaseStream.Position = Offset; if (resource.Blocks.ContainsKey(BlockType.NTRO)) { NTROBlock = new NTRO(); NTROBlock.Offset = Offset; NTROBlock.Size = Size; NTROBlock.Read(reader, resource); } } public byte[] GetSound() { Reader.BaseStream.Position = Offset + Size; return Reader.ReadBytes((int)(Reader.BaseStream.Length - Reader.BaseStream.Position)); } public override string ToString() { if (NTROBlock != null) { return NTROBlock.ToString(); } return "This is a sound."; } } } ```
d553842c-fdce-4c2d-b96e-527f5dd50a99
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace IronFoundry.Container { public class ContainerHostDependencyHelper { const string ContainerHostAssemblyName = "IronFoundry.Container.Host"; readonly Assembly containerHostAssembly; public ContainerHostDependencyHelper() { this.containerHostAssembly = GetContainerHostAssembly(); } public virtual string ContainerHostExe { get { return ContainerHostAssemblyName + ".exe"; } } public virtual string ContainerHostExePath { get { return containerHostAssembly.Location; } } public string ContainerHostExeConfig { get { return ContainerHostExe + ".config"; } } public string ContainerHostExeConfigPath { get { return ContainerHostExePath + ".config"; } } static Assembly GetContainerHostAssembly() { return Assembly.ReflectionOnlyLoad(ContainerHostAssemblyName); } public virtual IReadOnlyList<string> GetContainerHostDependencies() { return EnumerateLocalReferences(containerHostAssembly).ToList(); } IEnumerable<string> EnumerateLocalReferences(Assembly assembly) { foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies()) { var referencedAssembly = Assembly.ReflectionOnlyLoad(referencedAssemblyName.FullName); if (!referencedAssembly.GlobalAssemblyCache) { yield return referencedAssembly.Location; if (!referencedAssembly.Location.Contains("ICSharpCode.SharpZipLib.dll")) foreach (var nestedReferenceFilePath in EnumerateLocalReferences(referencedAssembly)) yield return nestedReferenceFilePath; } } } } } ``` Remove unnecessary check for SharpZipLib dll.
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace IronFoundry.Container { public class ContainerHostDependencyHelper { const string ContainerHostAssemblyName = "IronFoundry.Container.Host"; readonly Assembly containerHostAssembly; public ContainerHostDependencyHelper() { this.containerHostAssembly = GetContainerHostAssembly(); } public virtual string ContainerHostExe { get { return ContainerHostAssemblyName + ".exe"; } } public virtual string ContainerHostExePath { get { return containerHostAssembly.Location; } } public string ContainerHostExeConfig { get { return ContainerHostExe + ".config"; } } public string ContainerHostExeConfigPath { get { return ContainerHostExePath + ".config"; } } static Assembly GetContainerHostAssembly() { return Assembly.ReflectionOnlyLoad(ContainerHostAssemblyName); } public virtual IReadOnlyList<string> GetContainerHostDependencies() { return EnumerateLocalReferences(containerHostAssembly).ToList(); } IEnumerable<string> EnumerateLocalReferences(Assembly assembly) { foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies()) { var referencedAssembly = Assembly.ReflectionOnlyLoad(referencedAssemblyName.FullName); if (!referencedAssembly.GlobalAssemblyCache) { yield return referencedAssembly.Location; foreach (var nestedReferenceFilePath in EnumerateLocalReferences(referencedAssembly)) yield return nestedReferenceFilePath; } } } } } ```
650f5b88-63e3-40a5-8847-ef2afcecc853
{ "language": "C#" }
```c# #region using System.Diagnostics; using System.IO; using DesktopWidgets.Classes; #endregion namespace DesktopWidgets.Helpers { internal static class ProcessHelper { public static void Launch(string path, string args = "", string startIn = "", ProcessWindowStyle style = ProcessWindowStyle.Normal) { Launch(new ProcessFile {Path = path, Arguments = args, StartInFolder = startIn, WindowStyle = style}); } public static void Launch(ProcessFile file) { if (string.IsNullOrWhiteSpace(file.Path) || !File.Exists(file.Path)) return; Process.Start(new ProcessStartInfo { FileName = file.Path, Arguments = file.Arguments, WorkingDirectory = file.StartInFolder, WindowStyle = file.WindowStyle }); } public static void OpenFolder(string path) { if (File.Exists(path) || Directory.Exists(path)) Launch("explorer.exe", "/select," + path); } } }``` Revert "Fix error when launching missing files"
```c# #region using System.Diagnostics; using System.IO; using DesktopWidgets.Classes; #endregion namespace DesktopWidgets.Helpers { internal static class ProcessHelper { public static void Launch(string path, string args = "", string startIn = "", ProcessWindowStyle style = ProcessWindowStyle.Normal) { Launch(new ProcessFile {Path = path, Arguments = args, StartInFolder = startIn, WindowStyle = style}); } public static void Launch(ProcessFile file) { Process.Start(new ProcessStartInfo { FileName = file.Path, Arguments = file.Arguments, WorkingDirectory = file.StartInFolder, WindowStyle = file.WindowStyle }); } public static void OpenFolder(string path) { if (File.Exists(path) || Directory.Exists(path)) Launch("explorer.exe", "/select," + path); } } }```
ce49d8a4-2364-466d-97e4-44c5265633b6
{ "language": "C#" }
```c# using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Dbus { public partial class Connection { private static async Task authenticate(Stream stream) { using (var writer = new StreamWriter(stream, Encoding.ASCII, 32, true)) using (var reader = new StreamReader(stream, Encoding.ASCII, false, 32, true)) { writer.NewLine = "\r\n"; await writer.WriteAsync("\0AUTH EXTERNAL ").ConfigureAwait(false); var uid = getuid(); var stringUid = $"{uid}"; var uidBytes = Encoding.ASCII.GetBytes(stringUid); foreach (var b in uidBytes) await writer.WriteAsync($"{b:X}").ConfigureAwait(false); await writer.WriteLineAsync().ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); var response = await reader.ReadLineAsync().ConfigureAwait(false); if (!response.StartsWith("OK ")) throw new InvalidOperationException("Authentication failed: " + response); await writer.WriteLineAsync("BEGIN").ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); } } [DllImport("c")] private static extern int getuid(); } } ``` Add a `lib` prefix to the DllImport so it works with mono
```c# using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Dbus { public partial class Connection { private static async Task authenticate(Stream stream) { using (var writer = new StreamWriter(stream, Encoding.ASCII, 32, true)) using (var reader = new StreamReader(stream, Encoding.ASCII, false, 32, true)) { writer.NewLine = "\r\n"; await writer.WriteAsync("\0AUTH EXTERNAL ").ConfigureAwait(false); var uid = getuid(); var stringUid = $"{uid}"; var uidBytes = Encoding.ASCII.GetBytes(stringUid); foreach (var b in uidBytes) await writer.WriteAsync($"{b:X}").ConfigureAwait(false); await writer.WriteLineAsync().ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); var response = await reader.ReadLineAsync().ConfigureAwait(false); if (!response.StartsWith("OK ")) throw new InvalidOperationException("Authentication failed: " + response); await writer.WriteLineAsync("BEGIN").ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); } } [DllImport("libc")] private static extern int getuid(); } } ```
7fd27a02-5c8a-46fe-a2a7-6743c7270c27
{ "language": "C#" }
```c# // Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTestObjects { public static void Main () { Bus bus = Bus.Session; ObjectPath myPath = new ObjectPath ("/org/ndesk/test"); string myName = "org.ndesk.test"; //TODO: write the rest of this demo and implement } } public class Device : IDevice { public string GetName () { return "Some device"; } } public class DeviceManager : IDeviceManager { public IDevice GetCurrentDevice () { return new Device (); } } public interface IDevice { string GetName (); } public interface IDeviceManager { IDevice GetCurrentDevice (); } public interface IUglyDeviceManager { ObjectPath GetCurrentDevice (); } ``` Use properties in example code
```c# // Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTestObjects { public static void Main () { Bus bus = Bus.Session; ObjectPath myPath = new ObjectPath ("/org/ndesk/test"); string myName = "org.ndesk.test"; //TODO: write the rest of this demo and implement } } public class Device : IDevice { public string Name { get { return "Some device"; } } } public class DeviceManager : IDeviceManager { public IDevice CurrentDevice { get { return new Device (); } } } public interface IDevice { string Name { get; } } public interface IDeviceManager { IDevice CurrentDevice { get; } } public interface IUglyDeviceManager { ObjectPath CurrentDevice { get; } } ```
79f9d836-1e09-496f-8417-f91acaba2516
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Sandra")] [assembly: AssemblyDescription("Hosted on https://github.com/PenguinF/sandra-three")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sandra")] [assembly: AssemblyCopyright("Copyright © 2002-2016 - Henk Nicolai")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Correct year when development started.
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Sandra")] [assembly: AssemblyDescription("Hosted on https://github.com/PenguinF/sandra-three")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sandra")] [assembly: AssemblyCopyright("Copyright © 2004-2016 - Henk Nicolai")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ```
06d86ca4-b7ad-474f-91a8-80d50ef19bbd
{ "language": "C#" }
```c# using System; namespace Mpdn.CustomLinearScaler { namespace Example { public class Gaussian : ICustomLinearScaler { public Guid Guid { get { return new Guid("647351FF-7FEC-4EAB-86C7-CE1BEF43EFD4"); } } public string Name { get { return "Gaussian"; } } public bool AllowDeRing { get { return false; } } public ScalerTaps MaxTapCount { get { return ScalerTaps.Eight; } } public float GetWeight(float n, int width) { return (float) GaussianKernel(n, width); } private static double GaussianKernel(double x, double radius) { var sigma = radius/6; return Math.Exp(-(x*x/(2*sigma*sigma))); } } } } ``` Fix radius calculation and lower sigma.
```c# using System; namespace Mpdn.CustomLinearScaler { namespace Example { public class Gaussian : ICustomLinearScaler { public Guid Guid { get { return new Guid("647351FF-7FEC-4EAB-86C7-CE1BEF43EFD4"); } } public string Name { get { return "Gaussian"; } } public bool AllowDeRing { get { return false; } } public ScalerTaps MaxTapCount { get { return ScalerTaps.Eight; } } public float GetWeight(float n, int width) { return (float) GaussianKernel(n, width / 2); } private static double GaussianKernel(double x, double radius) { var sigma = radius / 4; return Math.Exp(-(x*x/(2*sigma*sigma))); } } } } ```
10a77916-d6f9-41a0-a1d0-1106967f7001
{ "language": "C#" }
```c# using UnityEngine; using UnityEngine.UI; using System.Collections; namespace UDBase.Components.Log { public class Log_Visual_Behaviour : MonoBehaviour { public Text Text; public void Init() { Text.text = ""; } public void AddMessage(string msg) { Text.text += msg + "\n"; } } } ``` Store messages in list to future filter; Clear method;
```c# using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; namespace UDBase.Components.Log { public class Log_Visual_Behaviour : MonoBehaviour { public Text Text; List<string> _messages = new List<string>(); public void Init() { Clear(); } public void Clear() { Text.text = ""; } public void AddMessage(string msg) { _messages.Add(msg); ApplyMessage(msg); } void ApplyMessage(string msg) { Text.text += msg + "\n"; } } } ```
f71044ae-8ca5-4edd-8c0f-3e2354c2a14b
{ "language": "C#" }
```c# using System; using System.Linq; using System.Reflection; using NUnit.Framework; [SetUpFixture] public class SplatModeDetectorSetUp { static SplatModeDetectorSetUp() { // HACK: Force .NET 4.5 version of Splat to load when executing inside NCrunch var ncrunchAsms = Environment.GetEnvironmentVariable("NCrunch.AllAssemblyLocations")?.Split(';'); if (ncrunchAsms != null) { ncrunchAsms.Where(x => x.EndsWith(@"\Net45\Splat.dll")).Select(Assembly.LoadFrom).FirstOrDefault(); } } [OneTimeSetUp] public void RunBeforeAnyTests() { Splat.ModeDetector.Current.SetInUnitTestRunner(true); } }``` Remove hack to load correct version of Splat.
```c# using System; using System.Linq; using System.Reflection; using NUnit.Framework; [SetUpFixture] public class SplatModeDetectorSetUp { [OneTimeSetUp] public void RunBeforeAnyTests() { Splat.ModeDetector.Current.SetInUnitTestRunner(true); } }```
e87a1b8e-5223-405c-90b8-4daaaaafd25d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.NodeServices; using Microsoft.AspNetCore.SpaServices.Prerendering; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for setting up prerendering features in an <see cref="IServiceCollection" />. /// </summary> public static class PrerenderingServiceCollectionExtensions { /// <summary> /// Configures the dependency injection system to supply an implementation /// of <see cref="ISpaPrerenderer"/>. /// </summary> /// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param> public static void AddSpaPrerenderer(this IServiceCollection serviceCollection) { serviceCollection.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); serviceCollection.AddSingleton<ISpaPrerenderer, DefaultSpaPrerenderer>(); } } } ``` Clean up how IHttpContextAccessor is added
```c# using Microsoft.AspNetCore.SpaServices.Prerendering; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for setting up prerendering features in an <see cref="IServiceCollection" />. /// </summary> public static class PrerenderingServiceCollectionExtensions { /// <summary> /// Configures the dependency injection system to supply an implementation /// of <see cref="ISpaPrerenderer"/>. /// </summary> /// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param> public static void AddSpaPrerenderer(this IServiceCollection serviceCollection) { serviceCollection.AddHttpContextAccessor(); serviceCollection.AddSingleton<ISpaPrerenderer, DefaultSpaPrerenderer>(); } } } ```
e6c16294-2443-4919-b22b-d889aee148eb
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WpfAboutView")] [assembly: AssemblyDescription("Simple About control with app name, icon, version, and credits")] [assembly: AssemblyCompany("Daniel Chalmers")] [assembly: AssemblyProduct("WpfAboutView")] [assembly: AssemblyCopyright("© Daniel Chalmers 2017")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.0")]``` Update copyright year to 2018
```c# using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WpfAboutView")] [assembly: AssemblyDescription("Simple About control with app name, icon, version, and credits")] [assembly: AssemblyCompany("Daniel Chalmers")] [assembly: AssemblyProduct("WpfAboutView")] [assembly: AssemblyCopyright("© Daniel Chalmers 2018")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.0")]```
ae94aeef-f456-44b6-8bc5-a1452a983abe
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using BenchmarkDotNet.Attributes; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osuTK.Graphics; namespace osu.Framework.Benchmarks { public class BenchmarkManySpinningBoxes : GameBenchmark { [Test] [Benchmark] public void RunFrame() => RunSingleFrame(); protected override Game CreateGame() => new TestGame(); private class TestGame : Game { protected override void LoadComplete() { base.LoadComplete(); for (int i = 0; i < 1000; i++) { var box = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black }; Add(box); box.Spin(200, RotationDirection.Clockwise); } } } } } ``` Add autosize coverage to spinning boxes benchmark
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using BenchmarkDotNet.Attributes; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osuTK; using osuTK.Graphics; namespace osu.Framework.Benchmarks { public class BenchmarkManySpinningBoxes : GameBenchmark { private TestGame game; [Test] [Benchmark] public void RunFrame() { game.MainContent.AutoSizeAxes = Axes.None; game.MainContent.RelativeSizeAxes = Axes.Both; RunSingleFrame(); } [Test] [Benchmark] public void RunFrameWithAutoSize() { game.MainContent.RelativeSizeAxes = Axes.None; game.MainContent.AutoSizeAxes = Axes.Both; RunSingleFrame(); } [Test] [Benchmark] public void RunFrameWithAutoSizeDuration() { game.MainContent.RelativeSizeAxes = Axes.None; game.MainContent.AutoSizeAxes = Axes.Both; game.MainContent.AutoSizeDuration = 100; RunSingleFrame(); } protected override Game CreateGame() => game = new TestGame(); private class TestGame : Game { public Container MainContent; protected override void LoadComplete() { base.LoadComplete(); Add(MainContent = new Container()); for (int i = 0; i < 1000; i++) { var box = new Box { Size = new Vector2(100), Colour = Color4.Black }; MainContent.Add(box); box.Spin(200, RotationDirection.Clockwise); } } } } } ```
da7b4c97-a70d-4f34-bb8b-63b0c84b86b4
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Tournament.Screens.Showcase { public class TournamentLogo : CompositeDrawable { public TournamentLogo() { RelativeSizeAxes = Axes.X; Margin = new MarginPadding { Vertical = 5 }; Height = 100; } [BackgroundDependencyLoader] private void load(TextureStore textures) { InternalChild = new Sprite { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, FillMode = FillMode.Fit, RelativeSizeAxes = Axes.Both, Texture = textures.Get("game-screen-logo"), }; } } } ``` Use new logo name for showcase screen
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Tournament.Screens.Showcase { public class TournamentLogo : CompositeDrawable { public TournamentLogo() { RelativeSizeAxes = Axes.X; Margin = new MarginPadding { Vertical = 5 }; Height = 100; } [BackgroundDependencyLoader] private void load(TextureStore textures) { InternalChild = new Sprite { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, FillMode = FillMode.Fit, RelativeSizeAxes = Axes.Both, Texture = textures.Get("header-logo"), }; } } } ```
a5f05121-c58c-4509-bd21-2b7699e52585
{ "language": "C#" }
```c# using EntityCore.DynamicEntity; using EntityCore.Utils; using System.Configuration; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace EntityCore { public static class Context { public static DynamicEntityContext New(string nameOrConnectionString) { Check.NotEmpty(nameOrConnectionString, "nameOrConnectionString"); var connnection = DbHelpers.GetDbConnection(nameOrConnectionString); DbCompiledModel model = GetCompiledModel(connnection); return new DynamicEntityContext(nameOrConnectionString, model); } public static DynamicEntityContext New(DbConnection existingConnection) { Check.NotNull(existingConnection, "existingConnection"); DbCompiledModel model = GetCompiledModel(existingConnection); return new DynamicEntityContext(existingConnection, model, false); } private static DbCompiledModel GetCompiledModel(DbConnection connection) { var builder = new DbModelBuilder(DbModelBuilderVersion.Latest); foreach (var entity in EntityTypeCache.GetEntitiesTypes(connection)) builder.RegisterEntityType(entity); var model = builder.Build(connection); return model.Compile(); } } } ``` Remove unsupported column attribute convention with no sql connection.
```c# using EntityCore.DynamicEntity; using EntityCore.Utils; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.ModelConfiguration.Conventions; using System.Data.SqlClient; using System.Linq; namespace EntityCore { public static class Context { public static DynamicEntityContext New(string nameOrConnectionString) { Check.NotEmpty(nameOrConnectionString, "nameOrConnectionString"); var connection = DbHelpers.GetDbConnection(nameOrConnectionString); DbCompiledModel model = GetCompiledModel(connection); return new DynamicEntityContext(nameOrConnectionString, model); } public static DynamicEntityContext New(DbConnection existingConnection) { Check.NotNull(existingConnection, "existingConnection"); DbCompiledModel model = GetCompiledModel(existingConnection); return new DynamicEntityContext(existingConnection, model, false); } private static DbCompiledModel GetCompiledModel(DbConnection connection) { var builder = new DbModelBuilder(DbModelBuilderVersion.Latest); foreach (var entity in EntityTypeCache.GetEntitiesTypes(connection)) builder.RegisterEntityType(entity); if (!(connection is SqlConnection)) // Compatible Effort. See https://effort.codeplex.com/workitem/678 builder.Conventions.Remove<ColumnAttributeConvention>(); var model = builder.Build(connection); return model.Compile(); } } } ```
dcc771de-3673-4e74-aadc-c1f880fa31fd
{ "language": "C#" }
```c# using System.IO; using OpenZH.Data.Utilities.Extensions; namespace OpenZH.Data.Map { public sealed class PolygonTrigger { public string Name { get; private set; } public string LayerName { get; private set; } public uint UniqueId { get; private set; } public PolygonTriggerType TriggerType { get; private set; } public MapVector3i[] Points { get; private set; } public static PolygonTrigger Parse(BinaryReader reader) { var name = reader.ReadUInt16PrefixedAsciiString(); var layerName = reader.ReadUInt16PrefixedAsciiString(); var uniqueId = reader.ReadUInt32(); var triggerType = reader.ReadUInt32AsEnum<PolygonTriggerType>(); var unknown = reader.ReadUInt16(); if (unknown != 0) { throw new InvalidDataException(); } var numPoints = reader.ReadUInt32(); var points = new MapVector3i[numPoints]; for (var i = 0; i < numPoints; i++) { points[i] = MapVector3i.Parse(reader); } return new PolygonTrigger { Name = name, LayerName = layerName, UniqueId = uniqueId, TriggerType = triggerType, Points = points }; } } public enum PolygonTriggerType : uint { Area = 0, Water = 1 } } ``` Support more polygon trigger types
```c# using System; using System.IO; using OpenZH.Data.Utilities.Extensions; namespace OpenZH.Data.Map { public sealed class PolygonTrigger { public string Name { get; private set; } public string LayerName { get; private set; } public uint UniqueId { get; private set; } public PolygonTriggerType TriggerType { get; private set; } public MapVector3i[] Points { get; private set; } public static PolygonTrigger Parse(BinaryReader reader) { var name = reader.ReadUInt16PrefixedAsciiString(); var layerName = reader.ReadUInt16PrefixedAsciiString(); var uniqueId = reader.ReadUInt32(); var triggerType = reader.ReadUInt32AsEnum<PolygonTriggerType>(); var unknown = reader.ReadUInt16(); if (unknown != 0) { throw new InvalidDataException(); } var numPoints = reader.ReadUInt32(); var points = new MapVector3i[numPoints]; for (var i = 0; i < numPoints; i++) { points[i] = MapVector3i.Parse(reader); } return new PolygonTrigger { Name = name, LayerName = layerName, UniqueId = uniqueId, TriggerType = triggerType, Points = points }; } } [Flags] public enum PolygonTriggerType : uint { Area = 0, Water = 1, River = 256, Unknown = 65536, WaterAndRiver = Water | River, WaterAndUnknown = Water | Unknown, } } ```
305cc279-7dab-4f01-9f5f-9eb4895e1ac0
{ "language": "C#" }
```c# using NUnit.Framework; using Mos6510.Instructions; namespace Mos6510.Tests.Instructions { [TestFixture] public class InyTests { [Test] public void IncrementsTheValueInRegisterY() { const int initialValue = 42; var model = new ProgrammingModel(); model.GetRegister(RegisterName.Y).SetValue(initialValue); var instruction = new Iny(); instruction.Execute(model); Assert.That(model.GetRegister(RegisterName.Y).GetValue(), Is.EqualTo(initialValue + 1)); } } } ``` Add tests for the status flags set by iny.
```c# using NUnit.Framework; using Mos6510.Instructions; namespace Mos6510.Tests.Instructions { [TestFixture] public class InyTests { [Test] public void IncrementsTheValueInRegisterY() { const int initialValue = 42; var model = new ProgrammingModel(); model.GetRegister(RegisterName.Y).SetValue(initialValue); var instruction = new Iny(); instruction.Execute(model); Assert.That(model.GetRegister(RegisterName.Y).GetValue(), Is.EqualTo(initialValue + 1)); } [TestCase(0x7F, true)] [TestCase(0x7E, false)] public void VerifyValuesOfNegativeFlag(int initialValue, bool expectedResult) { var model = new ProgrammingModel(); model.GetRegister(RegisterName.Y).SetValue(initialValue); model.NegativeFlag = !expectedResult; var instruction = new Iny(); instruction.Execute(model); Assert.That(model.NegativeFlag, Is.EqualTo(expectedResult)); } [TestCase(0xFF, true)] [TestCase(0x00, false)] public void VerifyValuesOfZeroFlag(int initialValue, bool expectedResult) { var model = new ProgrammingModel(); model.GetRegister(RegisterName.Y).SetValue(initialValue); model.ZeroFlag = !expectedResult; var instruction = new Iny(); instruction.Execute(model); Assert.That(model.ZeroFlag, Is.EqualTo(expectedResult)); } } } ```
7739f191-be97-4bca-81fc-fd38cc7bb482
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Security.Permissions; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("MongoDBDriver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: CLSCompliantAttribute(true)] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] ``` Allow MongoDB.Driver.Tests to see internals of MongoDB.Driver.
```c# using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Permissions; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("MongoDBDriver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: CLSCompliantAttribute(true)] [assembly: InternalsVisibleTo("MongoDB.Driver.Tests")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] ```
ea3f2f17-b8a5-4e7a-b069-ac94c7623b1d
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a single item that points to a range from a result. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentreferences /// for an example of item edges. /// </summary> internal sealed class Item : Edge { public Id<LsifDocument> Document { get; } public string? Property { get; } public Item(Id<Vertex> outVertex, Id<Range> range, Id<LsifDocument> document, IdFactory idFactory, string? property = null) : base(label: "item", outVertex, new[] { range.As<Range, Vertex>() }, idFactory) { Document = document; Property = property; } } } ``` Rename document to shard in item edges
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a single item that points to a range from a result. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentreferences /// for an example of item edges. /// </summary> internal sealed class Item : Edge { public Id<LsifDocument> Shard { get; } public string? Property { get; } public Item(Id<Vertex> outVertex, Id<Range> range, Id<LsifDocument> document, IdFactory idFactory, string? property = null) : base(label: "item", outVertex, new[] { range.As<Range, Vertex>() }, idFactory) { Shard = document; Property = property; } } } ```
f1f69d6d-bd1e-4941-aaa8-0fe5a5e40f5e
{ "language": "C#" }
```c# // ReSharper disable InconsistentNaming #pragma warning disable namespace Gu.Wpf.UiAutomation.WindowsAPI { using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; [DebuggerDisplay("({X}, {Y})")] [StructLayout(LayoutKind.Sequential)] public struct POINT : IEquatable<POINT> { public int X; public int Y; public POINT(int x, int y) { this.X = x; this.Y = y; } public static bool operator ==(POINT left, POINT right) { return left.Equals(right); } public static bool operator !=(POINT left, POINT right) { return !left.Equals(right); } public static POINT Create(Point p) { return new POINT { X = (int)p.X, Y = (int)p.Y, }; } /// <inheritdoc /> public bool Equals(POINT other) { return this.X == other.X && this.Y == other.Y; } /// <inheritdoc /> public override bool Equals(object obj) => obj is POINT other && this.Equals(other); /// <inheritdoc /> public override int GetHashCode() { unchecked { return (this.X * 397) ^ this.Y; } } } } ``` Make point factory method internal.
```c# // ReSharper disable InconsistentNaming #pragma warning disable namespace Gu.Wpf.UiAutomation.WindowsAPI { using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; [DebuggerDisplay("({X}, {Y})")] [StructLayout(LayoutKind.Sequential)] public struct POINT : IEquatable<POINT> { public int X; public int Y; public POINT(int x, int y) { this.X = x; this.Y = y; } public static bool operator ==(POINT left, POINT right) { return left.Equals(right); } public static bool operator !=(POINT left, POINT right) { return !left.Equals(right); } /// <inheritdoc /> public bool Equals(POINT other) { return this.X == other.X && this.Y == other.Y; } /// <inheritdoc /> public override bool Equals(object obj) => obj is POINT other && this.Equals(other); /// <inheritdoc /> public override int GetHashCode() { unchecked { return (this.X * 397) ^ this.Y; } } internal static POINT Create(Point p) { return new POINT { X = (int)p.X, Y = (int)p.Y, }; } } } ```
9d1c875c-0241-46fb-83b9-59fab778aba0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using IPTables.Net.Exceptions; namespace IPTables.Net.Iptables { /// <summary> /// Data to define the default IPTables tables and chains /// </summary> internal class IPTablesTables { static internal Dictionary<String, List<String>> Tables = new Dictionary<string, List<string>> { { "filter", new List<string>{"INPUT", "FORWARD", "OUTPUT"} }, { "nat", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} }, { "raw", new List<string>{"PREROUTING", "POSTROUTING"} }, { "mangle", new List<string>{"INPUT", "FORWARD", "OUTPUT", "PREROUTING", "POSTROUTING"} }, }; internal static List<String> GetInternalChains(String table) { if (!Tables.ContainsKey(table)) { throw new IpTablesNetException(String.Format("Unknown Table: {0}", table)); } return Tables[table]; } internal static bool IsInternalChain(String table, String chain) { return GetInternalChains(table).Contains(chain); } } } ``` Add OUTPUT chain to raw, remove POSTROUTING
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using IPTables.Net.Exceptions; namespace IPTables.Net.Iptables { /// <summary> /// Data to define the default IPTables tables and chains /// </summary> internal class IPTablesTables { static internal Dictionary<String, List<String>> Tables = new Dictionary<string, List<string>> { { "filter", new List<string>{"INPUT", "FORWARD", "OUTPUT"} }, { "nat", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} }, { "raw", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} }, { "mangle", new List<string>{"INPUT", "FORWARD", "OUTPUT", "PREROUTING", "POSTROUTING"} }, }; internal static List<String> GetInternalChains(String table) { if (!Tables.ContainsKey(table)) { throw new IpTablesNetException(String.Format("Unknown Table: {0}", table)); } return Tables[table]; } internal static bool IsInternalChain(String table, String chain) { return GetInternalChains(table).Contains(chain); } } } ```
e8dbcf67-a4e8-4a54-94f8-be0cf992fa18
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Mods { /// <summary> /// The usage of this mod to determine whether it's playable in such context. /// </summary> public enum ModUsage { /// <summary> /// Used for a per-user gameplay session. /// Determines whether the mod is playable by an end user. /// </summary> User, /// <summary> /// Used in multiplayer but must be applied to all users. /// This is generally the case for mods which affect the length of gameplay. /// </summary> MultiplayerRoomWide, /// <summary> /// Used in multiplayer either at a room or per-player level (i.e. "free mod"). /// </summary> MultiplayerPerPlayer, } } ``` Remove redundant line from mod usage
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Mods { /// <summary> /// The usage of this mod to determine whether it's playable in such context. /// </summary> public enum ModUsage { /// <summary> /// Used for a per-user gameplay session. /// </summary> User, /// <summary> /// Used in multiplayer but must be applied to all users. /// This is generally the case for mods which affect the length of gameplay. /// </summary> MultiplayerRoomWide, /// <summary> /// Used in multiplayer either at a room or per-player level (i.e. "free mod"). /// </summary> MultiplayerPerPlayer, } } ```
275721fe-b9db-4c1f-8b08-7475daae8489
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; namespace MatterHackers.MatterControl.Testing { public class TestingDispatch { string errorLogFileName = null; public TestingDispatch() { errorLogFileName = string.Format("ErrorLog - {0:yyyy-MM-dd hh-mmtt}.txt", DateTime.Now); string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now); using (StreamWriter file = new StreamWriter(errorLogFileName)) { file.WriteLine(errorLogFileName, firstLine); } } public void RunTests(string[] testCommands) { try { ReleaseTests.AssertDebugNotDefined(); } catch (Exception e) { DumpException(e); } try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); } catch (Exception e) { DumpException(e); } } void DumpException(Exception e) { using (StreamWriter w = File.AppendText(errorLogFileName)) { w.WriteLine(e.Message); w.Write(e.StackTrace); w.WriteLine(); } } } } ``` Save as consistent filename to make other scripting easier.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; namespace MatterHackers.MatterControl.Testing { public class TestingDispatch { string errorLogFileName = null; public TestingDispatch() { errorLogFileName = "ErrorLog.txt"; string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now); using (StreamWriter file = new StreamWriter(errorLogFileName)) { file.WriteLine(errorLogFileName, firstLine); } } public void RunTests(string[] testCommands) { try { ReleaseTests.AssertDebugNotDefined(); } catch (Exception e) { DumpException(e); } try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); } catch (Exception e) { DumpException(e); } } void DumpException(Exception e) { using (StreamWriter w = File.AppendText(errorLogFileName)) { w.WriteLine(e.Message); w.Write(e.StackTrace); w.WriteLine(); } } } } ```
55689919-e178-4eba-9761-e5b3823e6265
{ "language": "C#" }
```c# using System; namespace UnhelpfulDebugger { class Program { static void Main() { string awkward1 = "Foo\\Bar"; string awkward2 = "FindEle‌​ment"; float awkward3 = 4.9999995f; Console.WriteLine(awkward1); PrintString(awkward1); Console.WriteLine(awkward2); PrintString(awkward2); Console.WriteLine(awkward3); PrintDouble(awkward3); } static void PrintString(string text) { Console.WriteLine($"Text: '{text}'"); Console.WriteLine($"Length: {text.Length}"); for (int i = 0; i < text.Length; i++) { Console.WriteLine($"{i,2} U+{((int)text[i]):0000} '{text[i]}'"); } } static void PrintDouble(double value) => Console.WriteLine(DoubleConverter.ToExactString(value)); } } ``` Use double instead of float
```c# using System; namespace UnhelpfulDebugger { class Program { static void Main() { string awkward1 = "Foo\\Bar"; string awkward2 = "FindEle‌​ment"; double awkward3 = 4.9999999999999995d; Console.WriteLine(awkward1); PrintString(awkward1); Console.WriteLine(awkward2); PrintString(awkward2); Console.WriteLine(awkward3); PrintDouble(awkward3); } static void PrintString(string text) { Console.WriteLine($"Text: '{text}'"); Console.WriteLine($"Length: {text.Length}"); for (int i = 0; i < text.Length; i++) { Console.WriteLine($"{i,2} U+{((int)text[i]):0000} '{text[i]}'"); } } static void PrintDouble(double value) => Console.WriteLine(DoubleConverter.ToExactString(value)); } } ```
608330a4-207e-43d5-bcd0-4ec963ecd60b
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Foundation; using osu.Framework.Input; namespace osu.Framework.iOS.Input { public class IOSTextInput : ITextInputSource { private readonly IOSGameView view; private string pending = string.Empty; public IOSTextInput(IOSGameView view) { this.view = view; } public bool ImeActive => false; public string GetPendingText() { try { return pending; } finally { pending = string.Empty; } } private void handleShouldChangeCharacters(NSRange range, string text) { if (text == " " || text.Trim().Length > 0) pending += text; } public void Deactivate(object sender) { view.KeyboardTextField.HandleShouldChangeCharacters -= handleShouldChangeCharacters; view.KeyboardTextField.UpdateFirstResponder(false); } public void Activate(object sender) { view.KeyboardTextField.HandleShouldChangeCharacters += handleShouldChangeCharacters; view.KeyboardTextField.UpdateFirstResponder(true); } public event Action<string> OnNewImeComposition; public event Action<string> OnNewImeResult; } } ``` Use empty accessor for unimplemented events.
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Foundation; using osu.Framework.Input; namespace osu.Framework.iOS.Input { public class IOSTextInput : ITextInputSource { private readonly IOSGameView view; private string pending = string.Empty; public IOSTextInput(IOSGameView view) { this.view = view; } public bool ImeActive => false; public string GetPendingText() { try { return pending; } finally { pending = string.Empty; } } private void handleShouldChangeCharacters(NSRange range, string text) { if (text == " " || text.Trim().Length > 0) pending += text; } public void Deactivate(object sender) { view.KeyboardTextField.HandleShouldChangeCharacters -= handleShouldChangeCharacters; view.KeyboardTextField.UpdateFirstResponder(false); } public void Activate(object sender) { view.KeyboardTextField.HandleShouldChangeCharacters += handleShouldChangeCharacters; view.KeyboardTextField.UpdateFirstResponder(true); } public event Action<string> OnNewImeComposition { add { } remove { } } public event Action<string> OnNewImeResult { add { } remove { } } } } ```
abbd5608-c8ef-4bdf-b4c5-18058951bc17
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Input.StateChanges.Events; using osu.Framework.Input.States; using osuTK; namespace osu.Framework.Input.StateChanges { /// <summary> /// Denotes a relative change of mouse scroll. /// Pointing devices such as mice provide relative scroll input. /// </summary> public class MouseScrollRelativeInput : IInput { /// <summary> /// The change in scroll. This is added to the current scroll. /// </summary> public Vector2 Delta; /// <summary> /// Whether the change came from a device supporting precision scrolling. /// </summary> /// <remarks> /// In cases this is true, scroll events will generally map 1:1 to user's input, rather than incrementing in large "notches" (as expected of traditional scroll wheels). /// </remarks> public bool IsPrecise; public void Apply(InputState state, IInputStateChangeHandler handler) { var mouse = state.Mouse; if (Delta != Vector2.Zero) { var lastScroll = mouse.Scroll; mouse.Scroll += Delta; mouse.LastSource = this; handler.HandleInputStateChange(new MouseScrollChangeEvent(state, this, lastScroll, IsPrecise)); } } } } ``` Convert vertical scroll to horizontal when shift is held
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Input.StateChanges.Events; using osu.Framework.Input.States; using osuTK; namespace osu.Framework.Input.StateChanges { /// <summary> /// Denotes a relative change of mouse scroll. /// Pointing devices such as mice provide relative scroll input. /// </summary> public class MouseScrollRelativeInput : IInput { /// <summary> /// The change in scroll. This is added to the current scroll. /// </summary> public Vector2 Delta; /// <summary> /// Whether the change came from a device supporting precision scrolling. /// </summary> /// <remarks> /// In cases this is true, scroll events will generally map 1:1 to user's input, rather than incrementing in large "notches" (as expected of traditional scroll wheels). /// </remarks> public bool IsPrecise; public void Apply(InputState state, IInputStateChangeHandler handler) { var mouse = state.Mouse; if (Delta != Vector2.Zero) { if (!IsPrecise && Delta.X == 0 && state.Keyboard.ShiftPressed) Delta = new Vector2(Delta.Y, 0); var lastScroll = mouse.Scroll; mouse.Scroll += Delta; mouse.LastSource = this; handler.HandleInputStateChange(new MouseScrollChangeEvent(state, this, lastScroll, IsPrecise)); } } } } ```
75d92413-66dc-4c8b-a900-8770b4bcd62a
{ "language": "C#" }
```c#  @{ ViewBag.Title = "Employees Overview"; } <h2>Employees Overview</h2> You can only see this page if you have the <strong>employee_read</strong> permissions. ``` Hide or show button in sample application
```c# @using System.Security.Claims @{ ViewBag.Title = "Employees Overview"; } <h2>Employees Overview</h2> You can only see this page if you have the <strong>employee_read</strong> permissions. <br/> <br/> @if (ClaimsPrincipal.Current.HasClaim(ClaimTypes.Role, "employee_create")) { <a href="@Url.Action("Create", "Employee")" class="btn btn-info btn-lg">Create a new employee</a> }```