Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add standalone ifdef to leap example scene script | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using TMPro;
#if LEAPMOTIONCORE_PRESENT
using Microsoft.MixedReality.Toolkit.LeapMotion.Input;
#endif
namespace Microsoft.MixedReality.Toolkit.Examples
{
/// <summary>
/// Returns the orientation of Leap Motion Controller
/// </summary>
public class LeapMotionOrientationDisplay : MonoBehaviour
{
#if LEAPMOTIONCORE_PRESENT
[SerializeField]
private TextMeshProUGUI orientationText;
private LeapMotionDeviceManagerProfile managerProfile;
private void Start()
{
if (GetLeapManager())
{
orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString();
}
else
{
orientationText.text = "Orientation: Unavailable";
}
}
private LeapMotionDeviceManagerProfile GetLeapManager()
{
if (!MixedRealityToolkit.Instance.ActiveProfile)
{
return null;
}
foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations)
{
if (config.ComponentType == typeof(LeapMotionDeviceManager))
{
managerProfile = (LeapMotionDeviceManagerProfile)config.Profile;
return managerProfile;
}
}
return null;
}
#endif
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using Microsoft.MixedReality.Toolkit.Input;
using TMPro;
#if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE
using Microsoft.MixedReality.Toolkit.LeapMotion.Input;
#endif
namespace Microsoft.MixedReality.Toolkit.Examples
{
/// <summary>
/// Returns the orientation of Leap Motion Controller
/// </summary>
public class LeapMotionOrientationDisplay : MonoBehaviour
{
#if LEAPMOTIONCORE_PRESENT && UNITY_STANDALONE
[SerializeField]
private TextMeshProUGUI orientationText;
private LeapMotionDeviceManagerProfile managerProfile;
private void Start()
{
if (GetLeapManager())
{
orientationText.text = "Orientation: " + GetLeapManager().LeapControllerOrientation.ToString();
}
else
{
orientationText.text = "Orientation: Unavailable";
}
}
private LeapMotionDeviceManagerProfile GetLeapManager()
{
if (!MixedRealityToolkit.Instance.ActiveProfile)
{
return null;
}
foreach (MixedRealityInputDataProviderConfiguration config in MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.DataProviderConfigurations)
{
if (config.ComponentType == typeof(LeapMotionDeviceManager))
{
managerProfile = (LeapMotionDeviceManagerProfile)config.Profile;
return managerProfile;
}
}
return null;
}
#endif
}
}
|
Add max job count to levels | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Levels : MonoBehaviour
{
/* Cette classe a pour destin d'être sur un prefab.
* Ce prefab agira comme une config manuelle de niveaux pour faciliter le level design.
* On pourra faire différentes configs si on veut (mettons une par difficulté) et ultimement glisser cette config dans le gamecontroller
* pour qu'il s'en serve.
* */
[SerializeField] WorkDay[] days;
int currentLevel = 0;
public void StartNext()
{
//starts next level
}
public void EndCurrent()
{
//ends current level
currentLevel++;
if (days[currentLevel].AddsJob)
{
// add a job to pool
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Levels : MonoBehaviour
{
/* Cette classe a pour destin d'être sur un prefab.
* Ce prefab agira comme une config manuelle de niveaux pour faciliter le level design.
* On pourra faire différentes configs si on veut (mettons une par difficulté) et ultimement glisser cette config dans le gamecontroller
* pour qu'il s'en serve.
* */
[SerializeField] WorkDay[] days;
[SerializeField] int maxJobCount;
int currentLevel = 0;
public void StartNext()
{
//starts next level
}
public void EndCurrent()
{
//ends current level
currentLevel++;
if (days[currentLevel].AddsJob)
{
// add a job to pool
// if this brings us over maximum, change a job instead
}
}
}
|
Use static HttpClient in SO module | using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Modix.Services.StackExchange
{
public class StackExchangeService
{
private string _ApiReferenceUrl =
$"http://api.stackexchange.com/2.2/search/advanced" +
"?key={0}" +
$"&order=desc" +
$"&sort=votes" +
$"&filter=default";
public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags)
{
_ApiReferenceUrl = string.Format(_ApiReferenceUrl, token);
phrase = Uri.EscapeDataString(phrase);
site = Uri.EscapeDataString(site);
tags = Uri.EscapeDataString(tags);
var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}";
var client = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
});
var response = await client.GetAsync(query);
if (!response.IsSuccessStatusCode)
{
throw new WebException("Something failed while querying the Stack Exchange API.");
}
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<StackExchangeResponse>(json);
}
}
}
| using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Modix.Services.StackExchange
{
public class StackExchangeService
{
private static HttpClient HttpClient => new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
});
private string _ApiReferenceUrl =
$"http://api.stackexchange.com/2.2/search/advanced" +
"?key={0}" +
$"&order=desc" +
$"&sort=votes" +
$"&filter=default";
public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags)
{
_ApiReferenceUrl = string.Format(_ApiReferenceUrl, token);
phrase = Uri.EscapeDataString(phrase);
site = Uri.EscapeDataString(site);
tags = Uri.EscapeDataString(tags);
var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}";
var response = await HttpClient.GetAsync(query);
if (!response.IsSuccessStatusCode)
{
throw new WebException("Something failed while querying the Stack Exchange API.");
}
var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<StackExchangeResponse>(jsonResponse);
}
}
}
|
Fix assembly and file versions | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle(".NET Winforms Gantt Chart Control")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Braincase Solutions")]
[assembly: AssemblyProduct("GanttChartControl")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("e316b126-c783-4060-95b9-aa8ee2e676d7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.3")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle(".NET Winforms Gantt Chart Control")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Braincase Solutions")]
[assembly: AssemblyProduct("GanttChartControl")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("e316b126-c783-4060-95b9-aa8ee2e676d7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.4")]
|
Reduce testing of coordinate nodes call | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Consul.Test
{
[TestClass]
public class CoordinateTest
{
[TestMethod]
public void TestCoordinate_Datacenters()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var datacenters = client.Coordinate.Datacenters();
Assert.IsNotNull(datacenters.Response);
Assert.IsTrue(datacenters.Response.Length > 0);
}
[TestMethod]
public void TestCoordinate_Nodes()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var nodes = client.Coordinate.Nodes();
Assert.IsNotNull(nodes.Response);
Assert.IsTrue(nodes.Response.Length > 0);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Consul.Test
{
[TestClass]
public class CoordinateTest
{
[TestMethod]
public void Coordinate_Datacenters()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var datacenters = client.Coordinate.Datacenters();
Assert.IsNotNull(datacenters.Response);
Assert.IsTrue(datacenters.Response.Length > 0);
}
[TestMethod]
public void Coordinate_Nodes()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var nodes = client.Coordinate.Nodes();
// There's not a good way to populate coordinates without
// waiting for them to calculate and update, so the best
// we can do is call the endpoint and make sure we don't
// get an error. - from offical API.
Assert.IsNotNull(nodes);
}
}
}
|
Normalize directory separator char for finding the embedded icon | using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using PackageExplorerViewModel;
namespace PackageExplorer
{
public class PackageIconConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values?.Length > 1 && values[0] is PackageViewModel package && values[1] is string str && !string.IsNullOrEmpty(str))
{
var metadata = package.PackageMetadata;
if (!string.IsNullOrEmpty(metadata.Icon))
{
foreach (var file in package.RootFolder.GetFiles())
{
if (string.Equals(file.Path, metadata.Icon, StringComparison.OrdinalIgnoreCase))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = file.GetStream();
image.EndInit();
return image;
}
}
}
if (metadata.IconUrl != null)
{
var image = new BitmapImage();
image.BeginInit();
image.UriSource = metadata.IconUrl;
image.EndInit();
return image;
}
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
| using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using PackageExplorerViewModel;
namespace PackageExplorer
{
public class PackageIconConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values?.Length > 1 && values[0] is PackageViewModel package && values[1] is string str && !string.IsNullOrEmpty(str))
{
var metadata = package.PackageMetadata;
if (!string.IsNullOrEmpty(metadata.Icon))
{
// Normalize any directories to match what's the package
// We do this here instead of the metadata so that we round-trip
// whatever the user originally had when in edit view
var iconPath = metadata.Icon.Replace('/', '\\');
foreach (var file in package.RootFolder.GetFiles())
{
if (string.Equals(file.Path, iconPath, StringComparison.OrdinalIgnoreCase))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = file.GetStream();
image.EndInit();
return image;
}
}
}
if (metadata.IconUrl != null)
{
var image = new BitmapImage();
image.BeginInit();
image.UriSource = metadata.IconUrl;
image.EndInit();
return image;
}
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
|
Add doc comments for Author and Committer | using System.Collections.Generic;
using System.Diagnostics;
namespace Octokit
{
/// <summary>
/// An enhanced git commit containing links to additional resources
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class GitHubCommit : GitReference
{
public GitHubCommit() { }
public GitHubCommit(string url, string label, string @ref, string sha, User user, Repository repository, Author author, string commentsUrl, Commit commit, Author committer, string htmlUrl, GitHubCommitStats stats, IReadOnlyList<GitReference> parents, IReadOnlyList<GitHubCommitFile> files)
: base(url, label, @ref, sha, user, repository)
{
Author = author;
CommentsUrl = commentsUrl;
Commit = commit;
Committer = committer;
HtmlUrl = htmlUrl;
Stats = stats;
Parents = parents;
Files = files;
}
public Author Author { get; protected set; }
public string CommentsUrl { get; protected set; }
public Commit Commit { get; protected set; }
public Author Committer { get; protected set; }
public string HtmlUrl { get; protected set; }
public GitHubCommitStats Stats { get; protected set; }
public IReadOnlyList<GitReference> Parents { get; protected set; }
public IReadOnlyList<GitHubCommitFile> Files { get; protected set; }
}
}
| using System.Collections.Generic;
using System.Diagnostics;
namespace Octokit
{
/// <summary>
/// An enhanced git commit containing links to additional resources
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class GitHubCommit : GitReference
{
public GitHubCommit() { }
public GitHubCommit(string url, string label, string @ref, string sha, User user, Repository repository, Author author, string commentsUrl, Commit commit, Author committer, string htmlUrl, GitHubCommitStats stats, IReadOnlyList<GitReference> parents, IReadOnlyList<GitHubCommitFile> files)
: base(url, label, @ref, sha, user, repository)
{
Author = author;
CommentsUrl = commentsUrl;
Commit = commit;
Committer = committer;
HtmlUrl = htmlUrl;
Stats = stats;
Parents = parents;
Files = files;
}
/// <summary>
/// Gets the GitHub account information for the commit author. It attempts to match the email
/// address used in the commit with the email addresses registered with the GitHub account.
/// If no account corresponds to the commit email, then this property is null.
/// </summary>
public Author Author { get; protected set; }
public string CommentsUrl { get; protected set; }
public Commit Commit { get; protected set; }
/// <summary>
/// Gets the GitHub account information for the commit committer. It attempts to match the email
/// address used in the commit with the email addresses registered with the GitHub account.
/// If no account corresponds to the commit email, then this property is null.
/// </summary>
public Author Committer { get; protected set; }
public string HtmlUrl { get; protected set; }
public GitHubCommitStats Stats { get; protected set; }
public IReadOnlyList<GitReference> Parents { get; protected set; }
public IReadOnlyList<GitHubCommitFile> Files { get; protected set; }
}
}
|
Fix mono bug in the FontHelper class | using System;
using System.Drawing;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontAndStyle_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
}
}
}
| using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
}
}
}
|
Remove trailing spaces from stamnummer. | /*
* Copyright 2017 Chirojeugd-Vlaanderen vzw. See the NOTICE file at the
* top-level directory of this distribution, and at
* https://gapwiki.chiro.be/copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using Chiro.Gap.Api.Models;
using Chiro.Gap.ServiceContracts.DataContracts;
namespace Chiro.Gap.Api
{
public static class MappingHelper
{
public static void CreateMappings()
{
// TODO: Damn, nog steeds automapper 3. (zie #5401).
Mapper.CreateMap<GroepInfo, GroepModel>();
}
}
} | /*
* Copyright 2017 Chirojeugd-Vlaanderen vzw. See the NOTICE file at the
* top-level directory of this distribution, and at
* https://gapwiki.chiro.be/copyright
*
* 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 AutoMapper;
using Chiro.Gap.Api.Models;
using Chiro.Gap.ServiceContracts.DataContracts;
namespace Chiro.Gap.Api
{
public static class MappingHelper
{
public static void CreateMappings()
{
// TODO: Damn, nog steeds automapper 3. (zie #5401).
Mapper.CreateMap<GroepInfo, GroepModel>()
.ForMember(dst => dst.StamNummer, opt => opt.MapFrom(src => src.StamNummer.Trim()));
}
}
} |
Fix remove logging controller apiKey parameter | /* Empiria Extensions Framework ******************************************************************************
* *
* Solution : Empiria Extensions Framework System : Empiria Microservices *
* Namespace : Empiria.Microservices Assembly : Empiria.Microservices.dll *
* Type : LoggingController Pattern : Web API Controller *
* Version : 1.0 License : Please read license.txt file *
* *
* Summary : Contains web api methods for application log services. *
* *
********************************** Copyright(c) 2016-2017. La Vía Óntica SC, Ontica LLC and contributors. **/
using System;
using System.Web.Http;
using Empiria.Logging;
using Empiria.Security;
using Empiria.WebApi;
namespace Empiria.Microservices {
/// <summary>Contains web api methods for application log services.</summary>
public class LoggingController : WebApiController {
#region Public APIs
/// <summary>Stores an array of log entries.</summary>
/// <param name="logEntries">The non-empty array of LogEntryModel instances.</param>
[HttpPost, AllowAnonymous]
[Route("v1/logging")]
public void PostLogEntryArray(string apiKey, [FromBody] LogEntryModel[] logEntries) {
try {
ClientApplication clientApplication = base.GetClientApplication();
var logTrail = new LogTrail(clientApplication);
logTrail.Write(logEntries);
} catch (Exception e) {
throw base.CreateHttpException(e);
}
}
#endregion Public APIs
} // class LoggingController
} // namespace Empiria.Microservices
| /* Empiria Extensions Framework ******************************************************************************
* *
* Module : Empiria Web Api Component : Base controllers *
* Assembly : Empiria.WebApi.dll Pattern : Web Api Controller *
* Type : LoggingController License : Please read LICENSE.txt file *
* *
* Summary : Contains web api methods for application log services. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using System.Web.Http;
using Empiria.Logging;
using Empiria.Security;
namespace Empiria.WebApi.Controllers {
/// <summary>Contains web api methods for application log services.</summary>
public class LoggingController : WebApiController {
#region Public APIs
/// <summary>Stores an array of log entries.</summary>
/// <param name="logEntries">The non-empty array of LogEntryModel instances.</param>
[HttpPost, AllowAnonymous]
[Route("v1/logging")]
public void PostLogEntryArray([FromBody] LogEntryModel[] logEntries) {
try {
ClientApplication clientApplication = base.GetClientApplication();
var logTrail = new LogTrail(clientApplication);
logTrail.Write(logEntries);
} catch (Exception e) {
throw base.CreateHttpException(e);
}
}
#endregion Public APIs
} // class LoggingController
} // namespace Empiria.WebApi.Controllers
|
Use local function to verify mimetype string. | using System;
using System.Threading.Tasks;
using Windows.Storage;
namespace Papyrus
{
public static class EBookExtensions
{
public static async Task<bool> VerifyMimetypeAsync(this EBook ebook)
{
var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype");
if (mimetypeFile == null) // Make sure file exists.
return false;
var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile);
if (fileContents != "application/epub+zip") // Make sure file contents are correct.
return false;
return true;
}
}
}
| using System;
using System.Threading.Tasks;
using Windows.Storage;
namespace Papyrus
{
public static class EBookExtensions
{
public static async Task<bool> VerifyMimetypeAsync(this EBook ebook)
{
bool VerifyMimetypeString(string value) =>
value == "application/epub+zip";
if (ebook._rootFolder == null) // Make sure a root folder was specified.
return false;
var mimetypeFile = await ebook._rootFolder.GetItemAsync("mimetype");
if (mimetypeFile == null) // Make sure file exists.
return false;
var fileContents = await FileIO.ReadTextAsync(mimetypeFile as StorageFile);
if (!VerifyMimetypeString(fileContents)) // Make sure file contents are correct.
return false;
return true;
}
}
}
|
Rename GenerateWallet menuitem to WalletManager | using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;
namespace WalletWasabi.Gui.Shell.MainMenu
{
internal class ToolsMainMenuItems
{
private IMenuItemFactory _menuItemFactory;
[ImportingConstructor]
public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
{
_menuItemFactory = menuItemFactory;
}
#region MainMenu
[ExportMainMenuItem("Tools")]
[DefaultOrder(1)]
public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);
#endregion MainMenu
#region Group
[ExportMainMenuDefaultGroup("Tools", "Managers")]
[DefaultOrder(0)]
public object ManagersGroup => null;
[ExportMainMenuDefaultGroup("Tools", "Settings")]
[DefaultOrder(1)]
public object SettingsGroup => null;
#endregion Group
#region MenuItem
[ExportMainMenuItem("Tools", "Wallet Manager")]
[DefaultOrder(0)]
[DefaultGroup("Managers")]
public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");
[ExportMainMenuItem("Tools", "Settings")]
[DefaultOrder(1)]
[DefaultGroup("Settings")]
public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");
#endregion MenuItem
}
}
| using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;
namespace WalletWasabi.Gui.Shell.MainMenu
{
internal class ToolsMainMenuItems
{
private IMenuItemFactory _menuItemFactory;
[ImportingConstructor]
public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
{
_menuItemFactory = menuItemFactory;
}
#region MainMenu
[ExportMainMenuItem("Tools")]
[DefaultOrder(1)]
public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);
#endregion MainMenu
#region Group
[ExportMainMenuDefaultGroup("Tools", "Managers")]
[DefaultOrder(0)]
public object ManagersGroup => null;
[ExportMainMenuDefaultGroup("Tools", "Settings")]
[DefaultOrder(1)]
public object SettingsGroup => null;
#endregion Group
#region MenuItem
[ExportMainMenuItem("Tools", "Wallet Manager")]
[DefaultOrder(0)]
[DefaultGroup("Managers")]
public IMenuItem WalletManager => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");
[ExportMainMenuItem("Tools", "Settings")]
[DefaultOrder(1)]
[DefaultGroup("Settings")]
public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");
#endregion MenuItem
}
}
|
Save xpub instead of hex (wallet compatibility) | using NBitcoin;
using Newtonsoft.Json;
using System;
namespace WalletWasabi.JsonConverters
{
public class ExtPubKeyJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ExtPubKey);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var hex = (string)reader.Value;
return new ExtPubKey(ByteHelpers.FromHex(hex));
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var epk = (ExtPubKey)value;
var hex = ByteHelpers.ToHex(epk.ToBytes());
writer.WriteValue(hex);
}
}
}
| using NBitcoin;
using Newtonsoft.Json;
using System;
namespace WalletWasabi.JsonConverters
{
public class ExtPubKeyJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ExtPubKey);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var s = (string)reader.Value;
ExtPubKey epk;
try
{
epk = ExtPubKey.Parse(s);
}
catch
{
// Try hex, Old wallet format was like this.
epk = new ExtPubKey(ByteHelpers.FromHex(s));
}
return epk;
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var epk = (ExtPubKey)value;
var xpub = epk.GetWif(Network.Main).ToWif();
writer.WriteValue(xpub);
}
}
}
|
Add converters for System.Drawing structures. | using System;
using System.Collections.Generic;
using System.Text;
using Draw = System.Drawing;
using Geo = ERY.AgateLib.Geometry;
namespace ERY.AgateLib.WinForms
{
public static class FormsInterop
{
public static Draw.Rectangle ToRectangle(Geo.Rectangle rect)
{
return new System.Drawing.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Draw = System.Drawing;
using ERY.AgateLib.Geometry;
namespace ERY.AgateLib.WinForms
{
public static class FormsInterop
{
public static Draw.Color ConvertColor(Color clr)
{
return Draw.Color.FromArgb(clr.ToArgb());
}
public static Color ConvertColor(Draw.Color clr)
{
return Color.FromArgb(clr.ToArgb());
}
public static Draw.Rectangle ConvertRectangle(Rectangle rect)
{
return new Draw.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
}
public static Rectangle ConvertRectangle(Draw.Rectangle rect)
{
return new Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
}
public static Draw.RectangleF ConvertRectangleF(RectangleF rect)
{
return new Draw.RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
}
public static RectangleF ConvertRectangleF(Draw.RectangleF rect)
{
return new RectangleF(rect.X, rect.Y, rect.Width, rect.Height);
}
public static Point ConvertPoint(Draw.Point pt)
{
return new Point(pt.X, pt.Y);
}
public static Draw.Point ConvertPoint(Point pt)
{
return new Draw.Point(pt.X, pt.Y);
}
public static PointF ConvertPointF(Draw.PointF pt)
{
return new PointF(pt.X, pt.Y);
}
public static Draw.PointF ConvertPointF(PointF pt)
{
return new Draw.PointF(pt.X, pt.Y);
}
public static Size ConvertSize(Draw.Size pt)
{
return new Size(pt.Width, pt.Height);
}
public static Draw.Size ConvertSize(Size pt)
{
return new Draw.Size(pt.Width, pt.Height);
}
public static SizeF ConvertSizeF(Draw.SizeF pt)
{
return new SizeF(pt.Width, pt.Height);
}
public static Draw.SizeF ConvertSizeF(SizeF pt)
{
return new Draw.SizeF(pt.Width, pt.Height);
}
}
}
|
Allow spaces in !meme command. | using System.Text.RegularExpressions;
namespace MarekMotykaBot.ExtensionsMethods
{
public static class StringExtensions
{
public static string RemoveRepeatingChars(this string inputString)
{
string newString = string.Empty;
char[] charArray = inputString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if (string.IsNullOrEmpty(newString))
newString += charArray[i].ToString();
else if (newString[newString.Length - 1] != charArray[i])
newString += charArray[i].ToString();
}
return newString;
}
public static string RemoveEmojis(this string inputString)
{
return Regex.Replace(inputString, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}
public static string RemoveEmotes(this string inputString)
{
return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
}
public static string RemoveEmojisAndEmotes(this string inputString)
{
return inputString.RemoveEmotes().RemoveEmojis();
}
}
} | using System.Text.RegularExpressions;
namespace MarekMotykaBot.ExtensionsMethods
{
public static class StringExtensions
{
public static string RemoveRepeatingChars(this string inputString)
{
string newString = string.Empty;
char[] charArray = inputString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if (string.IsNullOrEmpty(newString))
newString += charArray[i].ToString();
else if (newString[newString.Length - 1] != charArray[i])
newString += charArray[i].ToString();
}
return newString;
}
public static string RemoveEmojis(this string inputString)
{
return Regex.Replace(inputString, @"[^a-zA-Z0-9\s]+", "", RegexOptions.Compiled);
}
public static string RemoveEmotes(this string inputString)
{
return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
}
public static string RemoveEmojisAndEmotes(this string inputString)
{
return inputString.RemoveEmotes().RemoveEmojis();
}
}
} |
Change version to a reasonable value | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("libcmdline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libcmdline")]
[assembly: AssemblyCopyright("")]
[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("853c7fe9-e12b-484c-93de-3f3de6907860")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("libcmdline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libcmdline")]
[assembly: AssemblyCopyright("")]
[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("853c7fe9-e12b-484c-93de-3f3de6907860")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
|
Fix a bug where dates are sometimes '-' | using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VirusTotalNET.Exceptions;
namespace VirusTotalNET.DateTimeParsers
{
public class YearMonthDayConverter : DateTimeConverterBase
{
private readonly CultureInfo _culture = new CultureInfo("en-us");
private const string _dateFormatString = "yyyyMMdd";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.DateFormatString = _dateFormatString;
writer.WriteValue(value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return DateTime.MinValue;
if (!(reader.Value is string))
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + reader.Value);
string value = (string)reader.Value;
if (DateTime.TryParseExact(value, _dateFormatString, _culture, DateTimeStyles.AllowWhiteSpaces, out DateTime result))
return result;
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + value);
}
}
} | using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VirusTotalNET.Exceptions;
namespace VirusTotalNET.DateTimeParsers
{
public class YearMonthDayConverter : DateTimeConverterBase
{
private readonly CultureInfo _culture = new CultureInfo("en-us");
private const string _dateFormatString = "yyyyMMdd";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.DateFormatString = _dateFormatString;
writer.WriteValue(value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return DateTime.MinValue;
if (!(reader.Value is string))
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + reader.Value);
string value = (string)reader.Value;
//VT sometimes have really old data that return '-' in timestamps
if (value.Equals("-", StringComparison.OrdinalIgnoreCase))
return DateTime.MinValue;
if (DateTime.TryParseExact(value, _dateFormatString, _culture, DateTimeStyles.AllowWhiteSpaces, out DateTime result))
return result;
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + value);
}
}
} |
Add more types to dropdown | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Configuration
{
public enum ScoreMeterType
{
[Description("None")]
None,
[Description("Hit Error (left)")]
HitErrorLeft,
[Description("Hit Error (right)")]
HitErrorRight,
[Description("Hit Error (both)")]
HitErrorBoth,
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Configuration
{
public enum ScoreMeterType
{
[Description("None")]
None,
[Description("Hit Error (left)")]
HitErrorLeft,
[Description("Hit Error (right)")]
HitErrorRight,
[Description("Hit Error (both)")]
HitErrorBoth,
[Description("Colour (left)")]
ColourLeft,
[Description("Colour (right)")]
ColourRight,
[Description("Colour (both)")]
ColourBoth,
}
}
|
Correct issue where settings.json cannot be found when using a shadow copied DLL. | using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
namespace AudioWorks.Common
{
/// <summary>
/// Manages the retrieval of configuration settings from disk.
/// </summary>
public static class ConfigurationManager
{
/// <summary>
/// Gets the configuration.
/// </summary>
/// <value>The configuration.</value>
[NotNull]
[CLSCompliant(false)]
public static IConfigurationRoot Configuration { get; }
static ConfigurationManager()
{
var settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"AudioWorks");
const string settingsFileName = "settings.json";
// Copy the settings template if the file doesn't already exist
var settingsFile = Path.Combine(settingsPath, settingsFileName);
if (!File.Exists(settingsFile))
{
Directory.CreateDirectory(settingsPath);
File.Copy(
// ReSharper disable once AssignNullToNotNullAttribute
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), settingsFileName),
settingsFile);
}
Configuration = new ConfigurationBuilder()
.SetBasePath(settingsPath)
.AddJsonFile(settingsFileName, true)
.Build();
}
}
}
| using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
namespace AudioWorks.Common
{
/// <summary>
/// Manages the retrieval of configuration settings from disk.
/// </summary>
public static class ConfigurationManager
{
/// <summary>
/// Gets the configuration.
/// </summary>
/// <value>The configuration.</value>
[NotNull]
[CLSCompliant(false)]
public static IConfigurationRoot Configuration { get; }
static ConfigurationManager()
{
var settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"AudioWorks");
const string settingsFileName = "settings.json";
// Copy the settings template if the file doesn't already exist
var settingsFile = Path.Combine(settingsPath, settingsFileName);
if (!File.Exists(settingsFile))
{
Directory.CreateDirectory(settingsPath);
File.Copy(
Path.Combine(
// ReSharper disable once AssignNullToNotNullAttribute
Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath),
settingsFileName),
settingsFile);
}
Configuration = new ConfigurationBuilder()
.SetBasePath(settingsPath)
.AddJsonFile(settingsFileName, true)
.Build();
}
}
}
|
Add test category to authenticated test | using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
namespace RohlikAPITests
{
[TestClass]
public class RohlikovacTests
{
private string[] GetCredentials()
{
string filePath = @"..\..\..\loginPassword.txt";
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Test needs credentials. Create 'loginPassword.txt' in solution root directory. Enter username@email.com:yourPassword on first line.");
}
var passwordString = File.ReadAllText(filePath);
return passwordString.Split(':');
}
[TestMethod]
public void RunTest()
{
var login = GetCredentials();
var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
var result = rohlikApi.RunRohlikovac();
if (result.Contains("error"))
{
Assert.Fail($"Failed to login to rohlik. Login used: {login[0]}");
}
}
}
} | using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
namespace RohlikAPITests
{
[TestClass]
public class RohlikovacTests
{
private string[] GetCredentials()
{
string filePath = @"..\..\..\loginPassword.txt";
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Test needs credentials. Create 'loginPassword.txt' in solution root directory. Enter username@email.com:yourPassword on first line.");
}
var passwordString = File.ReadAllText(filePath);
return passwordString.Split(':');
}
[TestMethod, TestCategory("Authenticated")]
public void RunTest()
{
var login = GetCredentials();
var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
var result = rohlikApi.RunRohlikovac();
if (result.Contains("error"))
{
Assert.Fail($"Failed to login to rohlik. Login used: {login[0]}");
}
}
}
} |
Tweak to content for display on ES marketing site | using System;
using Reachmail.Easysmtp.Post.Request;
public void Main()
{
var reachmail = Reachmail.Api.Create("<API Token>");
var request = new DeliveryRequest {
FromAddress = "from@from.com",
Recipients = new Recipients {
new Recipient {
Address = "to@to.com"
}
},
Subject = "Subject",
BodyText = "Text",
BodyHtml = "<p>html</p>",
Headers = new Headers {
{ "name", "value" }
},
Attachments = new Attachments {
new EmailAttachment {
Filename = "text.txt",
Data = "b2ggaGFp", // Base64 encoded
ContentType = "text/plain",
ContentDisposition = "attachment",
Cid = "<text.txt>"
}
},
Tracking = true,
FooterAddress = "footer@footer.com",
SignatureDomain = "signature.net"
};
var result = reachmail.Easysmtp.Post(request);
} | using System;
using Reachmail.Easysmtp.Post.Request;
public void Main()
{
var reachmail = Reachmail.Api.Create("<API Token>");
var request = new DeliveryRequest {
FromAddress = "from@from.com",
Recipients = new Recipients {
new Recipient {
Address = "to@to.com"
}
},
Subject = "Subject",
BodyText = "Text",
BodyHtml = "html",
Headers = new Headers {
{ "name", "value" }
},
Attachments = new Attachments {
new EmailAttachment {
Filename = "text.txt",
Data = "b2ggaGFp", // Base64 encoded
ContentType = "text/plain",
ContentDisposition = "attachment",
Cid = "<text.txt>"
}
},
Tracking = true,
FooterAddress = "footer@footer.com",
SignatureDomain = "signature.net"
};
var result = reachmail.Easysmtp.Post(request);
}
|
Fix tools being installed to wrong path | using System;
using Cake.Frosting;
public class Program
{
public static int Main(string[] args)
{
return new CakeHost()
.UseContext<Context>()
.UseLifetime<Lifetime>()
.UseWorkingDirectory("..")
.InstallTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"))
.InstallTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"))
.InstallTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"))
.InstallTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"))
.Run(args);
}
}
| using System;
using Cake.Frosting;
public class Program
{
public static int Main(string[] args)
{
return new CakeHost()
.UseContext<Context>()
.UseLifetime<Lifetime>()
.UseWorkingDirectory("..")
.SetToolPath("../tools")
.InstallTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"))
.InstallTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"))
.InstallTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"))
.InstallTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"))
.Run(args);
}
}
|
Add back and cancel button commands | using System.Reactive.Linq;
using ReactiveUI;
using System;
namespace WalletWasabi.Fluent.ViewModels
{
public class AddWalletPageViewModel : NavBarItemViewModel
{
private string _walletName = "";
private bool _optionsEnabled;
public AddWalletPageViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.Dialog)
{
Title = "Add Wallet";
this.WhenAnyValue(x => x.WalletName)
.Select(x => !string.IsNullOrWhiteSpace(x))
.Subscribe(x => OptionsEnabled = x);
}
public override string IconName => "add_circle_regular";
public string WalletName
{
get => _walletName;
set => this.RaiseAndSetIfChanged(ref _walletName, value);
}
public bool OptionsEnabled
{
get => _optionsEnabled;
set => this.RaiseAndSetIfChanged(ref _optionsEnabled, value);
}
}
}
| using System.Reactive.Linq;
using ReactiveUI;
using System;
using System.Windows.Input;
namespace WalletWasabi.Fluent.ViewModels
{
public class AddWalletPageViewModel : NavBarItemViewModel
{
private string _walletName = "";
private bool _optionsEnabled;
public AddWalletPageViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.Dialog)
{
Title = "Add Wallet";
BackCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear());
CancelCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear());
this.WhenAnyValue(x => x.WalletName)
.Select(x => !string.IsNullOrWhiteSpace(x))
.Subscribe(x => OptionsEnabled = x);
}
public override string IconName => "add_circle_regular";
public ICommand BackCommand { get; }
public ICommand CancelCommand { get; }
public string WalletName
{
get => _walletName;
set => this.RaiseAndSetIfChanged(ref _walletName, value);
}
public bool OptionsEnabled
{
get => _optionsEnabled;
set => this.RaiseAndSetIfChanged(ref _optionsEnabled, value);
}
}
}
|
Update the GelocationHandler example - seems people are still struggling with the callback concept. | // Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows;
namespace CefSharp.Wpf.Example.Handlers
{
internal class GeolocationHandler : IGeolocationHandler
{
bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback)
{
using (callback)
{
var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo);
callback.Continue(result == MessageBoxResult.Yes);
return result == MessageBoxResult.Yes;
}
}
void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId)
{
}
}
}
| // Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows;
namespace CefSharp.Wpf.Example.Handlers
{
internal class GeolocationHandler : IGeolocationHandler
{
bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback)
{
//You can execute the callback inline
//callback.Continue(true);
//return true;
//You can execute the callback in an `async` fashion
//Open a message box on the `UI` thread and ask for user input.
//You can open a form, or do whatever you like, just make sure you either
//execute the callback or call `Dispose` as it's an `unmanaged` wrapper.
var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
chromiumWebBrowser.Dispatcher.BeginInvoke((Action)(() =>
{
//Callback wraps an unmanaged resource, so we'll make sure it's Disposed (calling Continue will also Dipose of the callback, it's safe to dispose multiple times).
using (callback)
{
var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo);
//Execute the callback, to allow/deny the request.
callback.Continue(result == MessageBoxResult.Yes);
}
}));
//Yes we'd like to hadle this request ourselves.
return true;
}
void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId)
{
}
}
}
|
Handle message changing inventory size | using System.Drawing;
using MonoHaven.UI.Widgets;
namespace MonoHaven.UI.Remote
{
public class ServerInventoryWidget : ServerWidget
{
public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
{
var size = (Point)args[0];
var widget = new InventoryWidget(parent.Widget);
widget.SetInventorySize(size);
return new ServerInventoryWidget(id, parent, widget);
}
public ServerInventoryWidget(ushort id, ServerWidget parent, InventoryWidget widget)
: base(id, parent, widget)
{
widget.Drop += (p) => SendMessage("drop", p);
widget.Transfer += OnTransfer;
}
private void OnTransfer(TransferEventArgs e)
{
var mods = ServerInput.ToServerModifiers(e.Modifiers);
SendMessage("xfer", e.Delta, mods);
}
}
}
| using System.Drawing;
using MonoHaven.UI.Widgets;
namespace MonoHaven.UI.Remote
{
public class ServerInventoryWidget : ServerWidget
{
public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
{
var size = (Point)args[0];
var widget = new InventoryWidget(parent.Widget);
widget.SetInventorySize(size);
return new ServerInventoryWidget(id, parent, widget);
}
private readonly InventoryWidget widget;
public ServerInventoryWidget(ushort id, ServerWidget parent, InventoryWidget widget)
: base(id, parent, widget)
{
this.widget = widget;
this.widget.Drop += (p) => SendMessage("drop", p);
this.widget.Transfer += OnTransfer;
}
public override void ReceiveMessage(string message, object[] args)
{
if (message == "sz")
widget.SetInventorySize((Point)args[0]);
else
base.ReceiveMessage(message, args);
}
private void OnTransfer(TransferEventArgs e)
{
var mods = ServerInput.ToServerModifiers(e.Modifiers);
SendMessage("xfer", e.Delta, mods);
}
}
}
|
Use polling rate of 30 | using CommandLine;
using System;
using System.IO;
using System.Threading;
using WebScriptHook.Framework;
using WebScriptHook.Framework.BuiltinPlugins;
using WebScriptHook.Framework.Plugins;
using WebScriptHook.Service.Plugins;
namespace WebScriptHook.Service
{
class Program
{
static WebScriptHookComponent wshComponent;
static void Main(string[] args)
{
string componentName = Guid.NewGuid().ToString();
Uri remoteUri;
var options = new CommandLineOptions();
if (Parser.Default.ParseArguments(args, options))
{
if (!string.IsNullOrWhiteSpace(options.Name)) componentName = options.Name;
remoteUri = new Uri(options.ServerUriString);
}
else
{
return;
}
wshComponent = new WebScriptHookComponent(componentName, remoteUri, Console.Out, LogType.All);
// Register custom plugins
wshComponent.PluginManager.RegisterPlugin(new Echo());
wshComponent.PluginManager.RegisterPlugin(new PluginList());
wshComponent.PluginManager.RegisterPlugin(new PrintToScreen());
// Load plugins in plugins directory if dir exists
if (Directory.Exists("plugins"))
{
var plugins = PluginLoader.LoadAllPluginsFromDir("plugins", "*.dll");
foreach (var plug in plugins)
{
wshComponent.PluginManager.RegisterPlugin(plug);
}
}
// Start WSH component
wshComponent.Start();
// TODO: Use a timer instead of Sleep
while (true)
{
wshComponent.Update();
Thread.Sleep(100);
}
}
}
}
| using CommandLine;
using System;
using System.IO;
using System.Threading;
using WebScriptHook.Framework;
using WebScriptHook.Framework.BuiltinPlugins;
using WebScriptHook.Framework.Plugins;
using WebScriptHook.Service.Plugins;
namespace WebScriptHook.Service
{
class Program
{
static WebScriptHookComponent wshComponent;
static void Main(string[] args)
{
string componentName = Guid.NewGuid().ToString();
Uri remoteUri;
var options = new CommandLineOptions();
if (Parser.Default.ParseArguments(args, options))
{
if (!string.IsNullOrWhiteSpace(options.Name)) componentName = options.Name;
remoteUri = new Uri(options.ServerUriString);
}
else
{
return;
}
wshComponent = new WebScriptHookComponent(componentName, remoteUri, TimeSpan.FromMilliseconds(30), Console.Out, LogType.All);
// Register custom plugins
wshComponent.PluginManager.RegisterPlugin(new Echo());
wshComponent.PluginManager.RegisterPlugin(new PluginList());
wshComponent.PluginManager.RegisterPlugin(new PrintToScreen());
// Load plugins in plugins directory if dir exists
if (Directory.Exists("plugins"))
{
var plugins = PluginLoader.LoadAllPluginsFromDir("plugins", "*.dll");
foreach (var plug in plugins)
{
wshComponent.PluginManager.RegisterPlugin(plug);
}
}
// Start WSH component
wshComponent.Start();
// TODO: Use a timer instead of Sleep
while (true)
{
wshComponent.Update();
Thread.Sleep(100);
}
}
}
}
|
Fix handling of transient bindings to accomodate bindings that have been specified for an ancestral type | using System;
using System.Collections.Generic;
namespace WootzJs.Injection
{
public class Context
{
private ICache cache;
private IDictionary<Type, IBinding> transientBindings;
public Context(Context context = null, ICache cache = null, IDictionary<Type, IBinding> transientBindings = null)
{
cache = cache ?? new Cache();
this.cache = context != null ? new HybridCache(cache, context.Cache) : cache;
this.transientBindings = transientBindings;
}
public ICache Cache
{
get { return cache; }
}
public IBinding GetCustomBinding(Type type)
{
if (transientBindings == null)
return null;
IBinding result;
transientBindings.TryGetValue(type, out result);
return result;
}
}
} | using System;
using System.Collections.Generic;
namespace WootzJs.Injection
{
public class Context
{
private ICache cache;
private IDictionary<Type, IBinding> transientBindings;
public Context(Context context = null, ICache cache = null, IDictionary<Type, IBinding> transientBindings = null)
{
cache = cache ?? new Cache();
this.cache = context != null ? new HybridCache(cache, context.Cache) : cache;
this.transientBindings = transientBindings;
}
public ICache Cache
{
get { return cache; }
}
public IBinding GetCustomBinding(Type type)
{
if (transientBindings == null)
return null;
while (type != null)
{
IBinding result;
if (transientBindings.TryGetValue(type, out result))
return result;
type = type.BaseType;
}
return null;
}
}
} |
Use 1.0.0 as the default informational version so it's easy to spot when it might have been un-patched during a build | using System.Reflection;
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.15")] | using System.Reflection;
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")] |
Add Try block. bugid: 623 | #if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using UnitDriven;
namespace Csla.Test.Silverlight.Rollback
{
#if SILVERLIGHT
[TestClass]
#endif
public class RollbackTests : TestBase
{
#if SILVERLIGHT
[TestMethod]
public void UnintializedProperty_RollsBack_AfterCancelEdit()
{
var context = GetContext();
RollbackRoot.BeginCreateLocal((o, e) =>
{
var item = e.Object;
var initialValue = 0;// item.UnInitedP;
item.BeginEdit();
item.UnInitedP = 1000;
item.Another = "test";
item.CancelEdit();
context.Assert.AreEqual(initialValue, item.UnInitedP);
context.Assert.Success();
});
context.Complete();
}
#endif
}
}
| #if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using UnitDriven;
namespace Csla.Test.Silverlight.Rollback
{
#if SILVERLIGHT
[TestClass]
#endif
public class RollbackTests : TestBase
{
#if SILVERLIGHT
[TestMethod]
public void UnintializedProperty_RollsBack_AfterCancelEdit()
{
var context = GetContext();
RollbackRoot.BeginCreateLocal((o, e) =>
{
context.Assert.Try(() =>
{
var item = e.Object;
var initialValue = 0;// item.UnInitedP;
item.BeginEdit();
item.UnInitedP = 1000;
item.Another = "test";
item.CancelEdit();
context.Assert.AreEqual(initialValue, item.UnInitedP);
context.Assert.Success();
});
});
context.Complete();
}
#endif
}
}
|
Remove redundant specification of public in interface | // Copyright 2019 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
namespace VDrumExplorer.Data.Fields
{
public interface IField
{
string Description { get; }
FieldPath Path { get; }
ModuleAddress Address { get; }
int Size { get; }
public FieldCondition? Condition { get; }
}
}
| // Copyright 2019 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
namespace VDrumExplorer.Data.Fields
{
public interface IField
{
string Description { get; }
FieldPath Path { get; }
ModuleAddress Address { get; }
int Size { get; }
FieldCondition? Condition { get; }
}
}
|
Use ChatRelay instead of UIManager when examining objects | using JetBrains.Annotations;
using PlayGroups.Input;
using UI;
using UnityEngine;
public class MessageOnInteract : InputTrigger
{
public string Message;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public override void Interact(GameObject originator, Vector3 position, string hand)
{
UIManager.Chat.AddChatEvent(new ChatEvent(Message, ChatChannel.Examine));
}
}
| using JetBrains.Annotations;
using PlayGroups.Input;
using UI;
using UnityEngine;
public class MessageOnInteract : InputTrigger
{
public string Message;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public override void Interact(GameObject originator, Vector3 position, string hand)
{
ChatRelay.Instance.AddToChatLogClient(Message, ChatChannel.Examine);
}
}
|
Make sure Settings is never null | namespace StackExchange.Exceptional.Internal
{
/// <summary>
/// Internal Exceptional static controls, not meant for consumption.
/// This can and probably will break without warning. Don't use the .Internal namespace directly.
/// </summary>
public static class Statics
{
/// <summary>
/// Settings for context-less logging.
/// </summary>
/// <remarks>
/// In ASP.NET (non-Core) this is populated by the ConfigSettings load.
/// In ASP.NET Core this is populated by .Configure() in the DI pipeline.
/// </remarks>
public static ExceptionalSettingsBase Settings { get; set; }
/// <summary>
/// Returns whether an error passed in right now would be logged.
/// </summary>
public static bool IsLoggingEnabled { get; set; } = true;
}
}
| namespace StackExchange.Exceptional.Internal
{
/// <summary>
/// Internal Exceptional static controls, not meant for consumption.
/// This can and probably will break without warning. Don't use the .Internal namespace directly.
/// </summary>
public static class Statics
{
/// <summary>
/// Settings for context-less logging.
/// </summary>
/// <remarks>
/// In ASP.NET (non-Core) this is populated by the ConfigSettings load.
/// In ASP.NET Core this is populated by .Configure() in the DI pipeline.
/// </remarks>
public static ExceptionalSettingsBase Settings { get; set; } = new ExceptionalSettingsDefault();
/// <summary>
/// Returns whether an error passed in right now would be logged.
/// </summary>
public static bool IsLoggingEnabled { get; set; } = true;
}
}
|
Use multicast instead of explicit BehaviourSubject setup | namespace Mappy
{
using System;
using System.ComponentModel;
using System.Reactive.Linq;
using System.Reactive.Subjects;
public static class ExtensionMethods
{
public static IObservable<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged
{
var subject = new BehaviorSubject<TField>(accessor(source));
// FIXME: This is leaky.
// We create a subscription to connect this to the subject
// but we don't hold onto this subscription.
// The subject we return can never be garbage collected
// because the subscription cannot be freed.
Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
x => source.PropertyChanged += x,
x => source.PropertyChanged -= x)
.Where(x => x.EventArgs.PropertyName == name)
.Select(_ => accessor(source))
.Subscribe(subject);
return subject;
}
}
}
| namespace Mappy
{
using System;
using System.ComponentModel;
using System.Reactive.Linq;
using System.Reactive.Subjects;
public static class ExtensionMethods
{
public static IObservable<TField> PropertyAsObservable<TSource, TField>(this TSource source, Func<TSource, TField> accessor, string name) where TSource : INotifyPropertyChanged
{
var obs = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
x => source.PropertyChanged += x,
x => source.PropertyChanged -= x)
.Where(x => x.EventArgs.PropertyName == name)
.Select(_ => accessor(source))
.Multicast(new BehaviorSubject<TField>(accessor(source)));
// FIXME: This is leaky.
// We create a connection here but don't hold on to the reference.
// We can never unregister our event handler without this.
obs.Connect();
return obs;
}
}
}
|
Delete stop reciever, to stop receiver use CancellationToken | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TirkxDownloader.Framework.Interface
{
/// <summary>
/// This interface should be implemented for recieve JSON then parse it and return to caller
/// </summary>
/// <typeparam name="T">Type of message, must be JSON compatibility</typeparam>
interface IMessageReciever<T>
{
ICollection<string> Prefixes { get; }
bool IsRecieving { get; }
Task<T> GetMessageAsync();
/// <summary>
/// Call this method when terminate application
/// </summary>
void Close();
/// <summary>
/// Call this method when you want to stop reciever
/// </summary>
void StopReciever();
}
}
| using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TirkxDownloader.Framework.Interface
{
/// <summary>
/// This interface should be implemented for recieve JSON then parse it and return to caller
/// </summary>
/// <typeparam name="T">Type of message, must be JSON compatibility</typeparam>
public interface IMessageReciever<T>
{
ICollection<string> Prefixes { get; }
bool IsRecieving { get; }
Task<T> GetMessageAsync();
Task<T> GetMessageAsync(CancellationToken ct);
/// <summary>
/// Call this method when terminate application
/// </summary>
void Close();
}
}
|
Change MaybeNullWhenAttribute to internal to remove collision with diagnostics ns | #if NULLABLE_SHIMS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
public sealed class MaybeNullWhenAttribute : Attribute
{
public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; }
public bool ReturnValue { get; }
}
}
#endif
| #if NULLABLE_SHIMS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
internal sealed class MaybeNullWhenAttribute : Attribute
{
public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; }
public bool ReturnValue { get; }
}
}
#endif
|
Fix regression in reading config | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Framework.Configuration;
namespace Microsoft.AspNet.Server.Kestrel
{
public class ServerInformation : IServerInformation, IKestrelServerInformation
{
public ServerInformation()
{
Addresses = new List<ServerAddress>();
}
public void Initialize(IConfiguration configuration)
{
var urls = configuration["server.urls"];
if (!string.IsNullOrEmpty(urls))
{
urls = "http://+:5000/";
}
foreach (var url in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
var address = ServerAddress.FromUrl(url);
if (address != null)
{
Addresses.Add(address);
}
}
}
public string Name
{
get
{
return "Kestrel";
}
}
public IList<ServerAddress> Addresses { get; private set; }
public int ThreadCount { get; set; }
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Framework.Configuration;
namespace Microsoft.AspNet.Server.Kestrel
{
public class ServerInformation : IServerInformation, IKestrelServerInformation
{
public ServerInformation()
{
Addresses = new List<ServerAddress>();
}
public void Initialize(IConfiguration configuration)
{
var urls = configuration["server.urls"];
if (string.IsNullOrEmpty(urls))
{
urls = "http://+:5000/";
}
foreach (var url in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
var address = ServerAddress.FromUrl(url);
if (address != null)
{
Addresses.Add(address);
}
}
}
public string Name
{
get
{
return "Kestrel";
}
}
public IList<ServerAddress> Addresses { get; private set; }
public int ThreadCount { get; set; }
}
}
|
Fix display scoreboard packet id | using System;
using Pdelvo.Minecraft.Network;
namespace Pdelvo.Minecraft.Protocol.Packets
{
[PacketUsage(PacketUsage.ServerToClient)]
public class DisplayScoreboard : Packet
{
public byte Position { get; set; }
public string ScoreName { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DisplayScoreboard" /> class.
/// </summary>
/// <remarks>
/// </remarks>
public DisplayScoreboard()
{
Code = 0xCF;
}
/// <summary>
/// Receives the specified reader.
/// </summary>
/// <param name="reader"> The reader. </param>
/// <param name="version"> The version. </param>
/// <remarks>
/// </remarks>
protected override void OnReceive(BigEndianStream reader, int version)
{
if (reader == null)
throw new ArgumentNullException("reader");
Position = reader.ReadByte();
ScoreName = reader.ReadString16();
}
/// <summary>
/// Sends the specified writer.
/// </summary>
/// <param name="writer"> The writer. </param>
/// <param name="version"> The version. </param>
/// <remarks>
/// </remarks>
protected override void OnSend(BigEndianStream writer, int version)
{
if (writer == null)
throw new ArgumentNullException("writer");
writer.Write(Code);
writer.Write(Position);
writer.Write(ScoreName);
}
}
}
| using System;
using Pdelvo.Minecraft.Network;
namespace Pdelvo.Minecraft.Protocol.Packets
{
[PacketUsage(PacketUsage.ServerToClient)]
public class DisplayScoreboard : Packet
{
public byte Position { get; set; }
public string ScoreName { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DisplayScoreboard" /> class.
/// </summary>
/// <remarks>
/// </remarks>
public DisplayScoreboard()
{
Code = 0xD0;
}
/// <summary>
/// Receives the specified reader.
/// </summary>
/// <param name="reader"> The reader. </param>
/// <param name="version"> The version. </param>
/// <remarks>
/// </remarks>
protected override void OnReceive(BigEndianStream reader, int version)
{
if (reader == null)
throw new ArgumentNullException("reader");
Position = reader.ReadByte();
ScoreName = reader.ReadString16();
}
/// <summary>
/// Sends the specified writer.
/// </summary>
/// <param name="writer"> The writer. </param>
/// <param name="version"> The version. </param>
/// <remarks>
/// </remarks>
protected override void OnSend(BigEndianStream writer, int version)
{
if (writer == null)
throw new ArgumentNullException("writer");
writer.Write(Code);
writer.Write(Position);
writer.Write(ScoreName);
}
}
}
|
Bump assembly version to 2.5.0. | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ForecastPCL")]
[assembly: AssemblyDescription("An unofficial PCL for the forecast.io weather API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Cheng")]
[assembly: AssemblyProduct("ForecastPCL")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.4.0.0")]
[assembly: AssemblyFileVersion("2.4.0.0")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ForecastPCL")]
[assembly: AssemblyDescription("An unofficial PCL for the forecast.io weather API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Cheng")]
[assembly: AssemblyProduct("ForecastPCL")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.5.0.0")]
[assembly: AssemblyFileVersion("2.5.0.0")]
|
Use native pointer for format string | using System;
using System.Runtime.InteropServices;
using Foundation;
// Generated by Objective Sharpie (https://download.xamarin.com/objective-sharpie/ObjectiveSharpie.pkg)
// > sharpie bind -output TestFairy -namespace TestFairyLib -sdk iphoneos10.1 TestFairy.h
namespace TestFairyLib
{
public static class CFunctions
{
// extern void TFLog (NSString *format, ...) __attribute__((format(NSString, 1, 2)));
[DllImport ("__Internal")]
public static extern void TFLog (NSString format, IntPtr varArgs);
// extern void TFLogv (NSString *format, va_list arg_list);
[DllImport ("__Internal")]
public static extern unsafe void TFLogv (NSString format, sbyte* arg_list);
}
}
| using System;
using System.Runtime.InteropServices;
using Foundation;
// Generated by Objective Sharpie (https://download.xamarin.com/objective-sharpie/ObjectiveSharpie.pkg)
// > sharpie bind -output TestFairy -namespace TestFairyLib -sdk iphoneos10.1 TestFairy.h
namespace TestFairyLib
{
public static class CFunctions
{
// extern void TFLog (NSString *format, ...) __attribute__((format(NSString, 1, 2)));
[DllImport ("__Internal")]
public static extern void TFLog (IntPtr format, string arg0);
// extern void TFLogv (NSString *format, va_list arg_list);
[DllImport ("__Internal")]
public static extern unsafe void TFLogv (IntPtr format, sbyte* arg_list);
}
}
|
Fix issue with long data string (e.g. base64) | using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace PinSharp.Http
{
internal class FormUrlEncodedContent : ByteArrayContent
{
private static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding("ISO-8859-1");
public FormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
: base(GetContentByteArray(nameValueCollection))
{
Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}
private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
{
if (nameValueCollection == null) throw new ArgumentNullException(nameof(nameValueCollection));
var stringBuilder = new StringBuilder();
foreach (var keyValuePair in nameValueCollection)
{
if (stringBuilder.Length > 0)
stringBuilder.Append('&');
stringBuilder.Append(Encode(keyValuePair.Key));
stringBuilder.Append('=');
stringBuilder.Append(Encode(keyValuePair.Value));
}
return DefaultHttpEncoding.GetBytes(stringBuilder.ToString());
}
private static string Encode(string data)
{
return string.IsNullOrEmpty(data) ? "" : Uri.EscapeDataString(data).Replace("%20", "+");
}
}
}
| using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace PinSharp.Http
{
internal class FormUrlEncodedContent : ByteArrayContent
{
private static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding("ISO-8859-1");
public FormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
: base(GetContentByteArray(nameValueCollection))
{
Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}
private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
{
if (nameValueCollection == null) throw new ArgumentNullException(nameof(nameValueCollection));
var stringBuilder = new StringBuilder();
foreach (var keyValuePair in nameValueCollection)
{
if (stringBuilder.Length > 0)
stringBuilder.Append('&');
stringBuilder.Append(Encode(keyValuePair.Key));
stringBuilder.Append('=');
stringBuilder.Append(Encode(keyValuePair.Value));
}
return DefaultHttpEncoding.GetBytes(stringBuilder.ToString());
}
private static string Encode(string data)
{
if (string.IsNullOrEmpty(data))
return "";
return EscapeLongDataString(data);
}
private static string EscapeLongDataString(string data)
{
// Uri.EscapeDataString() does not support strings longer than this
const int maxLength = 65519;
var sb = new StringBuilder();
var iterationsNeeded = data.Length / maxLength;
for (var i = 0; i <= iterationsNeeded; i++)
{
sb.Append(i < iterationsNeeded
? Uri.EscapeDataString(data.Substring(maxLength * i, maxLength))
: Uri.EscapeDataString(data.Substring(maxLength * i)));
}
return sb.ToString().Replace("%20", "+");
}
}
}
|
Fix test referring to wrong value | using System;
using System.Linq;
using System.Threading.Tasks;
using Bug2211;
using Marten;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Core;
using Xunit;
namespace DocumentDbTests.Bugs
{
public class Bug_2211_select_transform_inner_object: BugIntegrationContext
{
[Fact]
public async Task should_be_able_to_select_nested_objects()
{
using var documentStore = SeparateStore(x =>
{
x.AutoCreateSchemaObjects = AutoCreate.All;
x.Schema.For<TestEntity>();
});
await documentStore.Advanced.Clean.DeleteAllDocumentsAsync();
await using var session = documentStore.OpenSession();
session.Store(new TestEntity { Name = "Test", Inner = new TestDto { Name = "TestDto" } });
await session.SaveChangesAsync();
await using var querySession = documentStore.QuerySession();
var results = await querySession.Query<TestEntity>()
.Select(x => new { Inner = x.Inner })
.ToListAsync();
results.Count.ShouldBe(1);
results[0].Inner.Name.ShouldBe("Test Dto");
}
}
}
namespace Bug2211
{
public class TestEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public TestDto Inner { get; set; }
}
public class TestDto
{
public string Name { get; set; }
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Bug2211;
using Marten;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Core;
using Xunit;
namespace DocumentDbTests.Bugs
{
public class Bug_2211_select_transform_inner_object: BugIntegrationContext
{
[Fact]
public async Task should_be_able_to_select_nested_objects()
{
using var documentStore = SeparateStore(x =>
{
x.AutoCreateSchemaObjects = AutoCreate.All;
x.Schema.For<TestEntity>();
});
await documentStore.Advanced.Clean.DeleteAllDocumentsAsync();
await using var session = documentStore.OpenSession();
var testEntity = new TestEntity { Name = "Test", Inner = new TestDto { Name = "TestDto" } };
session.Store(testEntity);
await session.SaveChangesAsync();
await using var querySession = documentStore.QuerySession();
var results = await querySession.Query<TestEntity>()
.Select(x => new { Inner = x.Inner })
.ToListAsync();
results.Count.ShouldBe(1);
results[0].Inner.Name.ShouldBe(testEntity.Inner.Name);
}
}
}
namespace Bug2211
{
public class TestEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public TestDto Inner { get; set; }
}
public class TestDto
{
public string Name { get; set; }
}
}
|
Change serialize/deserialze abstract class to interface | using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
using UnityEngine;
namespace LiteNetLibHighLevel
{
public class ServerSpawnSceneObjectMessage : LiteNetLibMessageBase
{
public uint objectId;
public Vector3 position;
public override void Deserialize(NetDataReader reader)
{
objectId = reader.GetUInt();
position = new Vector3(reader.GetFloat(), reader.GetFloat(), reader.GetFloat());
}
public override void Serialize(NetDataWriter writer)
{
writer.Put(objectId);
writer.Put(position.x);
writer.Put(position.y);
writer.Put(position.z);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;
using UnityEngine;
namespace LiteNetLibHighLevel
{
public class ServerSpawnSceneObjectMessage : ILiteNetLibMessage
{
public uint objectId;
public Vector3 position;
public void Deserialize(NetDataReader reader)
{
objectId = reader.GetUInt();
position = new Vector3(reader.GetFloat(), reader.GetFloat(), reader.GetFloat());
}
public void Serialize(NetDataWriter writer)
{
writer.Put(objectId);
writer.Put(position.x);
writer.Put(position.y);
writer.Put(position.z);
}
}
}
|
Set correct version number, v0.1.1 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18449
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyVersion("1.0.*")]
[assembly: System.Reflection.AssemblyInformationalVersion("0.1.2")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18449
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyVersion("1.0.*")]
[assembly: System.Reflection.AssemblyInformationalVersion("0.1.1")]
|
Add more features to vector 2 -> vector 3 conversion | using UnityEngine;
namespace Pear.InteractionEngine.Converters
{
/// <summary>
/// Converts a Vector2 to Vector3
/// </summary>
public class Vector2ToVector3 : MonoBehaviour, IPropertyConverter<Vector2, Vector3>
{
public Vector3 Convert(Vector2 convertFrom)
{
return convertFrom;
}
}
}
| using System;
using System.Collections.Generic;
using UnityEngine;
namespace Pear.InteractionEngine.Converters
{
/// <summary>
/// Converts a Vector2 to Vector3
/// </summary>
public class Vector2ToVector3 : MonoBehaviour, IPropertyConverter<Vector2, Vector3>
{
[Tooltip("Where should the X value be set")]
public VectorFields SetXOn = VectorFields.X;
[Tooltip("Multiplied on the X value when it's set")]
public float XMultiplier = 1;
[Tooltip("Where should the Y value be set")]
public VectorFields SetYOn = VectorFields.X;
[Tooltip("Multiplied on the Y value when it's set")]
public float YMultiplier = 1;
public Vector3 Convert(Vector2 convertFrom)
{
float x = 0;
float y = 0;
float z = 0;
Dictionary<VectorFields, Action<float>> setActions = new Dictionary<VectorFields, Action<float>>()
{
{ VectorFields.X, val => x = val },
{ VectorFields.Y, val => y = val },
{ VectorFields.Z, val => z = val },
};
setActions[SetXOn](convertFrom.x * XMultiplier);
setActions[SetYOn](convertFrom.y * YMultiplier);
return new Vector3(x, y, z);
}
}
public enum VectorFields
{
X,
Y,
Z,
}
}
|
Add Employee Standard Hours endpoints | 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("KeyPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("KeyPay")]
[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("93365e33-3b92-4ea6-ab42-ffecbc504138")]
// 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: AssemblyInformationalVersion("1.1.0.13-rc1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 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("KeyPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("KeyPay")]
[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("93365e33-3b92-4ea6-ab42-ffecbc504138")]
// 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: AssemblyInformationalVersion("1.1.0.13")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Add code to allow vendo img to show on Azure | @{
ViewBag.Title = "Home Page";
}
<div class="col-md-5">
<h1>
Vendo 5.0
</h1>
<p class="lead">The Future of Vending Machines</p>
<p class="text-justify">
Vendo 5.0 is among the first digitally integrated vending machines of the 21st century. It's so great, that we skipped the first four versions and
went straight to 5. With Vendo 5.0, you have the ability to access our machines through your smartphone or P.C. Create an account with us and explore
the Vendo lifestyle. You'll have access to each the machines in your area and the ability to control what the machine grabs for you. Whether it's candy,
chips or soda, Vendo 5.0 can satisfy your nourishment. So, sign up today and live life the Vendo way!
</p>
</div>
<img src="~/img/Vendo.png" class="center-block" />
<div class="row">
<div class="col-md-10 col-md-offset-1">
</div>
</div>
</div>
| @{
ViewBag.Title = "Home Page";
}
<div class="col-md-5">
<h1>
Vendo 5.0
</h1>
<p class="lead">The Future of Vending Machines</p>
<p class="text-justify">
Vendo 5.0 is among the first digitally integrated vending machines of the 21st century. It's so great, that we skipped the first four versions and
went straight to 5. With Vendo 5.0, you have the ability to access our machines through your smartphone or P.C. Create an account with us and explore
the Vendo lifestyle. You'll have access to each the machines in your area and the ability to control what the machine grabs for you. Whether it's candy,
chips or soda, Vendo 5.0 can satisfy your nourishment. So, sign up today and live life the Vendo way!
</p>
</div>
<img src="~/img/Vendo.png" class="center-block" />
<img id="vendo" src='<%=ResolveUrl("~/img/Vendo.png") %>' />
<div class="row">
<div class="col-md-10 col-md-offset-1">
</div>
</div>
|
Increase project version number to 0.7.0 | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.6.0.0")]
[assembly: AssemblyFileVersion("0.6.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.7.0.0")]
[assembly: AssemblyFileVersion("0.7.0.0")]
|
Add the ability to have a simple variable declared inline. | using System;
using LinqToTTreeInterfacesLib;
namespace LINQToTTreeLib.Variables
{
/// <summary>
/// A simple variable (like int, etc.).
/// </summary>
public class VarSimple : IVariable
{
public string VariableName { get; private set; }
public string RawValue { get; private set; }
public Type Type { get; private set; }
public VarSimple(System.Type type)
{
if (type == null)
throw new ArgumentNullException("Must have a good type!");
Type = type;
VariableName = type.CreateUniqueVariableName();
RawValue = VariableName;
}
public IValue InitialValue { get; set; }
public bool Declare
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
}
| using System;
using LinqToTTreeInterfacesLib;
namespace LINQToTTreeLib.Variables
{
/// <summary>
/// A simple variable (like int, etc.).
/// </summary>
public class VarSimple : IVariable
{
public string VariableName { get; private set; }
public string RawValue { get; private set; }
public Type Type { get; private set; }
public VarSimple(System.Type type)
{
if (type == null)
throw new ArgumentNullException("Must have a good type!");
Type = type;
VariableName = type.CreateUniqueVariableName();
RawValue = VariableName;
}
public IValue InitialValue { get; set; }
/// <summary>
/// Get/Set if this variable needs to be declared.
/// </summary>
public bool Declare { get; set; }
}
}
|
Use latest compat version in MvcSandbox | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace MvcSandbox
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args)
.Build();
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureLogging(factory =>
{
factory
.AddConsole()
.AddDebug();
})
.UseIISIntegration()
.UseKestrel()
.UseStartup<Startup>();
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace MvcSandbox
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args)
.Build();
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureLogging(factory =>
{
factory
.AddConsole()
.AddDebug();
})
.UseIISIntegration()
.UseKestrel()
.UseStartup<Startup>();
}
}
|
Fix deserialization of scheduled job. | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using NodaTime;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Infrastructure;
namespace Squidex.Domain.Apps.Entities.Contents
{
public sealed class ScheduleJob
{
public Guid Id { get; }
public Status Status { get; }
public RefToken ScheduledBy { get; }
public Instant DueTime { get; }
public ScheduleJob(Guid id, Status status, RefToken by, Instant due)
{
Id = id;
ScheduledBy = by;
Status = status;
DueTime = due;
}
public static ScheduleJob Build(Status status, RefToken by, Instant due)
{
return new ScheduleJob(Guid.NewGuid(), status, by, due);
}
}
}
| // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using NodaTime;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Infrastructure;
namespace Squidex.Domain.Apps.Entities.Contents
{
public sealed class ScheduleJob
{
public Guid Id { get; }
public Status Status { get; }
public RefToken ScheduledBy { get; }
public Instant DueTime { get; }
public ScheduleJob(Guid id, Status status, RefToken scheduledBy, Instant due)
{
Id = id;
ScheduledBy = scheduledBy;
Status = status;
DueTime = due;
}
public static ScheduleJob Build(Status status, RefToken by, Instant due)
{
return new ScheduleJob(Guid.NewGuid(), status, by, due);
}
}
}
|
Add special http method to return unprocessable entities | using System.Linq;
using Diploms.Dto;
using Microsoft.AspNetCore.Mvc;
namespace Diploms.WebUI
{
public static class ControllerExtensions
{
public static OperationResult GetErrors(this Controller controller, object model)
{
var result = new OperationResult();
if (model == null)
{
result.Errors.Add("Ошибка ввода данных");
}
result.Errors.AddRange(controller.ModelState.Values.SelectMany(v => v.Errors
.Where(b => !string.IsNullOrEmpty(b.ErrorMessage))
.Select(b => b.ErrorMessage)));
return result;
}
}
} | using System.Linq;
using Diploms.Dto;
using Microsoft.AspNetCore.Mvc;
namespace Diploms.WebUI
{
public static class ControllerExtensions
{
public static OperationResult GetErrors(this Controller controller, object model)
{
var result = new OperationResult();
if (model == null)
{
result.Errors.Add("Ошибка ввода данных");
}
result.Errors.AddRange(controller.ModelState.Values.SelectMany(v => v.Errors
.Where(b => !string.IsNullOrEmpty(b.ErrorMessage))
.Select(b => b.ErrorMessage)));
return result;
}
public static IActionResult Unprocessable(this Controller controller, object value)
{
return controller.StatusCode(422, value);
}
}
} |
Fix some formatting for Teams | using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HipChatConnect.Controllers.Listeners.Github.Models;
using HipChatConnect.Controllers.Listeners.TeamCity;
namespace HipChatConnect.Controllers.Listeners.Github
{
public class GithubAggregator
{
private IHipChatRoom Room { get; }
public GithubAggregator(IHipChatRoom room)
{
Room = room;
}
public async Task Handle(GithubPushNotification notification)
{
await SendTeamsInformationAsync(notification);
}
private async Task SendTeamsInformationAsync(GithubPushNotification notification)
{
var githubModel = notification.GithubModel;
(var title, var text) = BuildMessage(githubModel);
var cardData = new SuccessfulTeamsActivityCardData
{
Title = title,
Text = text
};
await Room.SendTeamsActivityCardAsync(cardData);
}
private static (string Title, string Text) BuildMessage(GithubModel model)
{
var branch = model.Ref.Replace("refs/heads/", "");
var authorNames = model.Commits.Select(c => c.Author.Name).Distinct();
var title = $"**{string.Join(", ", authorNames)}** committed on [{branch}]({model.Repository.HtmlUrl + "/tree/" + branch})";
var stringBuilder = new StringBuilder();
foreach (var commit in model.Commits)
{
stringBuilder.Append($@"* {commit.Message} [{commit.Id.Substring(0, 11)}]({commit.Url})");
}
return (title, stringBuilder.ToString());
}
}
} | using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HipChatConnect.Controllers.Listeners.Github.Models;
using HipChatConnect.Controllers.Listeners.TeamCity;
namespace HipChatConnect.Controllers.Listeners.Github
{
public class GithubAggregator
{
private IHipChatRoom Room { get; }
public GithubAggregator(IHipChatRoom room)
{
Room = room;
}
public async Task Handle(GithubPushNotification notification)
{
await SendTeamsInformationAsync(notification);
}
private async Task SendTeamsInformationAsync(GithubPushNotification notification)
{
var githubModel = notification.GithubModel;
(var title, var text) = BuildMessage(githubModel);
var cardData = new SuccessfulTeamsActivityCardData
{
Title = title,
Text = text
};
await Room.SendTeamsActivityCardAsync(cardData);
}
private static (string Title, string Text) BuildMessage(GithubModel model)
{
var branch = model.Ref.Replace("refs/heads/", "");
var authorNames = model.Commits.Select(c => c.Author.Name).Distinct().ToList();
var title = $"{string.Join(", ", authorNames)} committed on {branch}";
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine(
$"**{string.Join(", ", authorNames)}** committed on [{branch}]({model.Repository.HtmlUrl + "/tree/" + branch})");
foreach (var commit in model.Commits)
{
stringBuilder.AppendLine($@"* {commit.Message} [{commit.Id.Substring(0, 11)}]({commit.Url})");
stringBuilder.AppendLine();
}
return (title, stringBuilder.ToString());
}
}
} |
Add Layer to scene. Currently breaking on asset load | using System.Reflection;
using Microsoft.Xna.Framework;
using CocosDenshion;
using CocosSharp;
namespace Chess_Demo
{
class AppDelegate : CCApplicationDelegate
{
static CCWindow sharedWindow;
public static CCWindow SharedWindow
{
get { return sharedWindow; }
}
public static CCSize DefaultResolution;
public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow)
{
application.ContentRootDirectory = "assets";
sharedWindow = mainWindow;
DefaultResolution = new CCSize(
application.MainWindow.WindowSizeInPixels.Width,
application.MainWindow.WindowSizeInPixels.Height);
CCScene scene = new CCScene(sharedWindow);
sharedWindow.RunWithScene(scene);
}
public override void ApplicationDidEnterBackground(CCApplication application)
{
application.Paused = true;
}
public override void ApplicationWillEnterForeground(CCApplication application)
{
application.Paused = false;
}
}
}
| using System.Reflection;
using Microsoft.Xna.Framework;
using CocosDenshion;
using CocosSharp;
namespace Chess_Demo
{
class AppDelegate : CCApplicationDelegate
{
static CCWindow sharedWindow;
public static CCWindow SharedWindow
{
get { return sharedWindow; }
}
public static CCSize DefaultResolution;
public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow)
{
application.ContentRootDirectory = "assets";
sharedWindow = mainWindow;
DefaultResolution = new CCSize(
application.MainWindow.WindowSizeInPixels.Width,
application.MainWindow.WindowSizeInPixels.Height);
CCScene scene = new CCScene(sharedWindow);
scene.AddChild(new ChessLayer());
sharedWindow.RunWithScene(scene);
}
public override void ApplicationDidEnterBackground(CCApplication application)
{
application.Paused = true;
}
public override void ApplicationWillEnterForeground(CCApplication application)
{
application.Paused = false;
}
}
}
|
Add random position of card | using System;
using System.Collections.Generic;
using System.Linq;
namespace MemoryGames
{
public class CardRandomPosition
{
private List<CardFace> gameCard = new List<CardFace>();
private string[] cardName = new string[8];//here will be the name of the card
private Random randomGenerator = new Random();
public static void FillMatrix()
{
}
internal static CardFace[,] GetRandomCardFace()
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace MemoryGames
{
public class CardRandomPosition
{
public static CardFace[,] GetRandomCardFace(int dimentionZero, int dimentionOne)
{
const int pair = 2;
const int pairCount = 9;
CardFace[,] cardFace = new CardFace[dimentionZero, dimentionOne];
Random randomGenerator = new Random();
List<CardFace> gameCard = new List<CardFace>();
int allCard = dimentionZero * dimentionOne;
int currentGameCardPair = allCard / pair;
string[] cardName = new string[pairCount] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
for (int element = 0, j = 0; element < allCard; element++, j++)
{
if (j == currentGameCardPair)
{
j = 0;
}
gameCard.Add(new CardFace(cardName[j]));
}
for (int row = 0; row < dimentionZero; row++)
{
for (int col = 0; col < dimentionOne; col++)
{
int randomElement = randomGenerator.Next(0, gameCard.Count);
cardFace[row, col] = gameCard[randomElement];
gameCard.RemoveAt(randomElement);
}
}
return cardFace;
}
}
}
|
Test needs to be public | /* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using Microsoft.NodejsTools.Analysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AnalysisTests {
[TestClass]
internal class SerializedAnalysisTests : AnalysisTests {
internal override ModuleAnalysis ProcessText(string text) {
return SerializationTests.RoundTrip(ProcessOneText(text));
}
}
}
| /* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using Microsoft.NodejsTools.Analysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AnalysisTests {
[TestClass]
public class SerializedAnalysisTests : AnalysisTests {
internal override ModuleAnalysis ProcessText(string text) {
return SerializationTests.RoundTrip(ProcessOneText(text));
}
}
}
|
Allow filtering weapons by unit | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers.API
{
public class WeaponsController : ApiController
{
public WeaponsController(Database db) : base(db)
{
// Nothing to do here
}
[HttpGet]
public async Task<IEnumerable<dynamic>> Get()
{
// GET: api/weapons
return
await db
.Weapons
.Select(_ => new
{
_.Id,
_.OpticSerial,
_.OpticType,
_.Serial,
_.StockNumber,
_.Type,
_.UnitId
})
.ToListAsync();
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Weapon weapon)
{
await db.Weapons.AddAsync(weapon);
await db.SaveChangesAsync();
return Ok();
}
[HttpDelete]
public async Task<IActionResult> Delete(int id)
{
var weapon = await db.Weapons.FindAsync(id);
db.Weapons.Remove(weapon);
await db.SaveChangesAsync();
return Ok();
}
}
} | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers.API
{
public class WeaponsController : ApiController
{
public WeaponsController(Database db) : base(db)
{
// Nothing to do here
}
[HttpGet]
public async Task<IActionResult> Get(int? unit)
{
// GET: api/weapons
return Ok(
await db
.Weapons
.Where(weapon => !unit.HasValue || weapon.UnitId == unit)
.Select(_ => new
{
_.Id,
_.OpticSerial,
_.OpticType,
_.Serial,
_.StockNumber,
_.Type,
_.UnitId
})
.ToListAsync());
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Weapon weapon)
{
await db.Weapons.AddAsync(weapon);
await db.SaveChangesAsync();
return Ok();
}
[HttpDelete]
public async Task<IActionResult> Delete(int id)
{
var weapon = await db.Weapons.FindAsync(id);
db.Weapons.Remove(weapon);
await db.SaveChangesAsync();
return Ok();
}
}
} |
Check configuration values are set in tests | using System.Threading.Tasks;
using Auth0.AuthenticationApi;
using Auth0.AuthenticationApi.Models;
using Microsoft.Extensions.Configuration;
namespace Auth0.Tests.Shared
{
public class TestBase
{
private readonly IConfigurationRoot _config;
public TestBase()
{
_config = new ConfigurationBuilder()
.AddJsonFile("client-secrets.json", true)
.AddEnvironmentVariables()
.Build();
}
protected async Task<string> GenerateManagementApiToken()
{
var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));
// Get the access token
var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest
{
ClientId = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID"),
ClientSecret = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_SECRET"),
Audience = GetVariable("AUTH0_MANAGEMENT_API_AUDIENCE")
});
return token.AccessToken;
}
protected string GetVariable(string variableName)
{
return _config[variableName];
}
}
} | using System;
using System.Threading.Tasks;
using Auth0.AuthenticationApi;
using Auth0.AuthenticationApi.Models;
using Microsoft.Extensions.Configuration;
namespace Auth0.Tests.Shared
{
public class TestBase
{
private readonly IConfigurationRoot _config;
public TestBase()
{
_config = new ConfigurationBuilder()
.AddJsonFile("client-secrets.json", true)
.AddEnvironmentVariables()
.Build();
}
protected async Task<string> GenerateManagementApiToken()
{
var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));
// Get the access token
var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest
{
ClientId = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_ID"),
ClientSecret = GetVariable("AUTH0_MANAGEMENT_API_CLIENT_SECRET"),
Audience = GetVariable("AUTH0_MANAGEMENT_API_AUDIENCE")
});
return token.AccessToken;
}
protected string GetVariable(string variableName)
{
var value = _config[variableName];
if (String.IsNullOrEmpty(value))
throw new ArgumentOutOfRangeException($"Configuration value '{variableName}' has not been set.");
return value;
}
}
} |
Comment out the resource not found fix for .NET Core | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Quartz Software SRL">
// Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
// Implements the program class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ConfigurationConsole
{
using System.Runtime.Loader;
using System.Threading.Tasks;
using StartupConsole.Application;
class Program
{
public static async Task Main(string[] args)
{
AssemblyLoadContext.Default.Resolving += (context, name) =>
{
if (name.Name.EndsWith(".resources"))
{
return null;
}
return null;
};
await new ConsoleShell().BootstrapAsync(args);
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Quartz Software SRL">
// Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
// Implements the program class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ConfigurationConsole
{
using System.Runtime.Loader;
using System.Threading.Tasks;
using StartupConsole.Application;
class Program
{
public static async Task Main(string[] args)
{
//AssemblyLoadContext.Default.Resolving += (context, name) =>
// {
// if (name.Name.EndsWith(".resources"))
// {
// return null;
// }
// return null;
// };
await new ConsoleShell().BootstrapAsync(args);
}
}
}
|
Fix issue where ratio was always returning "1" | using System;
namespace Satrabel.OpenContent.Components.TemplateHelpers
{
public class Ratio
{
private readonly float _ratio;
public int Width { get; private set; }
public int Height { get; private set; }
public float AsFloat
{
get { return (float)Width / (float)Height); }
}
public Ratio(string ratioString)
{
Width = 1;
Height = 1;
var elements = ratioString.ToLowerInvariant().Split('x');
if (elements.Length == 2)
{
int leftPart;
int rightPart;
if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
{
Width = leftPart;
Height = rightPart;
}
}
_ratio = AsFloat;
}
public Ratio(int width, int height)
{
if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
Width = width;
Height = height;
_ratio = AsFloat;
}
public void SetWidth(int newWidth)
{
Width = newWidth;
Height = Convert.ToInt32(newWidth / _ratio);
}
public void SetHeight(int newHeight)
{
Width = Convert.ToInt32(newHeight * _ratio);
Height = newHeight;
}
}
} | using System;
namespace Satrabel.OpenContent.Components.TemplateHelpers
{
public class Ratio
{
private readonly float _ratio;
public int Width { get; private set; }
public int Height { get; private set; }
public float AsFloat
{
get { return (float)Width / (float)Height; }
}
public Ratio(string ratioString)
{
Width = 1;
Height = 1;
var elements = ratioString.ToLowerInvariant().Split('x');
if (elements.Length == 2)
{
int leftPart;
int rightPart;
if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
{
Width = leftPart;
Height = rightPart;
}
}
_ratio = AsFloat;
}
public Ratio(int width, int height)
{
if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
Width = width;
Height = height;
_ratio = AsFloat;
}
public void SetWidth(int newWidth)
{
Width = newWidth;
Height = Convert.ToInt32(newWidth / _ratio);
}
public void SetHeight(int newHeight)
{
Width = Convert.ToInt32(newHeight * _ratio);
Height = newHeight;
}
}
} |
Enable sliding expiration by default as that is what the Tea Commerce cache does | using System;
using TeaCommerce.Api.Dependency;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;
using Umbraco.Core.Cache;
namespace TeaCommerce.Umbraco.Application.Caching
{
[SuppressDependency("TeaCommerce.Api.Infrastructure.Caching.ICacheService", "TeaCommerce.Api")]
public class UmbracoRuntimeCacheService : ICacheService
{
private IRuntimeCacheProvider _runtimeCache;
public UmbracoRuntimeCacheService()
: this(ApplicationContext.Current.ApplicationCache.RuntimeCache)
{ }
public UmbracoRuntimeCacheService(IRuntimeCacheProvider runtimeCache)
{
_runtimeCache = runtimeCache;
}
public T GetCacheValue<T>(string cacheKey) where T : class
{
return (T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}");
}
public void Invalidate(string cacheKey)
{
_runtimeCache.ClearCacheItem($"TeaCommerce_{cacheKey}");
}
public void SetCacheValue(string cacheKey, object cacheValue)
{
_runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue);
}
public void SetCacheValue(string cacheKey, object cacheValue, TimeSpan cacheDuration)
{
_runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue, cacheDuration);
}
}
} | using System;
using TeaCommerce.Api.Dependency;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;
using Umbraco.Core.Cache;
namespace TeaCommerce.Umbraco.Application.Caching
{
[SuppressDependency("TeaCommerce.Api.Infrastructure.Caching.ICacheService", "TeaCommerce.Api")]
public class UmbracoRuntimeCacheService : ICacheService
{
private IRuntimeCacheProvider _runtimeCache;
public UmbracoRuntimeCacheService()
: this(ApplicationContext.Current.ApplicationCache.RuntimeCache)
{ }
public UmbracoRuntimeCacheService(IRuntimeCacheProvider runtimeCache)
{
_runtimeCache = runtimeCache;
}
public T GetCacheValue<T>(string cacheKey) where T : class
{
return (T)_runtimeCache.GetCacheItem($"TeaCommerce_{cacheKey}");
}
public void Invalidate(string cacheKey)
{
_runtimeCache.ClearCacheItem($"TeaCommerce_{cacheKey}");
}
public void SetCacheValue(string cacheKey, object cacheValue)
{
_runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue);
}
public void SetCacheValue(string cacheKey, object cacheValue, TimeSpan cacheDuration)
{
_runtimeCache.InsertCacheItem($"TeaCommerce_{cacheKey}", () => cacheValue, cacheDuration, true);
}
}
} |
Fix a missing semicolon in an example | public class StudentControllerTests
{
[SetUp]
public void Setup()
{
_fixture = new DatabaseFixture();
_controller = new StudentController(new StudentRepository(_fixture.Context));
}
[Test]
public void IndexAction_ShowsAllStudentsOrderedByName()
{
var expectedStudents = new List<Student>
{
new Student("Joe", "Bloggs"),
new Student("Jane", "Smith")
};
expectedStudents.ForEach(_fixture.SeedContext.Students.Add)
_fixture.SeedContext.SaveChanges();
List<StudentViewModel> viewModel;
_controller.Index()
.ShouldRenderDefaultView()
.WithModel<List<StudentViewModel>>(vm => viewModel = vm);
viewModel.Select(s => s.Name).ShouldBe(
_existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName))
}
private StudentController _controller;
private DatabaseFixture _fixture;
} | public class StudentControllerTests
{
[SetUp]
public void Setup()
{
_fixture = new DatabaseFixture();
_controller = new StudentController(new StudentRepository(_fixture.Context));
}
[Test]
public void IndexAction_ShowsAllStudentsOrderedByName()
{
var expectedStudents = new List<Student>
{
new Student("Joe", "Bloggs"),
new Student("Jane", "Smith")
};
expectedStudents.ForEach(_fixture.SeedContext.Students.Add)
_fixture.SeedContext.SaveChanges();
List<StudentViewModel> viewModel;
_controller.Index()
.ShouldRenderDefaultView()
.WithModel<List<StudentViewModel>>(vm => viewModel = vm);
viewModel.Select(s => s.Name).ShouldBe(
_existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName));
}
private StudentController _controller;
private DatabaseFixture _fixture;
} |
Fix erroneous removal of code | using UnityEditor;
using UnityEngine;
namespace GoogleMobileAds.Editor
{
[InitializeOnLoad]
[CustomEditor(typeof(GoogleMobileAdsSettings))]
public class GoogleMobileAdsSettingsEditor : UnityEditor.Editor
{
[MenuItem("Assets/Google Mobile Ads/Settings...")]
public static void OpenInspector()
{
Selection.activeObject = GoogleMobileAdsSettings.Instance;
if (GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit) {
EditorGUILayout.HelpBox(
"Delays app measurement until you explicitly initialize the Mobile Ads SDK or load an ad.",
MessageType.Info);
}
EditorGUI.indentLevel--;
EditorGUILayout.Separator();
if (GUI.changed)
{
OnSettingsChanged();
}
}
private void OnSettingsChanged()
{
EditorUtility.SetDirty((GoogleMobileAdsSettings) target);
GoogleMobileAdsSettings.Instance.WriteSettingsToFile();
}
}
}
| using UnityEditor;
using UnityEngine;
namespace GoogleMobileAds.Editor
{
[InitializeOnLoad]
[CustomEditor(typeof(GoogleMobileAdsSettings))]
public class GoogleMobileAdsSettingsEditor : UnityEditor.Editor
{
[MenuItem("Assets/Google Mobile Ads/Settings...")]
public static void OpenInspector()
{
Selection.activeObject = GoogleMobileAdsSettings.Instance;
}
public override void OnInspectorGUI()
{
EditorGUILayout.LabelField("Google Mobile Ads App ID", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
GoogleMobileAdsSettings.Instance.GoogleMobileAdsAndroidAppId =
EditorGUILayout.TextField("Android",
GoogleMobileAdsSettings.Instance.GoogleMobileAdsAndroidAppId);
GoogleMobileAdsSettings.Instance.GoogleMobileAdsIOSAppId =
EditorGUILayout.TextField("iOS",
GoogleMobileAdsSettings.Instance.GoogleMobileAdsIOSAppId);
EditorGUILayout.HelpBox(
"Google Mobile Ads App ID will look similar to this sample ID: ca-app-pub-3940256099942544~3347511713",
MessageType.Info);
EditorGUI.indentLevel--;
EditorGUILayout.Separator();
EditorGUILayout.LabelField("AdMob-specific settings", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit =
EditorGUILayout.Toggle(new GUIContent("Delay app measurement"),
GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit);
if (GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit) {
EditorGUILayout.HelpBox(
"Delays app measurement until you explicitly initialize the Mobile Ads SDK or load an ad.",
MessageType.Info);
}
EditorGUI.indentLevel--;
EditorGUILayout.Separator();
if (GUI.changed)
{
OnSettingsChanged();
}
}
private void OnSettingsChanged()
{
EditorUtility.SetDirty((GoogleMobileAdsSettings) target);
GoogleMobileAdsSettings.Instance.WriteSettingsToFile();
}
}
}
|
Add more string extension methods for common operations | using System.Collections.Generic;
using System.Text;
namespace Novell.Directory.Ldap
{
internal static partial class ExtensionMethods
{
/// <summary>
/// Is the given collection null, or Empty (0 elements)?
/// </summary>
internal static bool IsEmpty<T>(this IReadOnlyCollection<T> coll) => coll == null || coll.Count == 0;
/// <summary>
/// Is the given collection not null, and has at least 1 element?
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="coll"></param>
/// <returns></returns>
internal static bool IsNotEmpty<T>(this IReadOnlyCollection<T> coll) => !IsEmpty(coll);
/// <summary>
/// Shortcut for Encoding.UTF8.GetBytes
/// </summary>
internal static byte[] ToUtf8Bytes(this string input) => Encoding.UTF8.GetBytes(input);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Novell.Directory.Ldap
{
internal static partial class ExtensionMethods
{
/// <summary>
/// Shortcut for <see cref="string.IsNullOrEmpty"/>
/// </summary>
internal static bool IsEmpty(this string input) => string.IsNullOrEmpty(input);
/// <summary>
/// Shortcut for negative <see cref="string.IsNullOrEmpty"/>
/// </summary>
internal static bool IsNotEmpty(this string input) => !IsEmpty(input);
/// <summary>
/// Is the given collection null, or Empty (0 elements)?
/// </summary>
internal static bool IsEmpty<T>(this IReadOnlyCollection<T> coll) => coll == null || coll.Count == 0;
/// <summary>
/// Is the given collection not null, and has at least 1 element?
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="coll"></param>
/// <returns></returns>
internal static bool IsNotEmpty<T>(this IReadOnlyCollection<T> coll) => !IsEmpty(coll);
/// <summary>
/// Shortcut for <see cref="UTF8Encoding.GetBytes"/>
/// </summary>
internal static byte[] ToUtf8Bytes(this string input) => Encoding.UTF8.GetBytes(input);
/// <summary>
/// Shortcut for <see cref="UTF8Encoding.GetString"/>
/// Will return an empty string if <paramref name="input"/> is null or empty.
/// </summary>
internal static string FromUtf8Bytes(this byte[] input)
=> input.IsNotEmpty() ? Encoding.UTF8.GetString(input) : string.Empty;
/// <summary>
/// Compare two strings using <see cref="StringComparison.Ordinal"/>
/// </summary>
internal static bool EqualsOrdinal(this string input, string other) => string.Equals(input, other, StringComparison.Ordinal);
/// <summary>
/// Compare two strings using <see cref="StringComparison.OrdinalIgnoreCase"/>
/// </summary>
internal static bool EqualsOrdinalCI(this string input, string other) => string.Equals(input, other, StringComparison.OrdinalIgnoreCase);
}
}
|
Update todo sample for latest metadata changes | // TodoItem.cs
//
using System;
using System.Runtime.CompilerServices;
namespace Todo {
[Imported]
[IgnoreNamespace]
[ScriptName("Object")]
internal sealed class TodoItem {
public bool Completed;
[ScriptName("id")]
public string ID;
public string Title;
}
}
| // TodoItem.cs
//
using System;
using System.Runtime.CompilerServices;
namespace Todo {
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptName("Object")]
internal sealed class TodoItem {
public bool Completed;
[ScriptName("id")]
public string ID;
public string Title;
}
}
|
Use a more compatible method call | using System.Collections.Generic;
using BugsnagUnity.Payload;
using UnityEngine;
namespace BugsnagUnity
{
static class DictionaryExtensions
{
internal static void PopulateDictionaryFromAndroidData(this IDictionary<string, object> dictionary, AndroidJavaObject source)
{
using (var set = source.Call<AndroidJavaObject>("entrySet"))
using (var iterator = set.Call<AndroidJavaObject>("iterator"))
{
while (iterator.Call<bool>("hasNext"))
{
using (var mapEntry = iterator.Call<AndroidJavaObject>("next"))
{
var key = mapEntry.Call<string>("getKey");
using (var value = mapEntry.Call<AndroidJavaObject>("getValue"))
{
if (value != null)
{
using (var @class = value.Call<AndroidJavaObject>("getClass"))
{
if (@class.Call<bool>("isArray"))
{
using (var arrays = new AndroidJavaClass("java.util.Arrays"))
{
dictionary.AddToPayload(key, arrays.CallStatic<string>("toString", value));
}
}
else
{
dictionary.AddToPayload(key, value.Call<string>("toString"));
}
}
}
}
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using BugsnagUnity.Payload;
using UnityEngine;
namespace BugsnagUnity
{
static class DictionaryExtensions
{
private static IntPtr Arrays { get; } = AndroidJNI.FindClass("java/util/Arrays");
private static IntPtr ToStringMethod { get; } = AndroidJNIHelper.GetMethodID(Arrays, "toString", "([Ljava/lang/Object;)Ljava/lang/String;", true);
internal static void PopulateDictionaryFromAndroidData(this IDictionary<string, object> dictionary, AndroidJavaObject source)
{
using (var set = source.Call<AndroidJavaObject>("entrySet"))
using (var iterator = set.Call<AndroidJavaObject>("iterator"))
{
while (iterator.Call<bool>("hasNext"))
{
using (var mapEntry = iterator.Call<AndroidJavaObject>("next"))
{
var key = mapEntry.Call<string>("getKey");
using (var value = mapEntry.Call<AndroidJavaObject>("getValue"))
{
if (value != null)
{
using (var @class = value.Call<AndroidJavaObject>("getClass"))
{
if (@class.Call<bool>("isArray"))
{
var args = AndroidJNIHelper.CreateJNIArgArray(new[] {value});
var formattedValue = AndroidJNI.CallStaticStringMethod(Arrays, ToStringMethod, args);
dictionary.AddToPayload(key, formattedValue);
}
else
{
dictionary.AddToPayload(key, value.Call<string>("toString"));
}
}
}
}
}
}
}
}
}
}
|
Add properties to patch creator button | namespace SIM.Tool.Windows.MainWindowComponents
{
using System;
using System.IO;
using System.Windows;
using Sitecore.Diagnostics.Base;
using JetBrains.Annotations;
using SIM.Core;
using SIM.Instances;
using SIM.Tool.Base;
using SIM.Tool.Base.Plugins;
[UsedImplicitly]
public class CreateSupportPatchButton : IMainWindowButton
{
#region Public methods
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
if (instance == null)
{
WindowHelper.ShowMessage("Choose an instance first");
return;
}
var product = instance.Product;
Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first.");
var version = product.Version + "." + product.Update;
var args = new[]
{
version,
instance.Name,
instance.WebRootPath
};
var dir = Environment.ExpandEnvironmentVariables("%APPDATA%\\Sitecore\\PatchCreator");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllLines(Path.Combine(dir, "args.txt"), args);
CoreApp.RunApp("iexplore", $"http://dl.sitecore.net/updater/pc/PatchCreator.application");
}
#endregion
}
}
| namespace SIM.Tool.Windows.MainWindowComponents
{
using System;
using System.IO;
using System.Windows;
using Sitecore.Diagnostics.Base;
using JetBrains.Annotations;
using SIM.Core;
using SIM.Instances;
using SIM.Tool.Base;
using SIM.Tool.Base.Plugins;
[UsedImplicitly]
public class CreateSupportPatchButton : IMainWindowButton
{
#region Public methods
private string AppArgsFilePath { get; }
private string AppUrl { get; }
public CreateSupportPatchButton(string appArgsFilePath, string appUrl)
{
AppArgsFilePath = appArgsFilePath;
AppUrl = appUrl;
}
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
if (instance == null)
{
WindowHelper.ShowMessage("Choose an instance first");
return;
}
var product = instance.Product;
Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first.");
var version = product.Version + "." + product.Update;
var args = new[]
{
version,
instance.Name,
instance.WebRootPath
};
var dir = Environment.ExpandEnvironmentVariables(AppArgsFilePath);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllLines(Path.Combine(dir, "args.txt"), args);
CoreApp.RunApp("iexplore", AppUrl);
}
#endregion
}
}
|
Fix result checker if no subscriber errors in response | using System;
using System.Linq;
using ExactTarget.TriggeredEmail.ExactTargetApi;
namespace ExactTarget.TriggeredEmail.Core
{
public class ExactTargetResultChecker
{
public static void CheckResult(Result result)
{
if (result == null)
{
throw new Exception("Received an unexpected null result from ExactTarget");
}
if (result.StatusCode.Equals("OK", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
var triggeredResult = result as TriggeredSendCreateResult;
var subscriberFailures = triggeredResult == null
? Enumerable.Empty<string>()
: triggeredResult.SubscriberFailures.Select(f => " ErrorCode:" + f.ErrorCode + " ErrorDescription:" + f.ErrorDescription);
throw new Exception(string.Format("ExactTarget response indicates failure. StatusCode:{0} StatusMessage:{1} SubscriberFailures:{2}",
result.StatusCode,
result.StatusMessage,
string.Join("|", subscriberFailures)));
}
}
} | using System;
using System.Linq;
using ExactTarget.TriggeredEmail.ExactTargetApi;
namespace ExactTarget.TriggeredEmail.Core
{
public class ExactTargetResultChecker
{
public static void CheckResult(Result result)
{
if (result == null)
{
throw new Exception("Received an unexpected null result from ExactTarget");
}
if (result.StatusCode.Equals("OK", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
var triggeredResult = result as TriggeredSendCreateResult;
var subscriberFailures = triggeredResult == null || triggeredResult.SubscriberFailures == null
? Enumerable.Empty<string>()
: triggeredResult.SubscriberFailures.Select(f => " ErrorCode:" + f.ErrorCode + " ErrorDescription:" + f.ErrorDescription);
throw new Exception(string.Format("ExactTarget response indicates failure. StatusCode:{0} StatusMessage:{1} SubscriberFailures:{2}",
result.StatusCode,
result.StatusMessage,
string.Join("|", subscriberFailures)));
}
}
} |
Modify the migration so it rebuilds the table. | namespace EfMigrationsBug.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ChangePkType : DbMigration
{
public override void Up()
{
DropPrimaryKey("dbo.Foos");
AlterColumn("dbo.Foos", "ID", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.Foos", "ID");
}
public override void Down()
{
DropPrimaryKey("dbo.Foos");
AlterColumn("dbo.Foos", "ID", c => c.String(nullable: false, maxLength: 5));
AddPrimaryKey("dbo.Foos", "ID");
}
}
}
| namespace EfMigrationsBug.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ChangePkType : DbMigration
{
public override void Up()
{
DropTable("dbo.Foos");
CreateTable(
"dbo.Foos",
c => new
{
ID = c.Int(nullable: false, identity: true),
})
.PrimaryKey(t => t.ID);
}
public override void Down()
{
DropTable("dbo.Foos");
CreateTable(
"dbo.Foos",
c => new
{
ID = c.String(nullable: false, maxLength: 5),
})
.PrimaryKey(t => t.ID);
}
}
}
|
Add constructor that creates memory stream internally | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Aurio.Streams {
public class MemoryWriterStream : MemorySourceStream, IAudioWriterStream {
public MemoryWriterStream(MemoryStream target, AudioProperties properties) :
base(target, properties) {
}
public void Write(byte[] buffer, int offset, int count) {
// Default stream checks according to MSDN
if(buffer == null) {
throw new ArgumentNullException("buffer must not be null");
}
if(!source.CanWrite) {
throw new NotSupportedException("target stream is not writable");
}
if(buffer.Length - offset < count) {
throw new ArgumentException("not enough remaining bytes or count too large");
}
if(offset < 0 || count < 0) {
throw new ArgumentOutOfRangeException("offset and count must not be negative");
}
// Check block alignment
if(count % SampleBlockSize != 0) {
throw new ArgumentException("count must be a multiple of the sample block size");
}
source.Write(buffer, offset, count);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Aurio.Streams {
public class MemoryWriterStream : MemorySourceStream, IAudioWriterStream {
public MemoryWriterStream(MemoryStream target, AudioProperties properties) :
base(target, properties) {
}
public MemoryWriterStream(AudioProperties properties) :
base(new MemoryStream(), properties) {
}
public void Write(byte[] buffer, int offset, int count) {
// Default stream checks according to MSDN
if(buffer == null) {
throw new ArgumentNullException("buffer must not be null");
}
if(!source.CanWrite) {
throw new NotSupportedException("target stream is not writable");
}
if(buffer.Length - offset < count) {
throw new ArgumentException("not enough remaining bytes or count too large");
}
if(offset < 0 || count < 0) {
throw new ArgumentOutOfRangeException("offset and count must not be negative");
}
// Check block alignment
if(count % SampleBlockSize != 0) {
throw new ArgumentException("count must be a multiple of the sample block size");
}
source.Write(buffer, offset, count);
}
}
}
|
Update type extension for net40 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="TypeExtensions.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides extension methods for types.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot
{
using System;
using System.Linq;
using System.Reflection;
/// <summary>
/// Provides extension methods for types.
/// </summary>
public static class TypeExtensions
{
/// <summary>
/// Retrieves an object that represents a specified property.
/// </summary>
/// <param name="type">The type that contains the property.</param>
/// <param name="name">The name of the property.</param>
/// <returns>An object that represents the specified property, or null if the property is not found.</returns>
public static PropertyInfo GetRuntimeProperty(this Type type, string name)
{
#if NET40
var source = type.GetProperties();
#else
var typeInfo = type.GetTypeInfo();
var source = typeInfo.AsType().GetRuntimeProperties();
#endif
foreach (var x in source)
{
if (x.Name == name) return x;
}
return null;
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="TypeExtensions.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides extension methods for types.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot
{
using System;
using System.Linq;
using System.Reflection;
/// <summary>
/// Provides extension methods for types.
/// </summary>
public static class TypeExtensions
{
/// <summary>
/// Retrieves an object that represents a specified property.
/// </summary>
/// <param name="type">The type that contains the property.</param>
/// <param name="name">The name of the property.</param>
/// <returns>An object that represents the specified property, or null if the property is not found.</returns>
public static PropertyInfo GetRuntimeProperty(this Type type, string name)
{
#if NET40
var source = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
#else
var typeInfo = type.GetTypeInfo();
var source = typeInfo.AsType().GetRuntimeProperties();
#endif
foreach (var x in source)
{
if (x.Name == name) return x;
}
return null;
}
}
}
|
Use SdlClipboard on Linux when using new SDL2 backend | // 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.Platform.Linux.Native;
using osu.Framework.Platform.Linux.Sdl;
using osuTK;
namespace osu.Framework.Platform.Linux
{
public class LinuxGameHost : DesktopGameHost
{
internal LinuxGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default, bool portableInstallation = false, bool useSdl = false)
: base(gameName, bindIPC, toolkitOptions, portableInstallation, useSdl)
{
}
protected override void SetupForRun()
{
base.SetupForRun();
// required for the time being to address libbass_fx.so load failures (see https://github.com/ppy/osu/issues/2852)
Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL);
}
protected override IWindow CreateWindow() =>
!UseSdl ? (IWindow)new LinuxGameWindow() : new Window();
protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this);
public override Clipboard GetClipboard()
{
if (((LinuxGameWindow)Window).IsSdl)
{
return new SdlClipboard();
}
else
{
return new LinuxClipboard();
}
}
}
}
| // 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.Platform.Linux.Native;
using osu.Framework.Platform.Linux.Sdl;
using osuTK;
namespace osu.Framework.Platform.Linux
{
public class LinuxGameHost : DesktopGameHost
{
internal LinuxGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default, bool portableInstallation = false, bool useSdl = false)
: base(gameName, bindIPC, toolkitOptions, portableInstallation, useSdl)
{
}
protected override void SetupForRun()
{
base.SetupForRun();
// required for the time being to address libbass_fx.so load failures (see https://github.com/ppy/osu/issues/2852)
Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL);
}
protected override IWindow CreateWindow() =>
!UseSdl ? (IWindow)new LinuxGameWindow() : new Window();
protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this);
public override Clipboard GetClipboard() =>
Window is Window || (Window as LinuxGameWindow)?.IsSdl == true ? (Clipboard)new SdlClipboard() : new LinuxClipboard();
}
}
|
Change quarter type to enum to allow for "ot" as value. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace mdryden.cflapi.v1.Models.Games
{
public class LineScore
{
[JsonProperty(PropertyName = "quarter")]
public int Quarter { get; set; }
[JsonProperty(PropertyName = "score")]
public int Score { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace mdryden.cflapi.v1.Models.Games
{
public class LineScore
{
[JsonProperty(PropertyName = "quarter")]
public Quarters Quarter { get; set; }
[JsonProperty(PropertyName = "score")]
public int Score { get; set; }
}
}
|
Make GetValue method handle value types | using System.Linq;
using EPiServer.Core;
namespace Meridium.EPiServer.Migration.Support {
public class SourcePage {
public string TypeName { get; set; }
public PropertyDataCollection Properties { get; set; }
public TValue GetValue<TValue>(string propertyName, TValue @default = default(TValue)) where TValue : class {
var data = Properties != null ? Properties.Get(propertyName) : null;
return (data != null) ? (data.Value as TValue) : @default;
}
public TValue GetValueWithFallback<TValue>(params string[] properties) where TValue : class {
var property = properties.SkipWhile(p => !Properties.HasValue(p)).FirstOrDefault();
return (property != null) ? GetValue<TValue>(property) : null;
}
}
internal static class PropertyDataExtensions {
public static bool HasValue(this PropertyDataCollection self, string key) {
var property = self.Get(key);
if (property == null) return false;
return !(property.IsNull || string.IsNullOrWhiteSpace(property.ToString()));
}
}
} | using System.Linq;
using EPiServer.Core;
namespace Meridium.EPiServer.Migration.Support {
public class SourcePage {
public string TypeName { get; set; }
public PropertyDataCollection Properties { get; set; }
public TValue GetValue<TValue>(string propertyName, TValue @default = default(TValue)) {
var data = Properties != null ? Properties.Get(propertyName) : null;
if (data != null && data.Value is TValue)
return (TValue) data.Value;
return @default;
}
public TValue GetValueWithFallback<TValue>(params string[] properties) {
var property = properties.SkipWhile(p => !Properties.HasValue(p)).FirstOrDefault();
return (property != null) ? GetValue<TValue>(property) : default(TValue);
}
}
internal static class PropertyDataExtensions {
public static bool HasValue(this PropertyDataCollection self, string key) {
var property = self.Get(key);
if (property == null) return false;
return !(property.IsNull || string.IsNullOrWhiteSpace(property.ToString()));
}
}
} |
Remove usage of parallelism when compiling templates (causing crash in Jurassic?). | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace Templar
{
public class TemplateSource : IContentSource
{
private readonly string global;
private readonly Compiler compiler;
private readonly TemplateFinder finder;
public TemplateSource(string global, Compiler compiler, TemplateFinder finder)
{
this.global = global;
this.compiler = compiler;
this.finder = finder;
}
public string GetContent(HttpContextBase httpContext)
{
var templates = finder.Find(httpContext);
using (var writer = new StringWriter())
{
writer.WriteLine("!function() {");
writer.WriteLine(" var templates = {0}.templates = {{}};", global);
var results = Compile(templates);
foreach (var result in results)
{
writer.WriteLine(result);
}
writer.WriteLine("}();");
return writer.ToString();
}
}
private IEnumerable<string> Compile(IEnumerable<Template> templates)
{
return templates.AsParallel().Select(template =>
{
string name = template.GetName();
string content = compiler.Compile(template.GetContent());
return string.Format(" templates['{0}'] = {1};", name, content);
});
}
}
} | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace Templar
{
public class TemplateSource : IContentSource
{
private readonly string global;
private readonly Compiler compiler;
private readonly TemplateFinder finder;
public TemplateSource(string global, Compiler compiler, TemplateFinder finder)
{
this.global = global;
this.compiler = compiler;
this.finder = finder;
}
public string GetContent(HttpContextBase httpContext)
{
var templates = finder.Find(httpContext);
using (var writer = new StringWriter())
{
writer.WriteLine("!function() {");
writer.WriteLine(" var templates = {0}.templates = {{}};", global);
var results = Compile(templates);
foreach (var result in results)
{
writer.WriteLine(result);
}
writer.WriteLine("}();");
return writer.ToString();
}
}
private IEnumerable<string> Compile(IEnumerable<Template> templates)
{
return templates.Select(template =>
{
string name = template.GetName();
string content = compiler.Compile(template.GetContent());
return string.Format(" templates['{0}'] = {1};", name, content);
});
}
}
} |
Handle optionargumentpairs with only option | namespace Moya.Runner.Console
{
public struct OptionArgumentPair
{
public string Option { get; set; }
public string Argument { get; set; }
public static OptionArgumentPair Create(string stringFromCommandLine)
{
string[] optionAndArgument = stringFromCommandLine.Split('=');
return new OptionArgumentPair
{
Option = optionAndArgument[0],
Argument = optionAndArgument[1]
};
}
}
} | namespace Moya.Runner.Console
{
using System.Linq;
public struct OptionArgumentPair
{
public string Option { get; set; }
public string Argument { get; set; }
public static OptionArgumentPair Create(string stringFromCommandLine)
{
string[] optionAndArgument = stringFromCommandLine.Split('=');
return new OptionArgumentPair
{
Option = optionAndArgument.Any() ? optionAndArgument[0] : string.Empty,
Argument = optionAndArgument.Count() > 1 ? optionAndArgument[1] : string.Empty
};
}
}
} |
Add missing states and xmldoc for all states' purposes | // 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.Online.RealtimeMultiplayer
{
public enum MultiplayerUserState
{
Idle,
Ready,
WaitingForLoad,
Loaded,
Playing,
Results,
}
}
| // 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.Online.RealtimeMultiplayer
{
public enum MultiplayerUserState
{
/// <summary>
/// The user is idle and waiting for something to happen (or watching the match but not participating).
/// </summary>
Idle,
/// <summary>
/// The user has marked themselves as ready to participate and should be considered for the next game start.
/// </summary>
Ready,
/// <summary>
/// The server is waiting for this user to finish loading. This is a reserved state, and is set by the server.
/// </summary>
/// <remarks>
/// All users in <see cref="Ready"/> state when the game start will be transitioned to this state.
/// All users in this state need to transition to <see cref="Loaded"/> before the game can start.
/// </remarks>
WaitingForLoad,
/// <summary>
/// The user's client has marked itself as loaded and ready to begin gameplay.
/// </summary>
Loaded,
/// <summary>
/// The user is currently playing in a game. This is a reserved state, and is set by the server.
/// </summary>
/// <remarks>
/// Once there are no remaining <see cref="WaitingForLoad"/> users, all users in <see cref="Loaded"/> state will be transitioned to this state.
/// At this point the game will start for all users.
/// </remarks>
Playing,
/// <summary>
/// The user has finished playing and is ready to view results.
/// </summary>
/// <remarks>
/// Once all users transition from <see cref="Playing"/> to this state, the game will end and results will be distributed.
/// All users will be transitioned to the <see cref="Results"/> state.
/// </remarks>
FinishedPlay,
/// <summary>
/// The user is currently viewing results. This is a reserved state, and is set by the server.
/// </summary>
Results,
}
}
|
Add required validation for rich text components on server side | using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
namespace CollAction.ValidationAttributes
{
public class RichTextRequiredAttribute : ValidationAttribute, IClientModelValidator
{
public void AddValidation(ClientModelValidationContext context)
{
context.Attributes["data-val"] = "true";
context.Attributes["data-val-richtextrequired"] = ErrorMessage ?? $"{context.ModelMetadata.DisplayName} is required";
}
}
} | using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
namespace CollAction.ValidationAttributes
{
public class RichTextRequiredAttribute : RequiredAttribute, IClientModelValidator
{
public void AddValidation(ClientModelValidationContext context)
{
var requiredMessage = ErrorMessage ?? $"{context.ModelMetadata.DisplayName} is required";
context.Attributes["data-val"] = "true";
context.Attributes["data-val-required"] = requiredMessage;
context.Attributes["data-val-richtextrequired"] = requiredMessage;
}
}
} |
Revert "disable automatic migration data loss" | namespace QuizFactory.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
using System.Linq;
using QuizFactory.Data;
internal sealed class Configuration : DbMigrationsConfiguration<QuizFactoryDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(QuizFactoryDbContext context)
{
if (!context.Roles.Any())
{
var seedUsers = new SeedUsers();
seedUsers.Generate(context);
}
var seedData = new SeedData(context);
if (!context.QuizDefinitions.Any())
{
foreach (var item in seedData.Quizzes)
{
context.QuizDefinitions.Add(item);
}
}
if (!context.Categories.Any())
{
foreach (var item in seedData.Categories)
{
context.Categories.Add(item);
}
}
context.SaveChanges();
}
}
} | namespace QuizFactory.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
using System.Linq;
using QuizFactory.Data;
internal sealed class Configuration : DbMigrationsConfiguration<QuizFactoryDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(QuizFactoryDbContext context)
{
if (!context.Roles.Any())
{
var seedUsers = new SeedUsers();
seedUsers.Generate(context);
}
var seedData = new SeedData(context);
if (!context.QuizDefinitions.Any())
{
foreach (var item in seedData.Quizzes)
{
context.QuizDefinitions.Add(item);
}
}
if (!context.Categories.Any())
{
foreach (var item in seedData.Categories)
{
context.Categories.Add(item);
}
}
context.SaveChanges();
}
}
} |
Replace map with manual initialization | using AutoMapper;
using MediatR;
using SupportManager.DAL;
using SupportManager.Web.Infrastructure.CommandProcessing;
namespace SupportManager.Web.Features.User
{
public class CreateCommandHandler : RequestHandler<CreateCommand>
{
private readonly SupportManagerContext db;
public CreateCommandHandler(SupportManagerContext db)
{
this.db = db;
}
protected override void HandleCore(CreateCommand message)
{
var user = Mapper.Map<DAL.User>(message);
db.Users.Add(user);
}
}
} | using SupportManager.DAL;
using SupportManager.Web.Infrastructure.CommandProcessing;
namespace SupportManager.Web.Features.User
{
public class CreateCommandHandler : RequestHandler<CreateCommand>
{
private readonly SupportManagerContext db;
public CreateCommandHandler(SupportManagerContext db)
{
this.db = db;
}
protected override void HandleCore(CreateCommand message)
{
var user = new DAL.User {DisplayName = message.Name, Login = message.Name};
db.Users.Add(user);
}
}
} |
Move from powershell.getchell.org to ngetchell.com | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class NicholasMGetchell : IAmACommunityMember
{
public string FirstName => "Nicholas";
public string LastName => "Getchell";
public string ShortBioOrTagLine => "Analyst";
public string StateOrRegion => "Boston, MA";
public string EmailAddress => "nicholas@getchell.org";
public string TwitterHandle => "getch3028";
public string GravatarHash => "1ebff516aa68c1b3bc786bd291b8fca1";
public string GitHubHandle => "ngetchell";
public GeoPosition Position => new GeoPosition(53.073635, 8.806422);
public Uri WebSite => new Uri("https://powershell.getchell.org");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://powershell.getchell.org/feed/"); } }
public string FeedLanguageCode => "en";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class NicholasMGetchell : IAmACommunityMember
{
public string FirstName => "Nicholas";
public string LastName => "Getchell";
public string ShortBioOrTagLine => "Systems Administrator";
public string StateOrRegion => "Boston, MA";
public string EmailAddress => "nicholas@getchell.org";
public string TwitterHandle => "getch3028";
public string GravatarHash => "1ebff516aa68c1b3bc786bd291b8fca1";
public string GitHubHandle => "ngetchell";
public GeoPosition Position => new GeoPosition(53.073635, 8.806422);
public Uri WebSite => new Uri("https://ngetchell.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ngetchell.com/tag/powershell/rss/"); } }
public string FeedLanguageCode => "en";
}
}
|
Change etag from DateTime to string, to reflect updated api. | using System;
using Newtonsoft.Json;
namespace Storage.Net.Microsoft.Azure.DataLake.Store.Gen2.Models
{
public class DirectoryItem
{
[JsonProperty("contentLength")] public int? ContentLength { get; set; }
[JsonProperty("etag")] public DateTime Etag { get; set; }
[JsonProperty("group")] public string Group { get; set; }
[JsonProperty("isDirectory")] public bool IsDirectory { get; set; }
[JsonProperty("lastModified")] public DateTime LastModified { get; set; }
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("owner")] public string Owner { get; set; }
[JsonProperty("permissions")] public string Permissions { get; set; }
}
} | using System;
using Newtonsoft.Json;
namespace Storage.Net.Microsoft.Azure.DataLake.Store.Gen2.Models
{
public class DirectoryItem
{
[JsonProperty("contentLength")] public int? ContentLength { get; set; }
[JsonProperty("etag")] public string Etag { get; set; }
[JsonProperty("group")] public string Group { get; set; }
[JsonProperty("isDirectory")] public bool IsDirectory { get; set; }
[JsonProperty("lastModified")] public DateTime LastModified { get; set; }
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("owner")] public string Owner { get; set; }
[JsonProperty("permissions")] public string Permissions { get; set; }
}
} |
Use InvariantContains instead of Contains when looking for culture in the querystring | using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
namespace Umbraco.Web.WebApi.Filters
{
/// <summary>
/// Allows an Action to execute with an arbitrary number of QueryStrings
/// </summary>
/// <remarks>
/// Just like you can POST an arbitrary number of parameters to an Action, you can't GET an arbitrary number
/// but this will allow you to do it
/// </remarks>
public sealed class HttpQueryStringModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
//get the query strings from the request properties
if (actionContext.Request.Properties.ContainsKey("MS_QueryNameValuePairs"))
{
if (actionContext.Request.Properties["MS_QueryNameValuePairs"] is IEnumerable<KeyValuePair<string, string>> queryStrings)
{
var queryStringKeys = queryStrings.Select(kvp => kvp.Key).ToArray();
var additionalParameters = new Dictionary<string, string>();
if(queryStringKeys.Contains("culture") == false) {
additionalParameters["culture"] = actionContext.Request.ClientCulture();
}
var formData = new FormDataCollection(queryStrings.Union(additionalParameters));
bindingContext.Model = formData;
return true;
}
}
return false;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using Umbraco.Core;
namespace Umbraco.Web.WebApi.Filters
{
/// <summary>
/// Allows an Action to execute with an arbitrary number of QueryStrings
/// </summary>
/// <remarks>
/// Just like you can POST an arbitrary number of parameters to an Action, you can't GET an arbitrary number
/// but this will allow you to do it
/// </remarks>
public sealed class HttpQueryStringModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
//get the query strings from the request properties
if (actionContext.Request.Properties.ContainsKey("MS_QueryNameValuePairs"))
{
if (actionContext.Request.Properties["MS_QueryNameValuePairs"] is IEnumerable<KeyValuePair<string, string>> queryStrings)
{
var queryStringKeys = queryStrings.Select(kvp => kvp.Key).ToArray();
var additionalParameters = new Dictionary<string, string>();
if(queryStringKeys.InvariantContains("culture") == false) {
additionalParameters["culture"] = actionContext.Request.ClientCulture();
}
var formData = new FormDataCollection(queryStrings.Union(additionalParameters));
bindingContext.Model = formData;
return true;
}
}
return false;
}
}
}
|
Update server side API for single multiple answer question | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
|
Add unit test for AuthSettings class | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Solomobro.Instagram.Tests.WebApi
{
[TestFixture]
public class AuthSettingsTests
{
//WebApiDemo.Settings.EnvironmentManager.
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Solomobro.Instagram.WebApiDemo.Settings;
namespace Solomobro.Instagram.Tests.WebApi
{
[TestFixture]
public class AuthSettingsTests
{
const string Settings = @"#Instagram Settings
InstaWebsiteUrl=https://github.com/solomobro/Instagram
InstaClientId=<CLIENT-ID>
InstaClientSecret=<CLIENT-SECRET>
InstaRedirectUrl=http://localhost:56841/api/authorize";
[Test]
public void AllAuthSettingsPropertiesAreSet()
{
Assert.That(AuthSettings.InstaClientId, Is.Null);
Assert.That(AuthSettings.InstaClientSecret, Is.Null);
Assert.That(AuthSettings.InstaRedirectUrl, Is.Null);
Assert.That(AuthSettings.InstaWebsiteUrl, Is.Null);
using (var memStream = new MemoryStream(Encoding.ASCII.GetBytes(Settings)))
{
AuthSettings.LoadSettings(memStream);
}
Assert.That(AuthSettings.InstaClientId, Is.Not.Null);
Assert.That(AuthSettings.InstaClientSecret, Is.Not.Null);
Assert.That(AuthSettings.InstaRedirectUrl, Is.Not.Null);
Assert.That(AuthSettings.InstaWebsiteUrl, Is.Not.Null);
}
}
}
|
Set default values (to avoid null references for invalid user data) | using System;
namespace MultiMiner.Xgminer
{
//marked Serializable to allow deep cloning of CoinConfiguration
[Serializable]
public class MiningPool
{
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public int Quota { get; set; } //see bfgminer README about quotas
}
}
| using System;
namespace MultiMiner.Xgminer
{
//marked Serializable to allow deep cloning of CoinConfiguration
[Serializable]
public class MiningPool
{
public MiningPool()
{
//set defaults
Host = String.Empty;
Username = String.Empty;
Password = String.Empty;
}
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public int Quota { get; set; } //see bfgminer README about quotas
}
}
|
Fix package id version checking during pack - The logic wasn't in sync with nuget.exe | // 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;
using System.Globalization;
namespace NuGet
{
public static class PackageIdValidator
{
internal const int MaxPackageIdLength = 100;
public static bool IsValidPackageId(string packageId)
{
if (string.IsNullOrWhiteSpace(packageId))
{
throw new ArgumentException(nameof(packageId));
}
// Rules:
// Should start with a character
// Can be followed by '.' or '-'. Cannot have 2 of these special characters consecutively.
// Cannot end with '-' or '.'
var firstChar = packageId[0];
if (!char.IsLetterOrDigit(firstChar) && firstChar != '_')
{
// Should start with a char/digit/_.
return false;
}
var lastChar = packageId[packageId.Length - 1];
if (lastChar == '-' || lastChar == '.')
{
// Should not end with a '-' or '.'.
return false;
}
for (int index = 1; index < packageId.Length - 1; index++)
{
var ch = packageId[index];
if (!char.IsLetterOrDigit(ch) && ch != '-' && ch != '.')
{
return false;
}
if ((ch == '-' || ch == '.') && ch == packageId[index - 1])
{
// Cannot have two successive '-' or '.' in the name.
return false;
}
}
return true;
}
public static void ValidatePackageId(string packageId)
{
if (packageId.Length > MaxPackageIdLength)
{
// TODO: Resources
throw new ArgumentException("NuGetResources.Manifest_IdMaxLengthExceeded");
}
if (!IsValidPackageId(packageId))
{
// TODO: Resources
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "NuGetResources.InvalidPackageId", packageId));
}
}
}
} | // 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;
using System.Globalization;
using System.Text.RegularExpressions;
namespace NuGet
{
public static class PackageIdValidator
{
private static readonly Regex _idRegex = new Regex(@"^\w+([_.-]\w+)*$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
internal const int MaxPackageIdLength = 100;
public static bool IsValidPackageId(string packageId)
{
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
return _idRegex.IsMatch(packageId);
}
public static void ValidatePackageId(string packageId)
{
if (packageId.Length > MaxPackageIdLength)
{
// TODO: Resources
throw new ArgumentException("NuGetResources.Manifest_IdMaxLengthExceeded");
}
if (!IsValidPackageId(packageId))
{
// TODO: Resources
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "NuGetResources.InvalidPackageId", packageId));
}
}
}
} |
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.CommonServiceLocator 3.0.1")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.CommonServiceLocator 3.0.1")]
|
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.2.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.AggregateService 3.0.2")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.2.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.AggregateService 3.0.2")]
|
Add an improved string representation of PackageBuild instances | // <copyright file="PackageBuildList.cs" company="Mark Final">
// Opus
// </copyright>
// <summary>Opus Core</summary>
// <author>Mark Final</author>
namespace Opus.Core
{
public class PackageBuild
{
public PackageBuild(PackageIdentifier id)
{
this.Name = id.Name;
this.Versions = new UniqueList<PackageIdentifier>();
this.Versions.Add(id);
this.SelectedVersion = id;
}
public string Name
{
get;
private set;
}
public UniqueList<PackageIdentifier> Versions
{
get;
private set;
}
public PackageIdentifier SelectedVersion
{
get;
set;
}
}
public class PackageBuildList : UniqueList<PackageBuild>
{
public PackageBuild GetPackage(string name)
{
foreach (PackageBuild i in this)
{
if (i.Name == name)
{
return i;
}
}
return null;
}
}
} | // <copyright file="PackageBuildList.cs" company="Mark Final">
// Opus
// </copyright>
// <summary>Opus Core</summary>
// <author>Mark Final</author>
namespace Opus.Core
{
public class PackageBuild
{
public PackageBuild(PackageIdentifier id)
{
this.Name = id.Name;
this.Versions = new UniqueList<PackageIdentifier>();
this.Versions.Add(id);
this.SelectedVersion = id;
}
public string Name
{
get;
private set;
}
public UniqueList<PackageIdentifier> Versions
{
get;
private set;
}
public PackageIdentifier SelectedVersion
{
get;
set;
}
public override string ToString()
{
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.AppendFormat("{0}: Package '{1}' with {2} versions", base.ToString(), this.Name, this.Versions.Count);
return builder.ToString();
}
}
public class PackageBuildList : UniqueList<PackageBuild>
{
public PackageBuild GetPackage(string name)
{
foreach (PackageBuild i in this)
{
if (i.Name == name)
{
return i;
}
}
return null;
}
}
} |
Fix new warning around nullability | // Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using Newtonsoft.Json;
using System;
using VDrumExplorer.Utility;
namespace VDrumExplorer.Model.Schema.Json
{
internal class HexInt32Converter : JsonConverter<HexInt32>
{
public override void WriteJson(JsonWriter writer, HexInt32 value, JsonSerializer serializer) =>
writer.WriteValue(value.ToString());
public override HexInt32 ReadJson(JsonReader reader, Type objectType, HexInt32 existingValue, bool hasExistingValue, JsonSerializer serializer) =>
HexInt32.Parse(Preconditions.AssertNotNull((string?) reader.Value));
}
}
| // Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using Newtonsoft.Json;
using System;
using VDrumExplorer.Utility;
namespace VDrumExplorer.Model.Schema.Json
{
internal class HexInt32Converter : JsonConverter<HexInt32>
{
public override void WriteJson(JsonWriter writer, HexInt32? value, JsonSerializer serializer) =>
writer.WriteValue(value?.ToString());
public override HexInt32 ReadJson(JsonReader reader, Type objectType, HexInt32? existingValue, bool hasExistingValue, JsonSerializer serializer) =>
HexInt32.Parse(Preconditions.AssertNotNull((string?) reader.Value));
}
}
|
Add TODO for Input Requirement | using HarryPotterUnity.Game;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.Cards.PlayRequirements
{
public class InputRequirement : MonoBehaviour, ICardPlayRequirement
{
private BaseCard _cardInfo;
[SerializeField, UsedImplicitly]
private int _fromHandActionInputRequired;
[SerializeField, UsedImplicitly]
private int _inPlayActionInputRequired;
public int FromHandActionInputRequired { get { return _fromHandActionInputRequired; } }
public int InPlayActionInputRequired { get { return _inPlayActionInputRequired; } }
private void Awake()
{
_cardInfo = GetComponent<BaseCard>();
if (GetComponent<InputGatherer>() == null)
{
gameObject.AddComponent<InputGatherer>();
}
}
public bool MeetsRequirement()
{
return _cardInfo.GetFromHandActionTargets().Count >= _fromHandActionInputRequired;
}
public void OnRequirementMet() { }
}
}
| using HarryPotterUnity.Game;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.Cards.PlayRequirements
{
public class InputRequirement : MonoBehaviour, ICardPlayRequirement
{
private BaseCard _cardInfo;
[SerializeField, UsedImplicitly]
private int _fromHandActionInputRequired;
[SerializeField, UsedImplicitly]
private int _inPlayActionInputRequired;
public int FromHandActionInputRequired { get { return _fromHandActionInputRequired; } }
public int InPlayActionInputRequired { get { return _inPlayActionInputRequired; } }
private void Awake()
{
_cardInfo = GetComponent<BaseCard>();
if (GetComponent<InputGatherer>() == null)
{
gameObject.AddComponent<InputGatherer>();
}
}
public bool MeetsRequirement()
{
//TODO: Need to check whether this needs to check the FromHandActionTargets or the InPlayActionTargets!
return _cardInfo.GetFromHandActionTargets().Count >= _fromHandActionInputRequired;
}
public void OnRequirementMet() { }
}
}
|
Fix a typo in a comment | namespace System
{
/// <summary>
/// Represents a 32-bit integer.
/// </summary>
public struct Int32
{
// Note: integers are equivalent to instances of this data structure because
// flame-llvm the contents of single-field structs as a value of their single
// field, rather than as a LLVM struct. So a 32-bit integer becomes an i32 and
// so does a `System.Int32`. So don't add, remove, or edit the fields in this
// struct.
private int value;
/// <summary>
/// Converts this integer to a string representation.
/// </summary>
/// <returns>The string representation for the integer.</returns>
public string ToString()
{
return Convert.ToString(value);
}
}
} | namespace System
{
/// <summary>
/// Represents a 32-bit integer.
/// </summary>
public struct Int32
{
// Note: integers are equivalent to instances of this data structure because
// flame-llvm stores the contents of single-field structs as a value of their
// field, rather than as a LLVM struct. So a 32-bit integer becomes an i32 and
// so does a `System.Int32`. So don't add, remove, or edit the fields in this
// struct.
private int value;
/// <summary>
/// Converts this integer to a string representation.
/// </summary>
/// <returns>The string representation for the integer.</returns>
public string ToString()
{
return Convert.ToString(value);
}
}
} |
Fix build error with unused variable | using Android.App;
using Android.OS;
using MvvmCross.Droid.Support.V7.AppCompat;
using System;
namespace ExpandableList.Droid.Views
{
[Activity(Label = "DetailsView")]
public class DetailsView : MvxAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
try
{
base.OnCreate(savedInstanceState);
}
catch (Exception ex)
{
}
}
}
} | using Android.App;
using Android.OS;
using MvvmCross.Droid.Support.V7.AppCompat;
using System;
namespace ExpandableList.Droid.Views
{
[Activity(Label = "DetailsView")]
public class DetailsView : MvxAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
}
} |
Fix new test on CI host | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Audio;
using osu.Framework.IO.Stores;
using osu.Framework.Threading;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioComponentTest
{
[Test]
public void TestVirtualTrack()
{
var thread = new AudioThread();
var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.dll"), @"Resources");
var manager = new AudioManager(thread, store, store);
thread.Start();
var track = manager.Tracks.GetVirtual();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(0, track.CurrentTime);
track.Start();
Task.Delay(50);
Assert.Greater(track.CurrentTime, 0);
track.Stop();
Assert.IsFalse(track.IsRunning);
thread.Exit();
Task.Delay(500);
Assert.IsFalse(thread.Exited);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Audio;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Framework.Threading;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class AudioComponentTest
{
[Test]
public void TestVirtualTrack()
{
Architecture.SetIncludePath();
var thread = new AudioThread();
var store = new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.dll"), @"Resources");
var manager = new AudioManager(thread, store, store);
thread.Start();
var track = manager.Tracks.GetVirtual();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(0, track.CurrentTime);
track.Start();
Task.Delay(50);
Assert.Greater(track.CurrentTime, 0);
track.Stop();
Assert.IsFalse(track.IsRunning);
thread.Exit();
Task.Delay(500);
Assert.IsFalse(thread.Exited);
}
}
}
|
Remove old bootstrapper stuff from UI-project. | using System.Windows;
using Arkivverket.Arkade.UI.Views;
using Arkivverket.Arkade.Util;
using Autofac;
using Prism.Autofac;
using Prism.Modularity;
namespace Arkivverket.Arkade.UI
{
public class Bootstrapper : AutofacBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
protected override void ConfigureModuleCatalog()
{
var catalog = (ModuleCatalog) ModuleCatalog;
catalog.AddModule(typeof(ModuleAModule));
}
protected override void ConfigureContainerBuilder(ContainerBuilder builder)
{
base.ConfigureContainerBuilder(builder);
builder.RegisterModule(new ArkadeAutofacModule());
}
}
/* public class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterTypeForNavigation<View000Debug>("View000Debug");
Container.RegisterTypeForNavigation<View100Status>("View100Status");
ILogService logService = new RandomLogService();
Container.RegisterInstance(logService);
}
protected override void ConfigureModuleCatalog()
{
ModuleCatalog catalog = (ModuleCatalog)ModuleCatalog;
catalog.AddModule(typeof(ModuleAModule));
}
}
public static class UnityExtensons
{
public static void RegisterTypeForNavigation<T>(this IUnityContainer container, string name)
{
container.RegisterType(typeof(object), typeof(T), name);
}
}
*/
} | using System.Windows;
using Arkivverket.Arkade.UI.Views;
using Arkivverket.Arkade.Util;
using Autofac;
using Prism.Autofac;
using Prism.Modularity;
namespace Arkivverket.Arkade.UI
{
public class Bootstrapper : AutofacBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
protected override void ConfigureModuleCatalog()
{
var catalog = (ModuleCatalog) ModuleCatalog;
catalog.AddModule(typeof(ModuleAModule));
}
protected override void ConfigureContainerBuilder(ContainerBuilder builder)
{
base.ConfigureContainerBuilder(builder);
builder.RegisterModule(new ArkadeAutofacModule());
}
}
} |
Remove unused method on timeline db | using System;
using System.Collections.Generic;
using System.Linq;
namespace Totem.Runtime.Timeline
{
/// <summary>
/// Describes the database persisting the timeline
/// </summary>
public interface ITimelineDb
{
Many<TimelinePoint> Append(TimelinePosition cause, Many<Event> events);
TimelinePoint AppendOccurred(TimelinePoint scheduledPoint);
void RemoveFromSchedule(TimelinePosition position);
TimelineResumeInfo ReadResumeInfo();
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Totem.Runtime.Timeline
{
/// <summary>
/// Describes the database persisting the timeline
/// </summary>
public interface ITimelineDb
{
Many<TimelinePoint> Append(TimelinePosition cause, Many<Event> events);
TimelinePoint AppendOccurred(TimelinePoint scheduledPoint);
TimelineResumeInfo ReadResumeInfo();
}
} |
Update session only is value is changed | namespace Nancy.Session
{
using System.Collections;
using System.Collections.Generic;
public class Session : ISession
{
private readonly IDictionary<string, object> dictionary;
private bool hasChanged;
public Session() : this(new Dictionary<string, object>(0)){}
public Session(IDictionary<string, object> dictionary)
{
this.dictionary = dictionary;
}
public int Count
{
get { return dictionary.Count; }
}
public void DeleteAll()
{
if (Count > 0) { MarkAsChanged(); }
dictionary.Clear();
}
public void Delete(string key)
{
if (dictionary.Remove(key)) { MarkAsChanged(); }
}
public object this[string key]
{
get { return dictionary.ContainsKey(key) ? dictionary[key] : null; }
set
{
dictionary[key] = value;
MarkAsChanged();
}
}
public bool HasChanged
{
get { return this.hasChanged; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
private void MarkAsChanged()
{
hasChanged = true;
}
}
} | namespace Nancy.Session
{
using System.Collections;
using System.Collections.Generic;
public class Session : ISession
{
private readonly IDictionary<string, object> dictionary;
private bool hasChanged;
public Session() : this(new Dictionary<string, object>(0)){}
public Session(IDictionary<string, object> dictionary)
{
this.dictionary = dictionary;
}
public int Count
{
get { return dictionary.Count; }
}
public void DeleteAll()
{
if (Count > 0) { MarkAsChanged(); }
dictionary.Clear();
}
public void Delete(string key)
{
if (dictionary.Remove(key)) { MarkAsChanged(); }
}
public object this[string key]
{
get { return dictionary.ContainsKey(key) ? dictionary[key] : null; }
set
{
if (this[key] == value) return;
dictionary[key] = value;
MarkAsChanged();
}
}
public bool HasChanged
{
get { return this.hasChanged; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
private void MarkAsChanged()
{
hasChanged = true;
}
}
} |
Fix tournament videos stuttering when changing scenes | // 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.IO;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Video;
using osu.Game.Graphics;
namespace osu.Game.Tournament.Components
{
public class TourneyVideo : CompositeDrawable
{
private readonly VideoSprite video;
public TourneyVideo(Stream stream)
{
if (stream == null)
{
InternalChild = new Box
{
Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.3f), OsuColour.Gray(0.6f)),
RelativeSizeAxes = Axes.Both,
};
}
else
InternalChild = video = new VideoSprite(stream)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
};
}
public bool Loop
{
set
{
if (video != null)
video.Loop = value;
}
}
}
}
| // 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.IO;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Video;
using osu.Framework.Timing;
using osu.Game.Graphics;
namespace osu.Game.Tournament.Components
{
public class TourneyVideo : CompositeDrawable
{
private readonly VideoSprite video;
private ManualClock manualClock;
private IFrameBasedClock sourceClock;
public TourneyVideo(Stream stream)
{
if (stream == null)
{
InternalChild = new Box
{
Colour = ColourInfo.GradientVertical(OsuColour.Gray(0.3f), OsuColour.Gray(0.6f)),
RelativeSizeAxes = Axes.Both,
};
}
else
InternalChild = video = new VideoSprite(stream)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
};
}
public bool Loop
{
set
{
if (video != null)
video.Loop = value;
}
}
protected override void LoadComplete()
{
base.LoadComplete();
sourceClock = Clock;
Clock = new FramedClock(manualClock = new ManualClock());
}
protected override void Update()
{
base.Update();
// we want to avoid seeking as much as possible, because we care about performance, not sync.
// to avoid seeking completely, we only increment out local clock when in an updating state.
manualClock.CurrentTime += sourceClock.ElapsedFrameTime;
}
}
}
|
Fix typo in public variable | using UnityEngine;
public class RoomGenerator : MonoBehaviour
{
public GameObject roomPrefab;
public int roomCount = 100;
public int spaceWidth = 500;
public int spaceLength = 500;
public int minRoomWidth = 5;
public int maxRoomWidth = 20;
public int minRoomLength = 5;
public int maxRoomLength = 20;
public Room[] generatedrRooms;
public void Run()
{
for (int i = 0; i < this.transform.childCount; i++)
{
DestroyImmediate(this.transform.GetChild(i).gameObject);
}
generatedrRooms = new Room[roomCount];
for (int i = 0; i < roomCount; i++)
{
var posX = Random.Range (0, spaceWidth);
var posZ = Random.Range (0, spaceLength);
var sizeX = Random.Range (minRoomWidth, maxRoomWidth);
var sizeZ = Random.Range (minRoomLength, maxRoomLength);
var instance = Instantiate (roomPrefab);
instance.transform.SetParent (this.transform);
instance.transform.localPosition = new Vector3 (posX, 0f, posZ);
instance.transform.localScale = Vector3.one;
var room = instance.GetComponent<Room> ();
room.Init (sizeX, sizeZ);
generatedrRooms [i] = room;
}
}
}
| using UnityEngine;
public class RoomGenerator : MonoBehaviour
{
public GameObject roomPrefab;
public int roomCount = 100;
public int spaceWidth = 500;
public int spaceLength = 500;
public int minRoomWidth = 5;
public int maxRoomWidth = 20;
public int minRoomLength = 5;
public int maxRoomLength = 20;
public Room[] generatedRooms;
public void Run()
{
for (int i = 0; i < generatedRooms.Length; i++)
{
DestroyImmediate(generatedRooms[i].gameObject);
}
generatedRooms = new Room[roomCount];
for (int i = 0; i < roomCount; i++)
{
var posX = Random.Range (0, spaceWidth);
var posZ = Random.Range (0, spaceLength);
var sizeX = Random.Range (minRoomWidth, maxRoomWidth);
var sizeZ = Random.Range (minRoomLength, maxRoomLength);
var instance = Instantiate (roomPrefab);
instance.transform.SetParent (this.transform);
instance.transform.localPosition = new Vector3 (posX, 0f, posZ);
instance.transform.localScale = Vector3.one;
var room = instance.GetComponent<Room> ();
room.Init (sizeX, sizeZ);
generatedRooms [i] = room;
}
}
}
|
Add support for listening on multiple urls. | using System;
using DeployStatus.Configuration;
using DeployStatus.SignalR;
using log4net;
using Microsoft.Owin.Hosting;
namespace DeployStatus.Service
{
public class DeployStatusService : IService
{
private IDisposable webApp;
private readonly ILog log;
private readonly DeployStatusConfiguration deployConfiguration;
public DeployStatusService()
{
log = LogManager.GetLogger(typeof (DeployStatusService));
deployConfiguration = DeployStatusSettingsSection.Settings.AsDeployConfiguration();
}
public void Start()
{
log.Info("Starting api polling service...");
DeployStatusState.Instance.Value.Start(deployConfiguration);
var webAppUrl = deployConfiguration.WebAppUrl;
log.Info($"Starting web app service on {webAppUrl}...");
webApp = WebApp.Start<Startup>(webAppUrl);
log.Info("Started.");
}
public void Stop()
{
webApp.Dispose();
DeployStatusState.Instance.Value.Stop();
}
}
} | using System;
using System.Linq;
using DeployStatus.Configuration;
using DeployStatus.SignalR;
using log4net;
using Microsoft.Owin.Hosting;
namespace DeployStatus.Service
{
public class DeployStatusService : IService
{
private IDisposable webApp;
private readonly ILog log;
private readonly DeployStatusConfiguration deployConfiguration;
public DeployStatusService()
{
log = LogManager.GetLogger(typeof (DeployStatusService));
deployConfiguration = DeployStatusSettingsSection.Settings.AsDeployConfiguration();
}
public void Start()
{
log.Info("Starting api polling service...");
DeployStatusState.Instance.Value.Start(deployConfiguration);
var webAppUrl = deployConfiguration.WebAppUrl;
log.Info($"Starting web app service on {webAppUrl}...");
var startOptions = new StartOptions();
foreach (var url in webAppUrl.Split(','))
{
startOptions.Urls.Add(url);
}
webApp = WebApp.Start<Startup>(startOptions);
log.Info("Started.");
}
public void Stop()
{
webApp.Dispose();
DeployStatusState.Instance.Value.Stop();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.