commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
a757a42217d41fdd9b6fd4cd837a0c07e2cd4c5a | Add new ApiUrlBase to BasketService in Xamarin App | productinfo/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,TypeW/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,TypeW/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers | src/Mobile/eShopOnContainers/eShopOnContainers.Core/Services/Basket/BasketService.cs | src/Mobile/eShopOnContainers/eShopOnContainers.Core/Services/Basket/BasketService.cs | using System;
using System.Threading.Tasks;
using eShopOnContainers.Core.Services.RequestProvider;
using eShopOnContainers.Core.Models.Basket;
using eShopOnContainers.Core.Helpers;
namespace eShopOnContainers.Core.Services.Basket
{
public class BasketService : IBasketService
{
private readonly IRequestProvider _requestProvider;
private const string ApiUrlBase = "api/v1/basket";
public BasketService(IRequestProvider requestProvider)
{
_requestProvider = requestProvider;
}
public async Task<CustomerBasket> GetBasketAsync(string guidUser, string token)
{
var builder = new UriBuilder(GlobalSetting.Instance.BasketEndpoint)
{
Path = $"{ApiUrlBase}/{guidUser}"
};
var uri = builder.ToString();
CustomerBasket basket =
await _requestProvider.GetAsync<CustomerBasket>(uri, token);
ServicesHelper.FixBasketItemPictureUri(basket?.Items);
return basket;
}
public async Task<CustomerBasket> UpdateBasketAsync(CustomerBasket customerBasket, string token)
{
var builder = new UriBuilder(GlobalSetting.Instance.BasketEndpoint)
{
Path = ApiUrlBase
};
var uri = builder.ToString();
var result = await _requestProvider.PostAsync(uri, customerBasket, token);
return result;
}
public async Task CheckoutAsync(BasketCheckout basketCheckout, string token)
{
var builder = new UriBuilder(GlobalSetting.Instance.BasketEndpoint)
{
Path = $"{ApiUrlBase}/checkout"
};
var uri = builder.ToString();
await _requestProvider.PostAsync(uri, basketCheckout, token);
}
public async Task ClearBasketAsync(string guidUser, string token)
{
var builder = new UriBuilder(GlobalSetting.Instance.BasketEndpoint)
{
Path = $"{ApiUrlBase}/{guidUser}"
};
var uri = builder.ToString();
await _requestProvider.DeleteAsync(uri, token);
}
}
} | using System;
using System.Threading.Tasks;
using eShopOnContainers.Core.Services.RequestProvider;
using eShopOnContainers.Core.Models.Basket;
using eShopOnContainers.Core.Helpers;
namespace eShopOnContainers.Core.Services.Basket
{
public class BasketService : IBasketService
{
private readonly IRequestProvider _requestProvider;
public BasketService(IRequestProvider requestProvider)
{
_requestProvider = requestProvider;
}
public async Task<CustomerBasket> GetBasketAsync(string guidUser, string token)
{
UriBuilder builder = new UriBuilder(GlobalSetting.Instance.BasketEndpoint);
builder.Path = guidUser;
string uri = builder.ToString();
CustomerBasket basket =
await _requestProvider.GetAsync<CustomerBasket>(uri, token);
ServicesHelper.FixBasketItemPictureUri(basket?.Items);
return basket;
}
public async Task<CustomerBasket> UpdateBasketAsync(CustomerBasket customerBasket, string token)
{
UriBuilder builder = new UriBuilder(GlobalSetting.Instance.BasketEndpoint);
string uri = builder.ToString();
var result = await _requestProvider.PostAsync(uri, customerBasket, token);
return result;
}
public async Task CheckoutAsync(BasketCheckout basketCheckout, string token)
{
UriBuilder builder = new UriBuilder(GlobalSetting.Instance.BasketEndpoint + "/checkout");
string uri = builder.ToString();
await _requestProvider.PostAsync(uri, basketCheckout, token);
}
public async Task ClearBasketAsync(string guidUser, string token)
{
UriBuilder builder = new UriBuilder(GlobalSetting.Instance.BasketEndpoint);
builder.Path = guidUser;
string uri = builder.ToString();
await _requestProvider.DeleteAsync(uri, token);
}
}
} | mit | C# |
135acbf24e095eada23219ccd545cc3a9f158d1d | fix uri escape and encoding | Poket-Jony/GMusicProxyGui | GMusicProxyGui/WebController.cs | GMusicProxyGui/WebController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Threading;
namespace GMusicProxyGui
{
public class WebController
{
private string url;
public WebController(string url)
{
this.url = url;
}
public string RequestString(string request, Dictionary<string, string> parameters)
{
try
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
return client.DownloadString(Uri.EscapeUriString(url + request + BuildGetUrl(parameters)));
}
catch(Exception e)
{
throw e;
}
}
public async Task RequestFile(string fileName)
{
try
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
await client.DownloadFileTaskAsync(new Uri(Uri.EscapeUriString(url)), fileName);
}
catch (Exception e)
{
throw e;
}
}
public async void RequestFile(string request, Dictionary<string, string> parameters, string fileName)
{
try
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
await client.DownloadFileTaskAsync(new Uri(Uri.EscapeUriString(url + request + BuildGetUrl(parameters))), fileName);
}
catch (Exception e)
{
throw e;
}
}
private string BuildGetUrl(Dictionary<string, string> parameters)
{
string output = "?";
foreach(KeyValuePair<string, string> param in parameters)
{
output += string.Format("{0}={1}&", param.Key, param.Value);
}
output = output.Remove(output.Length - 1);
return output;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Threading;
namespace GMusicProxyGui
{
public class WebController
{
private string url;
public WebController(string url)
{
this.url = url;
}
public string RequestString(string request, Dictionary<string, string> parameters)
{
try
{
WebClient client = new WebClient();
return client.DownloadString(url + request + BuildGetUrl(parameters));
}
catch(Exception e)
{
throw e;
}
}
public async Task RequestFile(string fileName)
{
try
{
WebClient client = new WebClient();
await client.DownloadFileTaskAsync(new Uri(url), fileName);
}
catch (Exception e)
{
throw e;
}
}
public void RequestFile(string request, Dictionary<string, string> parameters, string fileName)
{
try
{
WebClient client = new WebClient();
client.DownloadFileAsync(new Uri(url + request + BuildGetUrl(parameters)), fileName);
}
catch (Exception e)
{
throw e;
}
}
private string BuildGetUrl(Dictionary<string, string> parameters)
{
string output = "?";
foreach(KeyValuePair<string, string> param in parameters)
{
output += string.Format("{0}={1}&", param.Key, param.Value);
}
output = output.Remove(output.Length - 1);
return output;
}
}
}
| mit | C# |
a3d4398c0a7a5f54a6ce2117eef6ad3dc8950d74 | Improve error if github can't be reached. | hschroedl/win-gists | GistClient/Client/GistClient.cs | GistClient/Client/GistClient.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography;
using GistClient.FileSystem;
using RestSharp;
using RestSharp.Deserializers;
namespace GistClient.Client
{
public static class GistClient
{
private static readonly RestClient Client;
static GistClient(){
Client = new RestClient("https://api.github.com");
}
public static Dictionary<String,String> SendRequest(RestRequest request){
var response = Client.Execute(request);
HandleResponse(response);
var jsonResponse = TrySerializeResponse(response);
return jsonResponse;
}
public static void SetAuthentication(String username, String password){
Client.Authenticator = new HttpBasicAuthenticator(username,password.Decrypt());
}
public static void HandleResponse(IRestResponse response){
var statusHeader = response.Headers.FirstOrDefault(x => x.Name == "Status");
if (statusHeader != null){
var statusValue = statusHeader.Value.ToString();
if (!statusValue.Contains("201")){
String message = TrySerializeResponse(response)["message"];
throw new Exception(statusValue + ", " + message);
}
}
else{
throw new Exception("Github could not be reached. Verify your connection.");
}
}
private static Dictionary<string, string> TrySerializeResponse(IRestResponse response)
{
var deserializer = new JsonDeserializer();
var jsonResponse = deserializer.Deserialize<Dictionary<String, String>>(response);
return jsonResponse;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography;
using GistClient.FileSystem;
using RestSharp;
using RestSharp.Deserializers;
namespace GistClient.Client
{
public static class GistClient
{
private static readonly RestClient Client;
static GistClient(){
Client = new RestClient("https://api.github.com");
}
public static Dictionary<String,String> SendRequest(RestRequest request){
var response = Client.Execute(request);
HandleResponse(response);
var jsonResponse = TrySerializeResponse(response);
return jsonResponse;
}
public static void SetAuthentication(String username, String password){
Client.Authenticator = new HttpBasicAuthenticator(username,password.Decrypt());
}
public static void HandleResponse(IRestResponse response){
var statusHeader = response.Headers.FirstOrDefault(x => x.Name == "Status");
var statusValue = statusHeader.Value.ToString();
if (!statusValue.Contains("201")){
String message = TrySerializeResponse(response)["message"];
throw new Exception(statusValue + ", "+message);
}
}
private static Dictionary<string, string> TrySerializeResponse(IRestResponse response)
{
var deserializer = new JsonDeserializer();
var jsonResponse = deserializer.Deserialize<Dictionary<String, String>>(response);
return jsonResponse;
}
}
}
| mit | C# |
6675f5ee2be0ab94d9c1cd77c02ef5563e242bd1 | Support high DPI (96DPI, 120DPI tested) | imknown/KeyFingerprintLooker | KeyFingerprintLooker/Program.cs | KeyFingerprintLooker/Program.cs | /*
* 由SharpDevelop创建。
* 用户: imknown
* 日期: 2015/12/3 周四
* 时间: 上午 11:22
*
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
*/
using System;
using System.Windows.Forms;
namespace KeyFingerprintLooker
{
/// <summary>
/// Class with program entry point.
/// </summary>
internal sealed class Program
{
/// <summary>
/// Program entry point.
/// </summary>
[STAThread]
private static void Main(string[] args)
{
if (Environment.OSVersion.Version.Major >= 6)
{
SetProcessDPIAware();
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();
}
}
| /*
* 由SharpDevelop创建。
* 用户: imknown
* 日期: 2015/12/3 周四
* 时间: 上午 11:22
*
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
*/
using System;
using System.Windows.Forms;
namespace KeyFingerprintLooker
{
/// <summary>
/// Class with program entry point.
/// </summary>
internal sealed class Program
{
/// <summary>
/// Program entry point.
/// </summary>
[STAThread]
private static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| apache-2.0 | C# |
7173b7ea528ec4fe8821bff06cbec403bebb202c | use proper graphic | Syntronian/cbabb,Syntronian/cbabb | source/CBA/Views/Home/Results.cshtml | source/CBA/Views/Home/Results.cshtml | @model CBA.Models.BuyBuddie.Search
@{
ViewBag.Title = "CBA Travel Companion";
}
<header class="bar bar-nav">
@{ Html.BeginForm("Index", "Home", FormMethod.Get); }
<button class="btn btn-link btn-nav pull-left">
<span class="icon icon-left-nav"></span>
</button>
@{ Html.EndForm(); }
<h1 class="title"><img src="@Url.Content("~/assets/img/cba-logo.png")" /></h1>
</header>
<nav class="bar bar-tab">
<a class="tab-item" href="@Url.Action("Index")">
<span class="icon icon-home"></span>
<span class="tab-label">Home</span>
</a>
<a class="tab-item" href="#">
<span class="icon icon-gear"></span>
<span class="tab-label">Settings</span>
</a>
</nav>
<div class="content">
@if (ViewBag.Error != null)
{
<p>ViewBag.Error</p>
}
<div class="content-padded">
<div class="pull-left">
@if (!String.IsNullOrEmpty(Model.ScoreGraphic))
{
<img src="http://buybuddie.com.au/@Model.ScoreGraphic" alt="@Model.RiskScore" />
}
else
{
<img src="http://buybuddie.com.au/Content/bb/img/bb-gray.gif" alt="0" />
}
</div>
<div class="pull-left" style="margin-left: 40px;">
<h2>
Issues
</h2>
@foreach (var issue in Model.Issues)
{
if (!string.IsNullOrEmpty(issue.Message))
{ <p>@Html.Raw(CBA.Helpers.HTML.WithActiveLinks(issue.Message))</p> }
}
<h2 style="margin-top: 40px;">
Solutions
</h2>
@foreach (var issue in Model.Issues)
{
if (!string.IsNullOrEmpty(issue.Solution))
{ <p>@Html.Raw(CBA.Helpers.HTML.WithActiveLinks(issue.Solution))</p> }
}
</div>
</div>
</div>
| @model CBA.Models.BuyBuddie.Search
@{
ViewBag.Title = "CBA Travel Companion";
}
<header class="bar bar-nav">
@{ Html.BeginForm("Index", "Home", FormMethod.Get); }
<button class="btn btn-link btn-nav pull-left">
<span class="icon icon-left-nav"></span>
</button>
@{ Html.EndForm(); }
<h1 class="title"><img src="@Url.Content("~/assets/img/cba-logo.png")" /></h1>
</header>
<nav class="bar bar-tab">
<a class="tab-item" href="@Url.Action("Index")">
<span class="icon icon-home"></span>
<span class="tab-label">Home</span>
</a>
<a class="tab-item" href="#">
<span class="icon icon-gear"></span>
<span class="tab-label">Settings</span>
</a>
</nav>
<div class="content">
@if (ViewBag.Error != null)
{
<p>ViewBag.Error</p>
}
<div class="content-padded">
<div class="pull-left">
<img src="http://buybuddie.com.au/Content/bb/img/bb-gray.gif" alt="0">
</div>
<div class="pull-left" style="margin-left: 40px;">
<h3>
Issues
</h3>
@foreach (var issue in Model.Issues)
{
if (!string.IsNullOrEmpty(issue.Message))
{ <p>@Html.Raw(CBA.Helpers.HTML.WithActiveLinks(issue.Message))</p> }
}
<h3 style="margin-top: 40px;">
Solutions
</h3>
@foreach (var issue in Model.Issues)
{
if (!string.IsNullOrEmpty(issue.Solution))
{ <p>@Html.Raw(CBA.Helpers.HTML.WithActiveLinks(issue.Solution))</p> }
}
</div>
</div>
</div>
| mit | C# |
a9b7b7eb693ff3c8f8a6ff0b29d01dcfd304c7e3 | Test coverage for configured, mapper-wide decimal and double ToString formatting | agileobjects/AgileMapper | AgileMapper.UnitTests/Configuration/WhenConfiguringStringFormatting.cs | AgileMapper.UnitTests/Configuration/WhenConfiguringStringFormatting.cs | namespace AgileObjects.AgileMapper.UnitTests.Configuration
{
using System;
using TestClasses;
using Xunit;
public class WhenConfiguringStringFormatting
{
// See https://github.com/agileobjects/AgileMapper/issues/23
[Fact]
public void ShouldFormatDateTimesMapperWide()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.StringsFrom<DateTime>(c => c.FormatUsing("o"));
var source = new PublicProperty<DateTime> { Value = DateTime.Now };
var result = mapper.Map(source).ToANew<PublicField<string>>();
result.Value.ShouldBe(source.Value.ToString("o"));
}
}
[Fact]
public void ShouldFormatDecimalsMapperWide()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.StringsFrom<decimal>(c => c.FormatUsing("C"));
var source = new PublicProperty<decimal> { Value = 1.99m };
var result = mapper.Map(source).ToANew<PublicField<string>>();
result.Value.ShouldBe(source.Value.ToString("C"));
}
}
[Fact]
public void ShouldFormatDoublesMapperWideUsingDecimalPlaces()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.StringsFrom<double>(c => c.FormatUsing("0.00"));
var source = new PublicProperty<double> { Value = 1 };
var result = mapper.Map(source).ToANew<PublicField<string>>();
result.Value.ShouldBe("1.00");
}
}
}
}
| namespace AgileObjects.AgileMapper.UnitTests.Configuration
{
using System;
using TestClasses;
using Xunit;
public class WhenConfiguringStringFormatting
{
// See https://github.com/agileobjects/AgileMapper/issues/23
[Fact]
public void ShouldFormatDateTimesGlobally()
{
using (var mapper = Mapper.CreateNew())
{
mapper.WhenMapping
.StringsFrom<DateTime>(c => c.FormatUsing("o"));
var source = new PublicProperty<DateTime> { Value = DateTime.Now };
var result = mapper.Map(source).ToANew<PublicField<string>>();
result.Value.ShouldBe(source.Value.ToString("o"));
}
}
}
}
| mit | C# |
d3fcc0d112b3d5e0629462aecbf4d6a224877bfa | Update EquipmentItemModel.cs | NinjaVault/NinjaHive,NinjaVault/NinjaHive | NinjaHive.Contract/Models/EquipmentItemModel.cs | NinjaHive.Contract/Models/EquipmentItemModel.cs | using NinjaHive.Components.Enums;
namespace NinjaHive.Contract.Models
{
public class EquipmentItemModel: GameItemModel
{
public EquipmentItemModel()
{
this.Durability = 0;
this.BodySlot = BodySlot.Head;
this.NumberOfSlots = 1;
}
public int Durability { get; set; }
public BodySlot VodySlot { get; set; }
public int NumberOfSlots {get; set;}
}
}
| using NinjaHive.Components.Enums;
namespace NinjaHive.Contract.Models
{
public class EquipmentItemModel: GameItemModel
{
public EquipmentitemModel()
{
this.Durability = 0;
this.Slot = BodySlot.Head;
}
public int Durability { get; set; }
public BodySlot Slot { get; set; }
}
}
| apache-2.0 | C# |
10c5331987d5031aa57c171bfb28bd235fd17472 | fix build | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Shell/Commands/ToolCommands.cs | WalletWasabi.Gui/Shell/Commands/ToolCommands.cs | using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Diagnostics;
using AvalonStudio.Commands;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Gui.Tabs;
using WalletWasabi.Gui.Tabs.WalletManager;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class ToolCommands
{
public Global Global { get; }
[ImportingConstructor]
public ToolCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = global.Global;
var walletManagerCommand = ReactiveCommand.Create(OnWalletManager);
var settingsCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new SettingsViewModel(Global)));
var transactionBroadcasterCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new TransactionBroadcasterViewModel(Global)));
#if DEBUG
var devToolsCommand = ReactiveCommand.Create(() =>
{
DevToolsExtensions.OpenDevTools((Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow);
});
#endif
Observable
.Merge(walletManagerCommand.ThrownExceptions)
.Merge(settingsCommand.ThrownExceptions)
#if DEBUG
.Merge(devToolsCommand.ThrownExceptions)
#endif
.Subscribe(OnException);
WalletManagerCommand = new CommandDefinition(
"Wallet Manager",
commandIconService.GetCompletionKindImage("WalletManager"),
walletManagerCommand);
SettingsCommand = new CommandDefinition(
"Settings",
commandIconService.GetCompletionKindImage("Settings"),
settingsCommand);
TransactionBroadcasterCommand = new CommandDefinition(
"Broadcast Transaction",
commandIconService.GetCompletionKindImage("BroadcastTransaction"),
transactionBroadcasterCommand);
#if DEBUG
DevToolsCommand = new CommandDefinition(
"Dev Tools",
commandIconService.GetCompletionKindImage("DevTools"),
devToolsCommand);
#endif
}
private void OnWalletManager()
{
var walletManagerViewModel = IoC.Get<IShell>().GetOrCreate<WalletManagerViewModel>();
if (Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any())
{
walletManagerViewModel.SelectLoadWallet();
}
else
{
walletManagerViewModel.SelectGenerateWallet();
}
}
private void OnException(Exception ex)
{
Logger.LogError(ex);
}
[ExportCommandDefinition("Tools.WalletManager")]
public CommandDefinition WalletManagerCommand { get; }
[ExportCommandDefinition("Tools.Settings")]
public CommandDefinition SettingsCommand { get; }
[ExportCommandDefinition("Tools.BroadcastTransaction")]
public CommandDefinition TransactionBroadcasterCommand { get; }
#if DEBUG
[ExportCommandDefinition("Tools.DevTools")]
public CommandDefinition DevToolsCommand { get; }
#endif
}
}
| using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Diagnostics;
using AvalonStudio.Commands;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using WalletWasabi.Gui.Controls.WalletExplorer;
using WalletWasabi.Gui.Tabs;
using WalletWasabi.Gui.Tabs.WalletManager;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class ToolCommands
{
public Global Global { get; }
[ImportingConstructor]
public ToolCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = global.Global;
var walletManagerCommand = ReactiveCommand.Create(OnWalletManager);
var settingsCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new SettingsViewModel(Global)));
var transactionBroadcasterCommand = ReactiveCommand.Create(() => IoC.Get<IShell>().AddOrSelectDocument(() => new TransactionBroadcasterViewModel(Global)));
#if DEBUG
var devToolsCommand = ReactiveCommand.Create(() =>
{
DevToolsExtensions.OpenDevTools((Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow);
});
#endif
Observable
.Merge(walletManagerCommand.ThrownExceptions)
.Merge(settingsCommand.ThrownExceptions)
#if DEBUG
.Merge(devToolsCommand.ThrownExceptions)
#endif
.Subscribe(OnException);
WalletManagerCommand = new CommandDefinition(
"Wallet Manager",
commandIconService.GetCompletionKindImage("WalletManager"),
walletManagerCommand);
SettingsCommand = new CommandDefinition(
"Settings",
commandIconService.GetCompletionKindImage("Settings"),
settingsCommand);
TransactionBroadcasterCommand = new CommandDefinition(
"Broadcast Transaction",
commandIconService.GetCompletionKindImage("BroadcastTransaction"),
transationBroadcasterCommand);
#if DEBUG
DevToolsCommand = new CommandDefinition(
"Dev Tools",
commandIconService.GetCompletionKindImage("DevTools"),
devToolsCommand);
#endif
}
private void OnWalletManager()
{
var walletManagerViewModel = IoC.Get<IShell>().GetOrCreate<WalletManagerViewModel>();
if (Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any())
{
walletManagerViewModel.SelectLoadWallet();
}
else
{
walletManagerViewModel.SelectGenerateWallet();
}
}
private void OnException(Exception ex)
{
Logger.LogError(ex);
}
[ExportCommandDefinition("Tools.WalletManager")]
public CommandDefinition WalletManagerCommand { get; }
[ExportCommandDefinition("Tools.Settings")]
public CommandDefinition SettingsCommand { get; }
[ExportCommandDefinition("Tools.BroadcastTransaction")]
public CommandDefinition TransactionBroadcasterCommand { get; }
#if DEBUG
[ExportCommandDefinition("Tools.DevTools")]
public CommandDefinition DevToolsCommand { get; }
#endif
}
}
| mit | C# |
60f0af2a0aa6626e6d179123a81e5eb0727e45ba | Refactor Add | mtsuker/GitTest1 | ConsoleApp1/ConsoleApp1/Feature1.cs | ConsoleApp1/ConsoleApp1/Feature1.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Feature1
{
public int Add(int x1, int x2)
{
return x1 + x2;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Feature1
{
public int Add()
{
int x1 = 1;
int x2 = 2;
int sum = x1 + x2;
return sum;
}
}
}
| mit | C# |
9785a8e6478b59f25de7cea74117b79fc23d5f86 | Add RadiatingLight to Server IgnoredComponents (#1636) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14 | Content.Server/IgnoredComponents.cs | Content.Server/IgnoredComponents.cs | namespace Content.Server
{
public static class IgnoredComponents
{
public static string[] List => new [] {
"ConstructionGhost",
"IconSmooth",
"SubFloorHide",
"LowWall",
"ReinforcedWall",
"Window",
"CharacterInfo",
"InteractionOutline",
"MeleeWeaponArcAnimation",
"AnimationsTest",
"ItemStatus",
"Marker",
"EmergencyLight",
"Clickable",
"CanSeeGases",
"RadiatingLight",
};
}
}
| namespace Content.Server
{
public static class IgnoredComponents
{
public static string[] List => new [] {
"ConstructionGhost",
"IconSmooth",
"SubFloorHide",
"LowWall",
"ReinforcedWall",
"Window",
"CharacterInfo",
"InteractionOutline",
"MeleeWeaponArcAnimation",
"AnimationsTest",
"ItemStatus",
"Marker",
"EmergencyLight",
"Clickable",
"CanSeeGases",
};
}
}
| mit | C# |
470e16ba2f8f25933ac5be9ba2800edf237b7cb3 | Update Test.cs | MicBrain/seatest,MicBrain/seatest,MicBrain/seatest,MicBrain/seatest | runners/windows/SeaTest/SeaTest/Test.cs | runners/windows/SeaTest/SeaTest/Test.cs | using System;
using System.Collections.ObjectModel;
namespace SeaTest
{
public class Test : Observable
{
public string Name { get; set; }
public ObservableCollection<TestResult> Results { get; set; }
private bool _hasRun;
public bool HasRun
{
get { return _hasRun; }
set { _hasRun = value; OnPropertyChanged("HasRun");}
}
private bool _passed = false;
public bool Passed
{
get { return _passed; }
set { _passed = value; OnPropertyChanged("Passed");}
}
public Fixture Fixture { get; set; }
}
}
| using System;
using System.Collections.ObjectModel;
namespace SeaTest
{
public class Test : Observable
{
public string Name { get; set; }
public ObservableCollection<TestResult> Results { get; set; }
private bool _hasRun;
public bool HasRun
{
get { return _hasRun; }
set { _hasRun = value; OnPropertyChanged("HasRun");}
}
private bool _passed = false;
public bool Passed
{
get { return _passed; }
set { _passed = value; OnPropertyChanged("Passed");}
}
public Fixture Fixture { get; set; }
}
} | mit | C# |
855109b04d00959c82288695e89b6f9151726bb7 | Adjust line endings. | RagingRudolf/CodeFirst.UCommerce | source/Core/Attributes/DataType/DataTypeAttribute.cs | source/Core/Attributes/DataType/DataTypeAttribute.cs | using System;
using RagingRudolf.UCommerce.CodeFirst.Core.Attributes.Shared;
namespace RagingRudolf.UCommerce.CodeFirst.Core.Attributes.DataType
{
[AttributeUsage(AttributeTargets.Class)]
public class DataTypeAttribute : DefinitionAttribute
{
public DataTypeAttribute(string name, string definitionName)
: base(BuiltInDefinitionType.DataType, name, string.Empty)
{
DefinitionName = definitionName;
}
public string DefinitionName { get; private set; }
public bool Nullable { get; set; }
public string ValidationExpression { get; set; }
}
} | using System;
using RagingRudolf.UCommerce.CodeFirst.Core.Attributes.Shared;
namespace RagingRudolf.UCommerce.CodeFirst.Core.Attributes.DataType
{
[AttributeUsage(AttributeTargets.Class)]
public class DataTypeAttribute : DefinitionAttribute
{
public DataTypeAttribute(string name, string definitionName)
: base(BuiltInDefinitionType.DataType, name, string.Empty)
{
DefinitionName = definitionName;
}
public string DefinitionName { get; private set; }
public bool Nullable { get; set; }
public string ValidationExpression { get; set; }
}
} | mit | C# |
39008261458d57d2949bb791c286de151cba216d | allow only authorized access to values resources | aoancea/practice-web-api-security,aoancea/practice-web-api-security,aoancea/practice-web-api-security | src/Api/Controllers/ValuesController.cs | src/Api/Controllers/ValuesController.cs | using System.Threading.Tasks;
using System.Web.Http;
namespace Phobos.Api.Controllers
{
[Authorize]
public class ValuesController : ApiController
{
[ActionName("Get")]
public async Task<string[]> GetAsync()
{
return await Task.FromResult(new string[5] { "string1", "string2", "string3", "string4", "string5" });
}
}
} | using System.Threading.Tasks;
using System.Web.Http;
namespace Phobos.Api.Controllers
{
public class ValuesController : ApiController
{
[ActionName("Get")]
public async Task<string[]> GetAsync()
{
return await Task.FromResult(new string[5] { "string1", "string2", "string3", "string4", "string5" });
}
}
} | mit | C# |
f7d6405d7dbd4b69e9d59e18220b9f3b366b1eac | Update User.cs | VeloMafia/VeloEventsManager | src/VeloEventsManager.Models/User.cs | src/VeloEventsManager.Models/User.cs | namespace VeloEventsManager.Models
{
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
// You can add User data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class User : IdentityUser
{
private ICollection<Event> events;
public User()
{
this.events = new HashSet<Event>();
this.Languages = new List<string>();
this.Skills = new List<string>();
}
public int BikeId { get; set; }
public virtual Bike Bike { get; set; }
public string Mobile { get; set; }
public double EnduranceIndex { get; set; }
public IEnumerable<string> Languages { get; set; }
public IEnumerable<string> Skills { get; set; }
public virtual ICollection<Event> Events
{
get { return this.events; }
set { this.events = value; }
}
public ClaimsIdentity GenerateUserIdentity(UserManager<User> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
}
}
| namespace VeloEventsManager.Models
{
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
// You can add User data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class User : IdentityUser
{
private ICollection<Event> events;
public User()
{
this.events = new HashSet<Event>();
}
public int BikeId { get; set; }
public virtual Bike Bike { get; set; }
public string Mobile { get; set; }
public double EnduranceIndex { get; set; }
public IEnumerable<string> Languages { get; set; }
public IEnumerable<string> Skills { get; set; }
public virtual ICollection<Event> Events
{
get { return this.events; }
set { this.events = value; }
}
public ClaimsIdentity GenerateUserIdentity(UserManager<User> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
}
}
| mit | C# |
d227e91c02038899cf54526d6b69667ac689be7f | Fix stylecop issues in debugging project | AArnott/pinvoke,vbfox/pinvoke | src/CodeGeneration.Debugging/Program.cs | src/CodeGeneration.Debugging/Program.cs | // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace CodeGeneration.Debugging
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
internal class Program
{
private static void Main(string[] args)
{
// This app is a dummy. But when it is debugged within VS, it builds the Tests
// allowing VS to debug into the build/code generation process.
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeGeneration.Debugging
{
class Program
{
static void Main(string[] args)
{
// This app is a dummy. But when it is debugged within VS, it builds the Tests
// allowing VS to debug into the build/code generation process.
}
}
}
| mit | C# |
498f0107812026214c525778cef3b13bad1ebd18 | Update VerificationLogSection | atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata | src/Atata/Logging/Sections/VerificationLogSection.cs | src/Atata/Logging/Sections/VerificationLogSection.cs | using System.Text;
namespace Atata
{
public class VerificationLogSection : UIComponentLogSection
{
public VerificationLogSection(UIComponent component, string verificationConstraint)
: this(component, null, verificationConstraint)
{
}
public VerificationLogSection(UIComponent component, string dataProviderName, string verificationConstraint)
: base(component)
{
Message = new StringBuilder($"Verify").
AppendIf(!component.GetType().IsSubclassOfRawGeneric(typeof(PageObject<>)), $" {component.ComponentFullName}").
AppendIf(!string.IsNullOrWhiteSpace(dataProviderName), $" {dataProviderName}").
AppendIf(!string.IsNullOrWhiteSpace(verificationConstraint), $" {verificationConstraint}").
ToString();
}
}
}
| using System.Text;
namespace Atata
{
public class VerificationLogSection : UIComponentLogSection
{
public VerificationLogSection(UIComponent component, string verificationConstraint)
: this(component, null, verificationConstraint)
{
}
public VerificationLogSection(UIComponent component, string dataProviderName, string verificationConstraint)
: base(component)
{
Message = new StringBuilder($"Verify {component.ComponentFullName}").
AppendIf(!string.IsNullOrWhiteSpace(dataProviderName), $" {dataProviderName}").
AppendIf(!string.IsNullOrWhiteSpace(verificationConstraint), $" {verificationConstraint}").
ToString();
}
}
}
| apache-2.0 | C# |
e728bdb884b8ee0b491e86237c6588e51d440ac5 | Add HTML5 download attribute. | x335/scriptsharp,x335/scriptsharp,x335/scriptsharp,nikhilk/scriptsharp,nikhilk/scriptsharp,nikhilk/scriptsharp | src/Libraries/Web/Html/AnchorElement.cs | src/Libraries/Web/Html/AnchorElement.cs | // AnchorElement.cs
// Script#/Libraries/Web
// Copyright (c) Nikhil Kothari.
// Copyright (c) Microsoft Corporation.
// This source code is subject to terms and conditions of the Microsoft
// Public License. A copy of the license can be found in License.txt.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[IgnoreNamespace]
[Imported]
public sealed class AnchorElement : Element {
private AnchorElement() {
}
[IntrinsicProperty]
public string Href {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Rel {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Target {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Download {
get {
return null;
}
set {
}
}
}
}
| // AnchorElement.cs
// Script#/Libraries/Web
// Copyright (c) Nikhil Kothari.
// Copyright (c) Microsoft Corporation.
// This source code is subject to terms and conditions of the Microsoft
// Public License. A copy of the license can be found in License.txt.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[IgnoreNamespace]
[Imported]
public sealed class AnchorElement : Element {
private AnchorElement() {
}
[IntrinsicProperty]
public string Href {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Rel {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public string Target {
get {
return null;
}
set {
}
}
}
}
| apache-2.0 | C# |
0b82e619618ce7adcd32365e0e6553b25d3490ff | add GetCustomReplacement for non-connection string replacements | avifatal/framework,signumsoftware/framework,avifatal/framework,AlejandroCano/framework,AlejandroCano/framework,signumsoftware/framework | Signum.Engine/Connection/UserConnections.cs | Signum.Engine/Connection/UserConnections.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Signum.Engine;
using System.Data.SqlClient;
using System.Diagnostics;
using Signum.Engine.Maps;
using Signum.Utilities;
using System.Text.RegularExpressions;
namespace Signum.Engine
{
public static class UserConnections
{
public static string FileName = @"C:\UserConnections.txt";
static Dictionary<string, string> replacements = null;
public static Dictionary<string, string> LoadReplacements()
{
if (!File.Exists(FileName))
return new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
return File.ReadAllLines(FileName).Where(s=> !string.IsNullOrWhiteSpace(s) && !s.StartsWith("-") && !s.StartsWith("/")).ToDictionaryEx(a => a.Before('>'), a => a.After('>'), "UserConnections");
}
public static string Replace(string connectionString)
{
if (replacements == null)
replacements = LoadReplacements();
Match m = Regex.Match(connectionString, @"(Initial Catalog|Database)\s*=\s*(?<databaseName>[^;]*)\s*;?", RegexOptions.IgnoreCase);
if (!m.Success)
throw new InvalidOperationException("Database name not found");
string databaseName = m.Groups["databaseName"].Value;
return replacements.TryGetC(databaseName) ?? connectionString;
}
public static string GetCustomReplacement(string key)
{
return replacements.TryGetC(key);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Signum.Engine;
using System.Data.SqlClient;
using System.Diagnostics;
using Signum.Engine.Maps;
using Signum.Utilities;
using System.Text.RegularExpressions;
namespace Signum.Engine
{
public static class UserConnections
{
public static string FileName = @"C:\UserConnections.txt";
static Dictionary<string, string> replacements = null;
public static Dictionary<string, string> LoadReplacements()
{
if (!File.Exists(FileName))
return new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
return File.ReadAllLines(FileName).Where(s=> !string.IsNullOrWhiteSpace(s) && !s.StartsWith("-") && !s.StartsWith("/")).ToDictionaryEx(a => a.Before('>'), a => a.After('>'), "UserConnections");
}
public static string Replace(string connectionString)
{
if (replacements == null)
replacements = LoadReplacements();
Match m = Regex.Match(connectionString, @"(Initial Catalog|Database)\s*=\s*(?<databaseName>[^;]*)\s*;?", RegexOptions.IgnoreCase);
if (!m.Success)
throw new InvalidOperationException("Database name not found");
string databaseName = m.Groups["databaseName"].Value;
return replacements.TryGetC(databaseName) ?? connectionString;
}
}
}
| mit | C# |
4cd3379607be9c81680b39fccbf3b0746cca9493 | Delete unused methods. | FacilityApi/Facility | tests/Facility.Definition.UnitTests/TestUtility.cs | tests/Facility.Definition.UnitTests/TestUtility.cs | using System;
using System.Collections.Generic;
using Facility.Definition.Fsd;
using NUnit.Framework;
namespace Facility.Definition.UnitTests
{
internal static class TestUtility
{
public static ServiceInfo ParseTestApi(string text)
{
return new FsdParser().ParseDefinition(new ServiceDefinitionText("TestApi.fsd", text));
}
public static ServiceDefinitionException ParseInvalidTestApi(string text)
{
try
{
ParseTestApi(text);
throw new InvalidOperationException("Parse did not fail.");
}
catch (ServiceDefinitionException exception)
{
return exception;
}
}
public static IReadOnlyList<ServiceDefinitionError> TryParseInvalidTestApi(string text)
{
if (new FsdParser().TryParseDefinition(new ServiceDefinitionText("TestApi.fsd", text), out _, out var errors))
throw new InvalidOperationException("Parse did not fail.");
return errors;
}
public static string[] GenerateFsd(ServiceInfo service)
{
var generator = new FsdGenerator { GeneratorName = "TestUtility" };
return generator.GenerateOutput(service).Files[0].Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
}
}
}
| using System;
using System.Collections.Generic;
using Facility.Definition.Fsd;
using NUnit.Framework;
namespace Facility.Definition.UnitTests
{
internal static class TestUtility
{
public static void ThrowsServiceDefinitionException(Action action, ServiceDefinitionPosition position)
{
try
{
action();
throw new InvalidOperationException("Action did not throw.");
}
catch (ServiceDefinitionException exception)
{
Assert.AreSame(position, exception.Errors[0].Position);
}
}
public static void ThrowsServiceDefinitionException(Func<object> func, ServiceDefinitionPosition position)
{
ThrowsServiceDefinitionException(
() =>
{
func();
}, position);
}
public static ServiceInfo ParseTestApi(string text)
{
return new FsdParser().ParseDefinition(new ServiceDefinitionText("TestApi.fsd", text));
}
public static ServiceDefinitionException ParseInvalidTestApi(string text)
{
try
{
ParseTestApi(text);
throw new InvalidOperationException("Parse did not fail.");
}
catch (ServiceDefinitionException exception)
{
return exception;
}
}
public static IReadOnlyList<ServiceDefinitionError> TryParseInvalidTestApi(string text)
{
if (new FsdParser().TryParseDefinition(new ServiceDefinitionText("TestApi.fsd", text), out _, out var errors))
throw new InvalidOperationException("Parse did not fail.");
return errors;
}
public static string[] GenerateFsd(ServiceInfo service)
{
var generator = new FsdGenerator { GeneratorName = "TestUtility" };
return generator.GenerateOutput(service).Files[0].Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
}
}
}
| mit | C# |
6b39bf519885825083443e985a216d1abed8824e | fix iis | linezero/NETCoreBBS,linezero/NETCoreBBS | src/NetCoreBBS/Program.cs | src/NetCoreBBS/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace NetCoreBBS
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://*:80")
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace NetCoreBBS
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://*:80")
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| mit | C# |
9fcc0c88b218b22e789bac5a3fe1b3694fd0589c | increment patch version | jwChung/TfsBuilder | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2013, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.3.3")]
[assembly: AssemblyInformationalVersion("0.3.3")] | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2013, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.3.2")]
[assembly: AssemblyInformationalVersion("0.3.2")] | mit | C# |
f3e936788b8dfb4e2a01470366cb037f42bd749c | update sample to show multiple AddClaim calls | rvdkooy/BrockAllen.MembershipReboot,eric-swann-q2/BrockAllen.MembershipReboot,vinneyk/BrockAllen.MembershipReboot,vankooch/BrockAllen.MembershipReboot,brockallen/BrockAllen.MembershipReboot,rajendra1809/BrockAllen.MembershipReboot,DosGuru/MembershipReboot,tomascassidy/BrockAllen.MembershipReboot | samples/SingleTenantWebApp/Global.asax.cs | samples/SingleTenantWebApp/Global.asax.cs | using BrockAllen.MembershipReboot.Ef;
using BrockAllen.MembershipReboot.Mvc.App_Start;
using System.Data.Entity;
using System.Security.Claims;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace BrockAllen.MembershipReboot.Mvc
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer<DefaultMembershipRebootDatabase>(new CreateDatabaseIfNotExists<DefaultMembershipRebootDatabase>());
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
InitDatabase();
}
private void InitDatabase()
{
using (var svc = new UserAccountService(new DefaultUserAccountRepository()))
{
if (svc.GetByUsername("admin") == null)
{
var account = svc.CreateAccount("admin", "admin123", "[email protected]");
svc.VerifyAccount(account.VerificationKey);
account.AddClaim(ClaimTypes.Role, "Administrator");
account.AddClaim(ClaimTypes.Role, "Manager");
account.AddClaim(ClaimTypes.Country, "USA");
svc.Update(account);
}
}
}
}
} | using BrockAllen.MembershipReboot.Ef;
using BrockAllen.MembershipReboot.Mvc.App_Start;
using System.Data.Entity;
using System.Security.Claims;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace BrockAllen.MembershipReboot.Mvc
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer<DefaultMembershipRebootDatabase>(new CreateDatabaseIfNotExists<DefaultMembershipRebootDatabase>());
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
InitDatabase();
}
private void InitDatabase()
{
using (var svc = new UserAccountService(new DefaultUserAccountRepository()))
{
if (svc.GetByUsername("admin") == null)
{
var account = svc.CreateAccount("admin", "admin123", "[email protected]");
svc.VerifyAccount(account.VerificationKey);
account.AddClaim(ClaimTypes.Role, "Administrator");
svc.Update(account);
}
}
}
}
} | bsd-3-clause | C# |
6b21a605c20620a52a90d517a658812f4033e971 | Bump version number to v1.1.0.26 | TDaphneB/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,jcvandan/XeroAPI.Net,XeroAPI/XeroAPI.Net | source/XeroApi/Properties/AssemblyInfo.cs | source/XeroApi/Properties/AssemblyInfo.cs | 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("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.26")]
[assembly: AssemblyFileVersion("1.1.0.26")]
| 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("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.25")]
[assembly: AssemblyFileVersion("1.1.0.25")]
| mit | C# |
22aae01e3e006a93443c23dbe87226d07f9e525c | enable jumping | nerai/CMenu | src/ExampleMenu/Procedures/ProcManager.cs | src/ExampleMenu/Procedures/ProcManager.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ConsoleMenu;
namespace ExampleMenu.Procedures
{
public class ProcManager
{
private class Proc
{
public readonly List<string> Commands = new List<string> ();
public readonly Dictionary<string, int> JumpMarks = new Dictionary<string, int> ();
public Proc (IEnumerable<string> content)
{
Commands = new List<string> (content);
for (int i = 0; i < Commands.Count; i++) {
var s = Commands[i];
if (s.StartsWith (":")) {
s = s.Substring (1);
var name = MenuUtil.SplitFirstWord (ref s);
JumpMarks[name] = i;
Commands[i] = s;
}
}
}
}
private readonly Dictionary<string, Proc> _Procs = new Dictionary<string, Proc> ();
private bool _RequestReturn = false;
private string _RequestJump = null;
public void AddProc (string name, IEnumerable<string> content)
{
var proc = new Proc (content);
_Procs.Add (name, proc);
}
public IEnumerable<string> GenerateInput (string procname)
{
Proc proc;
if (!_Procs.TryGetValue (procname, out proc)) {
Console.WriteLine ("Unknown procedure: " + proc);
yield break;
}
int i = 0;
while (i < proc.Commands.Count) {
var line = proc.Commands[i];
yield return line;
if (_RequestReturn) {
_RequestReturn = false;
break;
}
if (_RequestJump != null) {
i = proc.JumpMarks[_RequestJump]; // todo check
_RequestJump = null;
break;
}
}
}
public void Return ()
{
_RequestReturn = true;
}
public void Jump (string mark)
{
_RequestJump = mark;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ConsoleMenu;
namespace ExampleMenu.Procedures
{
public class ProcManager
{
private class Proc
{
public readonly List<string> Commands = new List<string> ();
public Proc (IEnumerable<string> content)
{
Commands = new List<string> (content);
}
}
private readonly Dictionary<string, Proc> _Procs = new Dictionary<string, Proc> ();
private bool _RequestReturn = false;
public void AddProc (string name, IEnumerable<string> content)
{
var proc = new Proc (content);
_Procs.Add (name, proc);
}
public IEnumerable<string> GenerateInput (string procname)
{
Proc proc;
if (!_Procs.TryGetValue (procname, out proc)) {
Console.WriteLine ("Unknown procedure: " + proc);
yield break;
}
int i = 0;
while (i < proc.Commands.Count) {
var line = proc.Commands[i];
yield return line;
if (_RequestReturn) {
_RequestReturn = false;
break;
}
}
}
public void Return ()
{
_RequestReturn = true;
}
}
}
| mit | C# |
45680b86ab43dc59073fb758c8ef2bdd521ead34 | Improve the documentation: - RetryContextExtensions.GetRetryAttempt - made it clear that it returns the number of the current attempt - RetryContextExtensions.GetRetryCount - corrected the incorrect description of when it returns zero | phatboyg/MassTransit,MassTransit/MassTransit,phatboyg/MassTransit,MassTransit/MassTransit | src/MassTransit/RetryContextExtensions.cs | src/MassTransit/RetryContextExtensions.cs | namespace MassTransit
{
using Context;
public static class RetryContextExtensions
{
/// <summary>
/// If within a retry attempt, the return value is greater than zero and indicates the number of the retry attempt
/// in progress.
/// </summary>
/// <param name="context"></param>
/// <returns>The retry attempt number, 0 = first time, >= 1 = retry</returns>
public static int GetRetryAttempt(this ConsumeContext context)
{
return context.TryGetPayload(out ConsumeRetryContext retryContext) ? retryContext.RetryAttempt : 0;
}
/// <summary>
/// If within a retry attempt, the return value indicates the number of retry attempts that have already occurred.
/// </summary>
/// <param name="context"></param>
/// <returns>The number of retries that have already been attempted, 0 = first time or first retry, >= 1 = subsequent retry</returns>
public static int GetRetryCount(this ConsumeContext context)
{
return context.TryGetPayload(out ConsumeRetryContext retryContext) ? retryContext.RetryCount : 0;
}
/// <summary>
/// If the message is being redelivered, returns the redelivery attempt
/// </summary>
/// <param name="context"></param>
/// <returns>The retry attempt number, 0 = first time, >= 1 = retry</returns>
public static int GetRedeliveryCount(this ConsumeContext context)
{
return context.Headers.Get(MessageHeaders.RedeliveryCount, default(int?)) ?? 0;
}
}
}
| namespace MassTransit
{
using Context;
public static class RetryContextExtensions
{
/// <summary>
/// If within a retry attempt, the return value is greater than zero and indicates the number of retry attempts
/// that have occurred.
/// </summary>
/// <param name="context"></param>
/// <returns>The retry attempt number, 0 = first time, >= 1 = retry</returns>
public static int GetRetryAttempt(this ConsumeContext context)
{
return context.TryGetPayload(out ConsumeRetryContext retryContext) ? retryContext.RetryAttempt : 0;
}
/// <summary>
/// If within a retry attempt, the return value is greater than zero and indicates the number of retry attempts
/// that have occurred.
/// </summary>
/// <param name="context"></param>
/// <returns>The retry attempt number, 0 = first time, >= 1 = retry</returns>
public static int GetRetryCount(this ConsumeContext context)
{
return context.TryGetPayload(out ConsumeRetryContext retryContext) ? retryContext.RetryCount : 0;
}
/// <summary>
/// If the message is being redelivered, returns the redelivery attempt
/// </summary>
/// <param name="context"></param>
/// <returns>The retry attempt number, 0 = first time, >= 1 = retry</returns>
public static int GetRedeliveryCount(this ConsumeContext context)
{
return context.Headers.Get(MessageHeaders.RedeliveryCount, default(int?)) ?? 0;
}
}
}
| apache-2.0 | C# |
f6d7e5a41c9ac1a3ec0875772fc71d86ef8cfc38 | Change opening message | jquintus/TeamCitySpike | AmazingApp/AmazingApp/Program.cs | AmazingApp/AmazingApp/Program.cs | using System;
namespace AmazingApp
{
public class Program
{
public static string Msg { get { return "Hello TeamCity!"; } }
public static void Main(string[] args)
{
Console.WriteLine(Msg);
}
}
} | using System;
namespace AmazingApp
{
public class Program
{
public static string Msg { get { return "Hello World"; } }
public static void Main(string[] args)
{
Console.WriteLine(Msg);
}
}
} | mit | C# |
05c301ec409886e701641cdfd01658042bee6c37 | Debug assertion test fix. | colgreen/sharpneat | src/SharpNeatLib/Core/CoordinateVector.cs | src/SharpNeatLib/Core/CoordinateVector.cs | /* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green ([email protected])
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System.Collections.Generic;
using System.Diagnostics;
namespace SharpNeat.Core
{
/// <summary>
/// General purpose representation of a point in a multidimensional space. A vector of coordinates,
/// each coordinate defining the position within a dimension/axis defined by an ID.
/// </summary>
public class CoordinateVector
{
readonly KeyValuePair<ulong,double>[] _coordElemArray;
#region Constructor
/// <summary>
/// Constructs a CoordinateVector using the provided array of ID/coordinate pairs.
/// CoordinateVector elements must be sorted by ID.
/// </summary>
public CoordinateVector(KeyValuePair<ulong,double>[] coordElemArray)
{
Debug.Assert(IsSorted(coordElemArray), "CoordinateVector elements must be sorted by ID.");
_coordElemArray = coordElemArray;
}
#endregion
#region Properties
/// <summary>
/// Gets an array containing the ID/coordinate pairs.
/// CoordinateVector elements are sorted by ID
/// </summary>
public KeyValuePair<ulong,double>[] CoordArray
{
get { return _coordElemArray; }
}
#endregion
#region Static Methods [Debugging]
private static bool IsSorted(KeyValuePair<ulong,double>[] coordElemArray)
{
if(0 == coordElemArray.Length) {
return true;
}
ulong prevId = coordElemArray[0].Key;
for(int i=1; i<coordElemArray.Length; i++)
{ // <= also checks for duplicates as well as sort order.
if(coordElemArray[i].Key <= prevId) {
return false;
}
prevId = coordElemArray[i].Key;
}
return true;
}
#endregion
}
}
| /* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green ([email protected])
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System.Collections.Generic;
using System.Diagnostics;
namespace SharpNeat.Core
{
/// <summary>
/// General purpose representation of a point in a multidimensional space. A vector of coordinates,
/// each coordinate defining the position within a dimension/axis defined by an ID.
/// </summary>
public class CoordinateVector
{
readonly KeyValuePair<ulong,double>[] _coordElemArray;
#region Constructor
/// <summary>
/// Constructs a CoordinateVector using the provided array of ID/coordinate pairs.
/// CoordinateVector elements must be sorted by ID.
/// </summary>
public CoordinateVector(KeyValuePair<ulong,double>[] coordElemArray)
{
Debug.Assert(IsSorted(coordElemArray), "CoordinateVector elements must be sorted by ID.");
_coordElemArray = coordElemArray;
}
#endregion
#region Properties
/// <summary>
/// Gets an array containing the ID/coordinate pairs.
/// CoordinateVector elements are sorted by ID
/// </summary>
public KeyValuePair<ulong,double>[] CoordArray
{
get { return _coordElemArray; }
}
#endregion
#region Static Methods [Debugging]
private static bool IsSorted(KeyValuePair<ulong,double>[] coordElemArray)
{
if(0 == coordElemArray.Length) {
return true;
}
ulong prevId = coordElemArray[0].Key;
for(int i=1; i<coordElemArray.Length; i++)
{ // <= also checks for duplicates as well as sort order.
if(coordElemArray[i].Key <= prevId) {
return false;
}
}
return true;
}
#endregion
}
}
| mit | C# |
6726ad0813321bbe1408768945ab1186c747c473 | Fix EditableObject.Rollback. | jakubfijalkowski/studentscalendar | StudentsCalendar.UI/EditableObject.cs | StudentsCalendar.UI/EditableObject.cs | using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using NodaTime;
using NodaTime.Serialization.JsonNet;
namespace StudentsCalendar.UI
{
/// <summary>
/// Udostępnia mechanizm do przywrócenia danych obiektu z momentu utworzenia.
/// </summary>
/// <remarks>
/// Używa do tego serializacji do formatu Bson za pomocą Json.NET.
/// </remarks>
/// <typeparam name="TData"></typeparam>
public sealed class EditableObject<TData>
{
private readonly JsonSerializer Serializer = JsonSerializer.Create(new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
ObjectCreationHandling = ObjectCreationHandling.Replace
}.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb));
private readonly byte[] OriginalData;
private readonly TData _Data;
/// <summary>
/// Pobiera obiekt do edycji.
/// </summary>
public TData Data
{
get { return this._Data; }
}
public EditableObject(TData obj)
{
this._Data = obj;
using (var stream = new MemoryStream())
{
using (var writer = new BsonWriter(stream))
{
this.Serializer.Serialize(writer, obj);
}
this.OriginalData = stream.ToArray();
}
}
/// <summary>
/// Cofa zmiany wprowadzone w obiekcie.
/// </summary>
public void Rollback()
{
using (var stream = new MemoryStream(this.OriginalData))
using (var reader = new BsonReader(stream))
{
this.Serializer.Populate(reader, this.Data);
}
}
}
}
| using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using NodaTime;
using NodaTime.Serialization.JsonNet;
namespace StudentsCalendar.UI
{
/// <summary>
/// Udostępnia mechanizm do przywrócenia danych obiektu z momentu utworzenia.
/// </summary>
/// <remarks>
/// Używa do tego serializacji do formatu Bson za pomocą Json.NET.
/// </remarks>
/// <typeparam name="TData"></typeparam>
public sealed class EditableObject<TData>
{
private readonly JsonSerializer Serializer = JsonSerializer.Create(new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
}.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb));
private readonly byte[] OriginalData;
private readonly TData _Data;
/// <summary>
/// Pobiera obiekt do edycji.
/// </summary>
public TData Data
{
get { return this._Data; }
}
public EditableObject(TData obj)
{
this._Data = obj;
using (var stream = new MemoryStream())
{
using (var writer = new BsonWriter(stream))
{
this.Serializer.Serialize(writer, obj);
}
this.OriginalData = stream.ToArray();
}
}
/// <summary>
/// Cofa zmiany wprowadzone w obiekcie.
/// </summary>
public void Rollback()
{
using (var stream = new MemoryStream(this.OriginalData))
using (var reader = new BsonReader(stream))
{
this.Serializer.Populate(reader, this.Data);
}
}
}
}
| mit | C# |
e1d9994b212b138caa27a5e54c956284037f53f6 | Revert unintentional changes to XamMac AssemblyInfo | TheBrainTech/xwt | Xwt.XamMac/Properties/AssemblyInfo.cs | Xwt.XamMac/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xwt.XamMac")]
[assembly: AssemblyDescription("Xamarin Mac Toolkit for the Xwt UI Framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Xwt UI Framework")]
[assembly: AssemblyCopyright("Xamarin, Inc (http://www.xamarin.com)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0.0-prerelease")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xwt.XamMac")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("${AuthorCopyright}")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
da5614d39579214fd621bede0e62eff9cfbfed9b | Fix AFK controller | mikelovesrobots/daft-pong,mikelovesrobots/daft-pong | app/Assets/Scripts/PaddleAiAfkController.cs | app/Assets/Scripts/PaddleAiAfkController.cs | using UnityEngine;
using System.Collections;
public class PaddleAiAfkController : PaddleAi {
public override void Tick() { }
}
| using UnityEngine;
using System.Collections;
public class PaddleAiAfkController : PaddleAi {
private const float MIN_DRIFT = 0.0001f;
private const float MAX_DRIFT = 0.0003f;
private float drift = 0f;
void Start() {
drift = Random.Range(MIN_DRIFT, MAX_DRIFT);
}
public override void Tick() {
var position = transform.position;
position.y += drift;
transform.position = position;
}
}
| mit | C# |
72fbf355b32d30bdee6d30e6deb0245f818712c5 | Remove service alerts workaround (#33) | RikkiGibson/Corvallis-Bus-Server,RikkiGibson/Corvallis-Bus-Server | CorvallisBus.Core/WebClients/ServiceAlertsClient.cs | CorvallisBus.Core/WebClients/ServiceAlertsClient.cs | using System;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using CorvallisBus.Core.Models;
using HtmlAgilityPack;
namespace CorvallisBus.Core.WebClients
{
public static class ServiceAlertsClient
{
static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581");
static readonly HttpClient httpClient = new HttpClient();
public static async Task<List<ServiceAlert>> GetServiceAlerts()
{
var responseStream = await httpClient.GetStreamAsync(FEED_URL);
var htmlDocument = new HtmlDocument();
htmlDocument.Load(responseStream);
var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr")
.Select(row => ParseRow(row))
.ToList();
return alerts;
}
private static ServiceAlert ParseRow(HtmlNode row)
{
var anchor = row.Descendants("a").First();
var relativeLink = anchor.Attributes["href"].Value;
var link = new Uri(FEED_URL, relativeLink).ToString();
var title = anchor.InnerText;
var publishDate = row.Descendants("span")
.First(node => node.HasClass("date-display-single"))
.Attributes["content"]
.Value;
return new ServiceAlert(title, publishDate, link);
}
}
}
| using System;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using CorvallisBus.Core.Models;
using HtmlAgilityPack;
namespace CorvallisBus.Core.WebClients
{
public static class ServiceAlertsClient
{
static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581");
static readonly HttpClient httpClient = new HttpClient();
public static async Task<List<ServiceAlert>> GetServiceAlerts()
{
#if false
var responseStream = await httpClient.GetStreamAsync(FEED_URL);
var htmlDocument = new HtmlDocument();
htmlDocument.Load(responseStream);
var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr")
.Select(row => ParseRow(row))
.ToList();
return alerts;
#endif
return await Task.FromResult(new List<ServiceAlert>()
{
new ServiceAlert("Tap to view service alerts", "2018-11-4T00:00:00-07:00", "https://www.corvallisoregon.gov/news?field_microsite_tid=581")
});
}
private static ServiceAlert ParseRow(HtmlNode row)
{
var anchor = row.Descendants("a").First();
var relativeLink = anchor.Attributes["href"].Value;
var link = new Uri(FEED_URL, relativeLink).ToString();
var title = anchor.InnerText;
var publishDate = row.Descendants("span")
.First(node => node.HasClass("date-display-single"))
.Attributes["content"]
.Value;
return new ServiceAlert(title, publishDate, link);
}
}
}
| mit | C# |
02cfeeef1d308c54a3881ca659b5e82d9f7dbf56 | Add rotation to recoil | jkereako/PillBlasta | Assets/Scripts/Weapon/Weapon.cs | Assets/Scripts/Weapon/Weapon.cs | using UnityEngine;
public enum FireMode {
Automatic,
Burst,
Single}
;
[RequireComponent(typeof(MuzzleFlash))]
public class Weapon: MonoBehaviour {
public FireMode fireMode;
public Transform muzzle;
public Transform ejector;
public Projectile projectile;
public Transform shell;
public int burstCount = 3;
public float fireRate = 100;
public float muzzleVelocity = 35;
float nextShotTime;
int shotsRemaining;
float angleDampaningVelocity;
Vector3 postitionDampaningVelocity;
float recoilAngle;
void Start() {
Initialize();
}
void LateUpdate() {
// Reset the position of the weapon.
Vector3 postitionDampaning;
postitionDampaning = Vector3.SmoothDamp(
transform.localPosition, Vector3.zero, ref postitionDampaningVelocity, 0.1f
);
recoilAngle = Mathf.SmoothDamp(recoilAngle, 0, ref angleDampaningVelocity, 0.1f);
transform.localPosition = postitionDampaning;
transform.localEulerAngles += Vector3.left * recoilAngle;
}
public void OnTriggerPull() {
if (shotsRemaining == 0 || Time.time < nextShotTime) {
return;
}
Fire();
switch (fireMode) {
case FireMode.Single:
case FireMode.Burst:
shotsRemaining -= 1;
break;
}
}
public void OnTriggerRelease() {
Initialize();
}
public void Aim(Vector3 point) {
transform.LookAt(point);
}
void Fire() {
Projectile aProjectile;
MuzzleFlash muzzleFlash = GetComponent<MuzzleFlash>();
nextShotTime = Time.time + fireRate / 1000;
aProjectile = Instantiate(projectile, muzzle.position, muzzle.rotation);
aProjectile.SetSpeed(muzzleVelocity);
Instantiate(shell, ejector.position, ejector.rotation);
muzzleFlash.Animate();
AnimateRecoil();
}
void AnimateRecoil() {
recoilAngle += 8.0f;
Mathf.Clamp(recoilAngle, 0, 30);
// Move the weapon backward
transform.localPosition -= Vector3.forward * 0.2f;
}
void Initialize() {
switch (fireMode) {
case FireMode.Single:
shotsRemaining = 1;
break;
case FireMode.Burst:
shotsRemaining = burstCount;
break;
case FireMode.Automatic:
shotsRemaining = -1;
break;
}
}
}
| using UnityEngine;
public enum FireMode {
Automatic,
Burst,
Single}
;
[RequireComponent(typeof(MuzzleFlash))]
public class Weapon: MonoBehaviour {
public FireMode fireMode;
public Transform muzzle;
public Transform ejector;
public Projectile projectile;
public Transform shell;
public int burstCount = 3;
public float fireRate = 100;
public float muzzleVelocity = 35;
float nextShotTime;
int shotsRemaining;
Vector3 velocity;
void Start() {
Initialize();
}
void Update() {
// Reset the position of the weapon.
Vector3 smoothDamp;
smoothDamp = Vector3.SmoothDamp(transform.localPosition, Vector3.zero, ref velocity, 0.1f);
transform.localPosition = smoothDamp;
}
public void OnTriggerPull() {
if (shotsRemaining == 0 || Time.time < nextShotTime) {
return;
}
Fire();
switch (fireMode) {
case FireMode.Single:
case FireMode.Burst:
shotsRemaining -= 1;
break;
}
}
public void OnTriggerRelease() {
Initialize();
}
public void Aim(Vector3 point) {
transform.LookAt(point);
}
void Fire() {
Projectile aProjectile;
MuzzleFlash muzzleFlash = GetComponent<MuzzleFlash>();
nextShotTime = Time.time + fireRate / 1000;
aProjectile = Instantiate(projectile, muzzle.position, muzzle.rotation);
aProjectile.SetSpeed(muzzleVelocity);
Instantiate(shell, ejector.position, ejector.rotation);
muzzleFlash.Animate();
AnimateRecoil();
}
void AnimateRecoil() {
// Move the weapon backward
transform.localPosition -= Vector3.forward * 0.2f;
}
void Initialize() {
switch (fireMode) {
case FireMode.Single:
shotsRemaining = 1;
break;
case FireMode.Burst:
shotsRemaining = burstCount;
break;
case FireMode.Automatic:
shotsRemaining = -1;
break;
}
}
}
| mit | C# |
1decc312a30a80fb934f675a85be1f041e670346 | Test even and odd tab settings. | MrSim17/LaserCutterTools | BoxBuilder/BoxBuilderFactory.cs | BoxBuilder/BoxBuilderFactory.cs | using ColorProvider;
using Common;
namespace BoxBuilder
{
public sealed class BoxBuilderFactory
{
internal static IBoxPointGenerator GetBoxPointGenerator(ILogger Logger)
{
IPiecePointGenerator piecePointGen = new PiecePointGenerator();
IBoxPointGenerator pointGen = new BoxPointGenerator(piecePointGen, Logger);
return pointGen;
}
public static IBoxBuilderSVG GetBoxHandler(ILogger Logger)
{
IColorProvider colorProvider = new ColorProviderAllDifferent();
IBoxPointRendererSVG pointRender = new BoxPointRendererSVG(colorProvider, true);
IBoxPointGenerator pointGen = GetBoxPointGenerator(Logger);
IBoxBuilderSVG handler = new BoxBuilderSVG(pointGen,
pointRender,
Logger);
return handler;
}
}
} | using ColorProvider;
using Common;
namespace BoxBuilder
{
public sealed class BoxBuilderFactory
{
internal static IBoxPointGenerator GetBoxPointGenerator(ILogger Logger)
{
IPiecePointGenerator piecePointGen = new PiecePointGenerator();
IBoxPointGenerator pointGen = new BoxPointGenerator(piecePointGen, Logger);
return pointGen;
}
public static IBoxBuilderSVG GetBoxHandler(ILogger Logger)
{
IColorProvider colorProvider = new ColorProviderAllDifferent();
IBoxPointRendererSVG pointRender = new BoxPointRendererSVG(colorProvider);
IBoxPointGenerator pointGen = GetBoxPointGenerator(Logger);
IBoxBuilderSVG handler = new BoxBuilderSVG(pointGen,
pointRender,
Logger);
return handler;
}
}
} | mit | C# |
60a3f2c484a2bd06cb25c2ddda624385ab2026aa | Update NewAzureIPTag.cs | naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,atpham256/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,naveedaz/azure-powershell,atpham256/azure-powershell | src/ServiceManagement/Compute/Commands.ServiceManagement/IaaS/Network/NewAzureIPTag.cs | src/ServiceManagement/Compute/Commands.ServiceManagement/IaaS/Network/NewAzureIPTag.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Management.Automation;
using Microsoft.WindowsAzure.Management.Network.Models;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Properties;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS
{
[Cmdlet(VerbsCommon.New, "AzureIPTag"), OutputType(typeof(IPTag))]
public class NewAzureIPTagCommand : Cmdlet
{
[Parameter(Position = 0, Mandatory = true, HelpMessage = "IP Tag Type of desired IP address")]
[ValidateSet(Management.Network.Models.IPTagType.IPAddressClassification,
Management.Network.Models.IPTagType.FirstPartyUsage,
Management.Network.Models.IPTagType.AvailabilityZone, IgnoreCase = true)]
[ValidateNotNullOrEmpty]
public string IPTagType
{
get;
set;
}
[Parameter(Position = 1, Mandatory = true, HelpMessage = "Value of the IPTag")]
[ValidateNotNullOrEmpty]
public string Value
{
get;
set;
}
public void ExecuteCommand()
{
WriteObject(new IPTag { IPTagType = this.IPTagType, Value = Value });
}
protected override void ProcessRecord()
{
try
{
base.ProcessRecord();
ExecuteCommand();
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, string.Empty, ErrorCategory.CloseError, null));
}
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Management.Automation;
using Microsoft.WindowsAzure.Management.Network.Models;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Properties;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS
{
[Cmdlet(VerbsCommon.New, "AzureIPTag", SupportsShouldProcess = true), OutputType(typeof(IPTag))]
public class NewAzureIPTagCommand : Cmdlet
{
[Parameter(Position = 0, Mandatory = true, HelpMessage = "IP Tag Type of desired IP address")]
[ValidateSet(Management.Network.Models.IPTagType.IPAddressClassification,
Management.Network.Models.IPTagType.FirstPartyUsage,
Management.Network.Models.IPTagType.AvailabilityZone, IgnoreCase = true)]
[ValidateNotNullOrEmpty]
public string IPTagType
{
get;
set;
}
[Parameter(Position = 1, Mandatory = true, HelpMessage = "Value of the IPTag")]
[ValidateNotNullOrEmpty]
public string Value
{
get;
set;
}
public void ExecuteCommand()
{
WriteObject(new IPTag { IPTagType = this.IPTagType, Value = Value });
}
protected override void ProcessRecord()
{
try
{
base.ProcessRecord();
ExecuteCommand();
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, string.Empty, ErrorCategory.CloseError, null));
}
}
}
}
| apache-2.0 | C# |
28955d0f02e5e369dbac824f167cd87c8fd1dfb3 | Fix up for 16.11 | dotnet/roslyn,AmadeusW/roslyn,physhi/roslyn,sharwell/roslyn,bartdesmet/roslyn,mavasani/roslyn,KevinRansom/roslyn,dotnet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,bartdesmet/roslyn,eriawan/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,wvdd007/roslyn,eriawan/roslyn,diryboy/roslyn,sharwell/roslyn,diryboy/roslyn,mavasani/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,KevinRansom/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,eriawan/roslyn,weltkante/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn | src/Tools/ExternalAccess/OmniSharp/Internal/PickMembers/OmniSharpPickMembersService.cs | src/Tools/ExternalAccess/OmniSharp/Internal/PickMembers/OmniSharpPickMembersService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.PickMembers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PickMembers;
namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Internal.PickMembers
{
[Shared]
[ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host)]
internal class OmniSharpPickMembersService : IPickMembersService
{
private readonly IOmniSharpPickMembersService _omniSharpPickMembersService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public OmniSharpPickMembersService(IOmniSharpPickMembersService omniSharpPickMembersService)
{
_omniSharpPickMembersService = omniSharpPickMembersService;
}
public PickMembersResult PickMembers(string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options = default)
{
var result = _omniSharpPickMembersService.PickMembers(title, members, options.SelectAsArray(o => new OmniSharpPickMembersOption(o)), selectAll: true);
return new(result.Members, result.Options.SelectAsArray(o => o.PickMembersOptionInternal));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.PickMembers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PickMembers;
namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Internal.PickMembers
{
[Shared]
[ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host)]
internal class OmniSharpPickMembersService : IPickMembersService
{
private readonly IOmniSharpPickMembersService _omniSharpPickMembersService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public OmniSharpPickMembersService(IOmniSharpPickMembersService omniSharpPickMembersService)
{
_omniSharpPickMembersService = omniSharpPickMembersService;
}
public PickMembersResult PickMembers(string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options = default, bool selectAll = true)
{
var result = _omniSharpPickMembersService.PickMembers(title, members, options.SelectAsArray(o => new OmniSharpPickMembersOption(o)), selectAll);
return new(result.Members, result.Options.SelectAsArray(o => o.PickMembersOptionInternal), result.SelectedAll);
}
}
}
| mit | C# |
914fcf8db8dae8d338638635f90fc8c8dca84629 | Add DuplicationNameException | kei10in/KipSharp | Kip/Exceptions.cs | Kip/Exceptions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kip
{
/// <summary>
/// Thrown when an attempt is made to add a Print Schema element with the
/// name that already exists to the parent element.
/// </summary>
public class DuplicateNameException : InvalidOperationException
{
public DuplicateNameException() { }
public DuplicateNameException(string message) : base(message) { }
public DuplicateNameException(string message, Exception inner) : base(message, inner) { }
}
public class InvalidChildElementException : Exception
{
public InvalidChildElementException() { }
public InvalidChildElementException(string message) : base(message) { }
public InvalidChildElementException(string message, Exception inner) : base(message, inner) { }
}
public class ReadPrintSchemaDocumentException : Exception
{
public ReadPrintSchemaDocumentException() { }
public ReadPrintSchemaDocumentException(string message) : base(message) { }
public ReadPrintSchemaDocumentException(string message, Exception inner) : base(message, inner) { }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kip
{
public class InvalidChildElementException : Exception
{
public InvalidChildElementException()
{
}
public InvalidChildElementException(string message)
: base(message)
{
}
public InvalidChildElementException(string message, Exception inner)
: base(message, inner)
{
}
}
public class ReadPrintSchemaDocumentException : Exception
{
public ReadPrintSchemaDocumentException()
{
}
public ReadPrintSchemaDocumentException(string message)
: base(message)
{
}
public ReadPrintSchemaDocumentException(string message, Exception inner)
: base(message, inner)
{
}
}
}
| mit | C# |
fd349eb530e99f6b35be81b16f893846fef1650a | Set appsettings.json to optional | alimon808/contoso-university,alimon808/contoso-university,alimon808/contoso-university | ContosoUniversity.Api/Program.cs | ContosoUniversity.Api/Program.cs | using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using Microsoft.Extensions.Configuration;
namespace ContosoUniversity.Api
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.ConfigureAppConfiguration(ConfigConfiguration)
.UseStartup<Startup>()
.Build();
host.Run();
}
// use by EF Tooling
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
public static void ConfigConfiguration(WebHostBuilderContext context, IConfigurationBuilder config)
{
config.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true);
if (context.HostingEnvironment.IsDevelopment())
{
config.AddJsonFile($"sampleData.json", optional: false, reloadOnChange: false);
config.AddUserSecrets<Startup>();
}
config.AddEnvironmentVariables();
}
}
}
| using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using Microsoft.Extensions.Configuration;
namespace ContosoUniversity.Api
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.ConfigureAppConfiguration(ConfigConfiguration)
.UseStartup<Startup>()
.Build();
host.Run();
}
// use by EF Tooling
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
public static void ConfigConfiguration(WebHostBuilderContext context, IConfigurationBuilder config)
{
config.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true);
if (context.HostingEnvironment.IsDevelopment())
{
config.AddJsonFile($"sampleData.json", optional: false, reloadOnChange: false);
config.AddUserSecrets<Startup>();
}
config.AddEnvironmentVariables();
}
}
}
| mit | C# |
bd661bf0efc65914b55f03e1e2c98491d5290a5b | Add methods that need our own implementation | charlenni/Mapsui,charlenni/Mapsui | Mapsui/MPoint2.cs | Mapsui/MPoint2.cs | using Mapsui.Utilities;
namespace Mapsui;
public class MPoint2
{
public double X { get; set; }
public double Y { get; set; }
MRect MRect { get; }
MPoint Copy();
double Distance(MPoint point);
bool Equals(MPoint? p);
int GetHashCode();
MPoint Offset(double offsetX, double offsetY);
/// <summary>
/// Calculates a new point by rotating this point clockwise about the specified center point
/// </summary>
/// <param name="degrees">Angle to rotate clockwise (degrees)</param>
/// <param name="centerX">X coordinate of point about which to rotate</param>
/// <param name="centerY">Y coordinate of point about which to rotate</param>
/// <returns>Returns the rotated point</returns>
public MPoint Rotate(double degrees, double centerX, double centerY)
{
// translate this point back to the center
var newX = X - centerX;
var newY = Y - centerY;
// rotate the values
var p = Algorithms.RotateClockwiseDegrees(newX, newY, degrees);
// translate back to original reference frame
newX = p.X + centerX;
newY = p.Y + centerY;
return new MPoint(newX, newY);
}
/// <summary>
/// Calculates a new point by rotating this point clockwise about the specified center point
/// </summary>
/// <param name="degrees">Angle to rotate clockwise (degrees)</param>
/// <param name="center">MPoint about which to rotate</param>
/// <returns>Returns the rotated point</returns>
public MPoint Rotate(double degrees, MPoint center)
{
return Rotate(degrees, center.X, center.Y);
}
}
| using Mapsui.Utilities;
namespace Mapsui;
public class MPoint2
{
public double X { get; set; }
public double Y { get; set; }
/// <summary>
/// Calculates a new point by rotating this point clockwise about the specified center point
/// </summary>
/// <param name="degrees">Angle to rotate clockwise (degrees)</param>
/// <param name="centerX">X coordinate of point about which to rotate</param>
/// <param name="centerY">Y coordinate of point about which to rotate</param>
/// <returns>Returns the rotated point</returns>
public MPoint Rotate(double degrees, double centerX, double centerY)
{
// translate this point back to the center
var newX = X - centerX;
var newY = Y - centerY;
// rotate the values
var p = Algorithms.RotateClockwiseDegrees(newX, newY, degrees);
// translate back to original reference frame
newX = p.X + centerX;
newY = p.Y + centerY;
return new MPoint(newX, newY);
}
/// <summary>
/// Calculates a new point by rotating this point clockwise about the specified center point
/// </summary>
/// <param name="degrees">Angle to rotate clockwise (degrees)</param>
/// <param name="center">MPoint about which to rotate</param>
/// <returns>Returns the rotated point</returns>
public MPoint Rotate(double degrees, MPoint center)
{
return Rotate(degrees, center.X, center.Y);
}
}
| mit | C# |
791abc52094589059b535cb4184487133f89cace | Add "now im in the cloud" | travistme/PersonalSite | TElkins.Web/Views/Home/Index.cshtml | TElkins.Web/Views/Home/Index.cshtml |
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
Hello people!<br />
Now I'm in the CLOUDDDD
</div>
</body>
</html>
|
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
Hello people!
</div>
</body>
</html>
| mit | C# |
ff80f94c7e1bcdd29d18a4c2504a8a1628c4a310 | add cmd line environment config and folder config | pauldotknopf/react-aspnet-boilerplate,theonlylawislove/react-dot-net,pauldotknopf/react-dot-net,pauldotknopf/react-aspnet-boilerplate,theonlylawislove/react-dot-net,pauldotknopf/react-dot-net | src/ReactBoilerplate/Program.cs | src/ReactBoilerplate/Program.cs | using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace ReactBoilerplate
{
public class Program
{
private static readonly Dictionary<string, string> defaults =
new Dictionary<string, string> {
{ WebHostDefaults.EnvironmentKey, "development" }
};
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(defaults)
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace ReactBoilerplate
{
public class Program
{
public static void Main(string[] args)
{
var host = WebHostBuilderExtensions.UseStartup<Startup>(new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration())
.Build();
host.Run();
}
}
}
| mit | C# |
c7f5d91feb817731f35bf7e2afc70d40020da488 | Update SmsController.cs | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | quickstart/csharp/sms/receive-sms/SmsController.cs | quickstart/csharp/sms/receive-sms/SmsController.cs | // Code sample for ASP.NET MVC on .NET Framework 4.6.1+
// In Package Manager, run:
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor
using Twilio.AspNet.Common;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;
namespace WebApplication1.Controllers
{
public class SmsController : TwilioController
{
public TwiMLResult Index(SmsRequest incomingMessage)
{
var messagingResponse = new MessagingResponse();
messagingResponse.Message("The copy cat says: " +
incomingMessage.Body);
return TwiML(messagingResponse);
}
}
}
| // Code sample for ASP.NET MVC on .NET Framework 4.6.1+
// In Package Manager, run:
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor
using System.Web.Mvc;
using Twilio.AspNet.Common;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;
namespace YourNewWebProject.Controllers
{
public class SmsController : TwilioController
{
[HttpPost]
public TwiMLResult Index(SmsRequest incomingMessage)
{
var messagingResponse = new MessagingResponse();
messagingResponse.Message("The copy cat says: " +
incomingMessage.Body);
return TwiML(messagingResponse);
}
}
}
| mit | C# |
87d7f9aaf8c3a4f1426107a42e9e5f730133c023 | Bump v1.0.8 | karronoli/tiny-sato | TinySato/Properties/AssemblyInfo.cs | TinySato/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TinySato")]
[assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to recognized by windows driver.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TinySato")]
[assembly: AssemblyCopyright("Copyright 2016 karronoli")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
[assembly: AssemblyVersion("1.0.8.*")]
[assembly: AssemblyFileVersion("1.0.8")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TinySato")]
[assembly: AssemblyDescription("You can construct and send SBPL packet to Sato printer. Sato printer is needed to recognized by windows driver.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TinySato")]
[assembly: AssemblyCopyright("Copyright 2016 karronoli")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("f56213db-fa1f-42da-b930-b642a56ee840")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
[assembly: AssemblyVersion("1.0.7.*")]
[assembly: AssemblyFileVersion("1.0.7")]
| apache-2.0 | C# |
b98428c830885171fe311fabc082ca55c7cd1a37 | Use default command timeout | martincostello/website,martincostello/website,martincostello/website,martincostello/website | tests/Website.Tests/WebDriverFactory.cs | tests/Website.Tests/WebDriverFactory.cs | // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Website
{
using System;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
/// <summary>
/// A factory class for creating instances of <see cref="IWebDriver"/>. This class cannot be inherited.
/// </summary>
internal static class WebDriverFactory
{
/// <summary>
/// Creates a new instance of <see cref="IWebDriver"/>.
/// </summary>
/// <returns>
/// The <see cref="IWebDriver"/> to use for tests.
/// </returns>
public static IWebDriver CreateWebDriver()
{
string chromeDriverDirectory = Path.GetDirectoryName(typeof(WebDriverFactory).Assembly.Location) ?? ".";
var options = new ChromeOptions()
{
AcceptInsecureCertificates = true,
};
if (!System.Diagnostics.Debugger.IsAttached)
{
options.AddArgument("--headless");
}
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
#if DEBUG
options.SetLoggingPreference(LogType.Client, LogLevel.All);
options.SetLoggingPreference(LogType.Driver, LogLevel.All);
options.SetLoggingPreference(LogType.Profiler, LogLevel.All);
options.SetLoggingPreference(LogType.Server, LogLevel.All);
#endif
var driver = new ChromeDriver(chromeDriverDirectory, options);
try
{
var timeout = TimeSpan.FromSeconds(10);
var timeouts = driver.Manage().Timeouts();
timeouts.AsynchronousJavaScript = timeout;
timeouts.ImplicitWait = timeout;
timeouts.PageLoad = timeout;
}
catch (Exception)
{
driver.Dispose();
throw;
}
return driver;
}
}
}
| // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Website
{
using System;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
/// <summary>
/// A factory class for creating instances of <see cref="IWebDriver"/>. This class cannot be inherited.
/// </summary>
internal static class WebDriverFactory
{
/// <summary>
/// Creates a new instance of <see cref="IWebDriver"/>.
/// </summary>
/// <returns>
/// The <see cref="IWebDriver"/> to use for tests.
/// </returns>
public static IWebDriver CreateWebDriver()
{
string chromeDriverDirectory = Path.GetDirectoryName(typeof(WebDriverFactory).Assembly.Location) ?? ".";
var options = new ChromeOptions()
{
AcceptInsecureCertificates = true,
};
if (!System.Diagnostics.Debugger.IsAttached)
{
options.AddArgument("--headless");
}
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
#if DEBUG
options.SetLoggingPreference(LogType.Client, LogLevel.All);
options.SetLoggingPreference(LogType.Driver, LogLevel.All);
options.SetLoggingPreference(LogType.Profiler, LogLevel.All);
options.SetLoggingPreference(LogType.Server, LogLevel.All);
#endif
var driver = new ChromeDriver(chromeDriverDirectory, options, TimeSpan.FromSeconds(15));
try
{
var timeout = TimeSpan.FromSeconds(10);
var timeouts = driver.Manage().Timeouts();
timeouts.AsynchronousJavaScript = timeout;
timeouts.ImplicitWait = timeout;
timeouts.PageLoad = timeout;
}
catch (Exception)
{
driver.Dispose();
throw;
}
return driver;
}
}
}
| apache-2.0 | C# |
54b5eb7a1bfeed0337309b691bdf0ff7620d1e5b | Simplify the HomeController a bit. | rakutensf-malex/slinqy,rakutensf-malex/slinqy | Source/ExampleApp.Web/Controllers/HomeController.cs | Source/ExampleApp.Web/Controllers/HomeController.cs | namespace ExampleApp.Web.Controllers
{
using System.Configuration;
using System.Web.Mvc;
using Microsoft.ServiceBus;
using Models;
/// <summary>
/// Defines supported actions for the Homepage.
/// </summary>
public class HomeController : Controller
{
/// <summary>
/// Handles the default HTTP GET /.
/// </summary>
/// <returns>Returns the default Homepage view.</returns>
public
ActionResult
Index()
{
var serviceBusNamespaceManager = NamespaceManager.CreateFromConnectionString(
ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]
);
this.ViewBag.Title = "Home Page";
this.ViewBag.ServiceBusNamespace = serviceBusNamespaceManager.Address.ToString();
var defaultValues = new CreateQueueCommandModel {
MaxQueueSizeMegabytes = 1024
};
return this.View(defaultValues);
}
/// <summary>
/// Handles the HTTP GET /QueueInformation.
/// </summary>
/// <param name="queueName">Specifies the name of the queue to get information for.</param>
/// <returns>Returns a partial view containing the queues information.</returns>
public
ActionResult
QueueInformation(
string queueName)
{
this.ViewBag.QueueName = queueName;
return this.PartialView("QueueInformation");
}
/// <summary>
/// Handles the HTTP GET /ManageQueue request.
/// </summary>
/// <param name="queueName">Specifies the name of the queue.</param>
/// <returns>Returns a partial view of the queue management UI.</returns>
public
ActionResult
ManageQueue(
string queueName)
{
this.ViewBag.QueueName = queueName;
return this.PartialView("ManageQueue");
}
}
} | namespace ExampleApp.Web.Controllers
{
using System.Configuration;
using System.Web.Mvc;
using Microsoft.ServiceBus;
using Models;
/// <summary>
/// Defines supported actions for the Homepage.
/// </summary>
public class HomeController : Controller
{
/// <summary>
/// Used to manage Service Bus resources.
/// </summary>
private readonly NamespaceManager serviceBusNamespaceManager;
/// <summary>
/// Initializes a new instance of the <see cref="HomeController"/> class.
/// </summary>
public
HomeController()
{
this.serviceBusNamespaceManager = NamespaceManager.CreateFromConnectionString(
ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]
);
}
/// <summary>
/// Handles the default HTTP GET /.
/// </summary>
/// <returns>Returns the default Homepage view.</returns>
public
ActionResult
Index()
{
this.ViewBag.Title = "Home Page";
this.ViewBag.ServiceBusNamespace = this.serviceBusNamespaceManager.Address.ToString();
var defaultValues = new CreateQueueCommandModel {
MaxQueueSizeMegabytes = 1024
};
return this.View(defaultValues);
}
/// <summary>
/// Handles the HTTP GET /QueueInformation.
/// </summary>
/// <param name="queueName">Specifies the name of the queue to get information for.</param>
/// <returns>Returns a partial view containing the queues information.</returns>
public
ActionResult
QueueInformation(
string queueName)
{
this.ViewBag.QueueName = queueName;
return this.PartialView("QueueInformation");
}
/// <summary>
/// Handles the HTTP GET /ManageQueue request.
/// </summary>
/// <param name="queueName">Specifies the name of the queue.</param>
/// <returns>Returns a partial view of the queue management UI.</returns>
public
ActionResult
ManageQueue(
string queueName)
{
this.ViewBag.QueueName = queueName;
return this.PartialView("ManageQueue");
}
}
} | mit | C# |
d6f8554f3560a49b060541d12f339f4c9fadbed4 | Use bit check to avoid garbage with IsInLayer. (#6027) | fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/Tilemaps/Utils/Types.cs | UnityProject/Assets/Scripts/Tilemaps/Utils/Types.cs | using System;
using System.Linq;
using UnityEngine.Serialization;
public enum TileType
{
None,
Wall,
Window,
Floor,
Table,
Object,
Grill,
Base,
WindowDamaged,
Effects,
UnderFloor,
ElectricalCable
}
//If you change numbers, scene layers will mess up
public enum LayerType
{
//None is the same as empty space
[Order(0)] None = 7,
[Order(1)] Effects = 6,
[Order(2)] Walls = 0,
[Order(3)] Windows = 1,
[Order(4)] Grills = 5,
[Order(5)] Tables = 9,
[Order(6)] Objects = 2,
[Order(7)] Floors = 3,
[Order(8)] Underfloor = 8,
[Order(9)] Base = 4,
}
[Flags]
public enum LayerTypeSelection
{
None = 0,
Effects = 1 << 0,
Walls = 1 << 1,
Windows =1 << 2,
Objects = 1 << 3,
Grills = 1 << 4,
Floors = 1 << 5,
Underfloor = 1 << 6,
Base = 1 << 7,
Tables = 1 << 8,
All = ~None
}
/// <summary>
/// Used for converting between LayerType and LayerTypeSelection
/// </summary>
public static class LTSUtil
{
public static bool IsLayerIn(LayerTypeSelection SpecifyLayers, LayerType Layer)
{
LayerTypeSelection LayerCon = LayerType2LayerTypeSelection(Layer);
//Bits are set in SpecifyLayers, doing a logical AND with the layer will return either 0 if it doesn't contain it or the layer bit itself.
return (SpecifyLayers & LayerCon) > 0;
}
public static LayerTypeSelection LayerType2LayerTypeSelection(LayerType Layer)
{
switch (Layer)
{
case LayerType.Effects:
return LayerTypeSelection.Effects;
case LayerType.Walls:
return LayerTypeSelection.Walls;
case LayerType.Windows:
return LayerTypeSelection.Windows;
case LayerType.Grills:
return LayerTypeSelection.Grills;
case LayerType.Objects:
return LayerTypeSelection.Objects;
case LayerType.Floors:
return LayerTypeSelection.Floors;
case LayerType.Underfloor:
return LayerTypeSelection.Underfloor;
case LayerType.Base:
return LayerTypeSelection.Base;
case LayerType.Tables:
return LayerTypeSelection.Tables;
}
return LayerTypeSelection.Base;
}
}
public class OrderAttribute : Attribute
{
public readonly int Order;
public OrderAttribute(int order)
{
Order = order;
}
}
| using System;
using System.Linq;
using UnityEngine.Serialization;
public enum TileType
{
None,
Wall,
Window,
Floor,
Table,
Object,
Grill,
Base,
WindowDamaged,
Effects,
UnderFloor,
ElectricalCable
}
//If you change numbers, scene layers will mess up
public enum LayerType
{
//None is the same as empty space
[Order(0)] None = 7,
[Order(1)] Effects = 6,
[Order(2)] Walls = 0,
[Order(3)] Windows = 1,
[Order(4)] Grills = 5,
[Order(5)] Tables = 9,
[Order(6)] Objects = 2,
[Order(7)] Floors = 3,
[Order(8)] Underfloor = 8,
[Order(9)] Base = 4,
}
[Flags]
public enum LayerTypeSelection
{
None = 0,
Effects = 1 << 0,
Walls = 1 << 1,
Windows =1 << 2,
Objects = 1 << 3,
Grills = 1 << 4,
Floors = 1 << 5,
Underfloor = 1 << 6,
Base = 1 << 7,
Tables = 1 << 8,
All = ~None
}
/// <summary>
/// Used for converting between LayerType and LayerTypeSelection
/// </summary>
public static class LTSUtil
{
public static bool IsLayerIn(LayerTypeSelection SpecifyLayers, LayerType Layer)
{
LayerTypeSelection LayerCon = LayerType2LayerTypeSelection(Layer);
return (SpecifyLayers.HasFlag(LayerCon));
}
public static LayerTypeSelection LayerType2LayerTypeSelection(LayerType Layer)
{
switch (Layer)
{
case LayerType.Effects:
return LayerTypeSelection.Effects;
case LayerType.Walls:
return LayerTypeSelection.Walls;
case LayerType.Windows:
return LayerTypeSelection.Windows;
case LayerType.Grills:
return LayerTypeSelection.Grills;
case LayerType.Objects:
return LayerTypeSelection.Objects;
case LayerType.Floors:
return LayerTypeSelection.Floors;
case LayerType.Underfloor:
return LayerTypeSelection.Underfloor;
case LayerType.Base:
return LayerTypeSelection.Base;
case LayerType.Tables:
return LayerTypeSelection.Tables;
}
return LayerTypeSelection.Base;
}
}
public class OrderAttribute : Attribute
{
public readonly int Order;
public OrderAttribute(int order)
{
Order = order;
}
} | agpl-3.0 | C# |
5b8faa9239aca5b4231412bf412723d744f43e4e | Remove duplicate code. | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Shared/_ShowdownScriptsPartial.cshtml | Anlab.Mvc/Views/Shared/_ShowdownScriptsPartial.cshtml |
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.7.2/showdown.min.js"></script>
<script type="text/javascript">
$(function () {
$('body').tooltip({
selector: '.analysisTooltip'
});
});
</script>
<script type="text/javascript">
function renderTitle(title) {
var converter = new showdown.Converter();
var newContent = converter.makeHtml(title);
$('.analysisTooltip').attr('data-original-title', newContent);
}
</script>
| <environment names="Development">
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.7.2/showdown.min.js"></script>
<script type="text/javascript">
$(function () {
$('body').tooltip({
selector: '.analysisTooltip'
});
});
</script>
<script type="text/javascript">
function renderTitle(title) {
var converter = new showdown.Converter();
var newContent = converter.makeHtml(title);
$('.analysisTooltip').attr('data-original-title', newContent);
}
</script>
</environment>
<environment names="Staging,Production">
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.7.2/showdown.min.js"></script>
<script type="text/javascript">
$(function () {
$('body').tooltip({
selector: '.analysisTooltip'
});
});
</script>
<script type="text/javascript">
function renderTitle(title) {
var converter = new showdown.Converter();
var newContent = converter.makeHtml(title);
$('.analysisTooltip').attr('data-original-title', newContent);
}
</script>
</environment>
| mit | C# |
f5a2211de49c37fe102344390b5e0b23f93c8c42 | Bump version to 3.0.0 | Brightspace/D2L.Security.OAuth2 | D2L.Security.OAuth2.WebApi/Properties/AssemblyInfo.cs | D2L.Security.OAuth2.WebApi/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Nuget: Title
[assembly: AssemblyTitle( "D2L Security For Web API" )]
// Nuget: Description
[assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )]
// Nuget: Author
[assembly: AssemblyCompany( "Desire2Learn" )]
// Nuget: Owners
[assembly: AssemblyProduct( "Brightspace" )]
// Nuget: Version
[assembly: AssemblyInformationalVersion( "3.0.0.0" )]
[assembly: AssemblyVersion( "3.0.0.0" )]
[assembly: AssemblyFileVersion( "3.0.0.0" )]
[assembly: AssemblyCopyright( "Copyright © Desire2Learn" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )] | using System.Reflection;
using System.Runtime.CompilerServices;
// Nuget: Title
[assembly: AssemblyTitle( "D2L Security For Web API" )]
// Nuget: Description
[assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )]
// Nuget: Author
[assembly: AssemblyCompany( "Desire2Learn" )]
// Nuget: Owners
[assembly: AssemblyProduct( "Brightspace" )]
// Nuget: Version
[assembly: AssemblyInformationalVersion( "2.4.0.0" )]
[assembly: AssemblyVersion( "2.4.0.0" )]
[assembly: AssemblyFileVersion( "2.4.0.0" )]
[assembly: AssemblyCopyright( "Copyright © Desire2Learn" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )] | apache-2.0 | C# |
451af0a3a734169d6499247426225865e1be0762 | Fix ImageViewBackend sizing issue | TheBrainTech/xwt,lytico/xwt,hamekoz/xwt,hwthomas/xwt,mono/xwt,mminns/xwt,directhex/xwt,steffenWi/xwt,akrisiun/xwt,residuum/xwt,mminns/xwt,sevoku/xwt,cra0zy/xwt,iainx/xwt,antmicro/xwt | Xwt.Mac/Xwt.Mac/ImageViewBackend.cs | Xwt.Mac/Xwt.Mac/ImageViewBackend.cs | //
// ImageViewBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class ImageViewBackend: ViewBackend<NSImageView,IWidgetEventSink>, IImageViewBackend
{
public ImageViewBackend ()
{
}
public override void Initialize ()
{
base.Initialize ();
ViewObject = new CustomNSImageView ();
}
protected override Size GetNaturalSize ()
{
NSImage img = Widget.Image;
return img == null ? Size.Zero : img.Size.ToXwtSize ();
}
public void SetImage (Image image)
{
if (image == null)
throw new ArgumentNullException ("nativeImage");
NSImage nativeImage = Toolkit.GetBackend (image) as NSImage;
if (nativeImage == null)
nativeImage = Toolkit.GetBackend (image.ToBitmap ()) as NSImage;
if (nativeImage == null)
throw new ArgumentException ("nativeImage is not of the expected type", "nativeImage");
Widget.Image = nativeImage;
Widget.SetFrameSize (Widget.Image.Size);
}
}
class CustomNSImageView: NSImageView, IViewObject
{
public NSView View {
get {
return this;
}
}
public ViewBackend Backend { get; set; }
}
}
| //
// ImageViewBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class ImageViewBackend: ViewBackend<NSImageView,IWidgetEventSink>, IImageViewBackend
{
public ImageViewBackend ()
{
}
public override void Initialize ()
{
base.Initialize ();
ViewObject = new CustomNSImageView ();
}
public void SetImage (Image image)
{
if (image == null)
throw new ArgumentNullException ("nativeImage");
NSImage nativeImage = Toolkit.GetBackend (image) as NSImage;
if (nativeImage == null)
nativeImage = Toolkit.GetBackend (image.ToBitmap ()) as NSImage;
if (nativeImage == null)
throw new ArgumentException ("nativeImage is not of the expected type", "nativeImage");
Widget.Image = nativeImage;
Widget.SetFrameSize (Widget.Image.Size);
}
}
class CustomNSImageView: NSImageView, IViewObject
{
public NSView View {
get {
return this;
}
}
public ViewBackend Backend { get; set; }
}
}
| mit | C# |
252b8868a13ee8ac65a6aee1d1d0cb54f8ddf61e | Remove useless case clause | xavierfoucrier/gmail-notifier,xavierfoucrier/gmail-notifier | code/Program.cs | code/Program.cs | using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using notifier.Languages;
using notifier.Properties;
namespace notifier {
static class Program {
#region #attributes
/// <summary>
/// Mutex associated to the application instance
/// </summary>
static Mutex Mutex = new Mutex(true, "gmailnotifier-115e363ecbfefd771e55c6874680bc0a");
#endregion
#region #methods
[STAThread]
static void Main(string[] args) {
// initialize the configuration file with setup installer settings
if (args.Length == 3 && args[0] == "install") {
// language application setting
switch (args[1]) {
default:
Settings.Default.Language = "English";
break;
case "fr":
Settings.Default.Language = "Français";
break;
case "de":
Settings.Default.Language = "Deutsch";
break;
}
// start with Windows setting
Settings.Default.RunAtWindowsStartup = args[2] == "auto";
// commit changes to the configuration file
Settings.Default.Save();
return;
}
// initialize the interface with the specified culture, depending on the user settings
switch (Settings.Default.Language) {
default:
CultureInfo.CurrentUICulture = new CultureInfo("en-US");
break;
case "Français":
CultureInfo.CurrentUICulture = new CultureInfo("fr-FR");
break;
case "Deutsch":
CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
break;
}
// check if there is an instance running
if (!Mutex.WaitOne(TimeSpan.Zero, true)) {
MessageBox.Show(Translation.mutexError, Translation.multipleInstances, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// set some default properties
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// set the process priority to "low"
Process process = Process.GetCurrentProcess();
process.PriorityClass = ProcessPriorityClass.BelowNormal;
// run the main window
Application.Run(new Main());
// release the mutex instance
Mutex.ReleaseMutex();
}
#endregion
#region #accessors
#endregion
}
} | using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using notifier.Languages;
using notifier.Properties;
namespace notifier {
static class Program {
#region #attributes
/// <summary>
/// Mutex associated to the application instance
/// </summary>
static Mutex Mutex = new Mutex(true, "gmailnotifier-115e363ecbfefd771e55c6874680bc0a");
#endregion
#region #methods
[STAThread]
static void Main(string[] args) {
// initialize the configuration file with setup installer settings
if (args.Length == 3 && args[0] == "install") {
// language application setting
switch (args[1]) {
default:
case "en":
Settings.Default.Language = "English";
break;
case "fr":
Settings.Default.Language = "Français";
break;
case "de":
Settings.Default.Language = "Deutsch";
break;
}
// start with Windows setting
Settings.Default.RunAtWindowsStartup = args[2] == "auto";
// commit changes to the configuration file
Settings.Default.Save();
return;
}
// initialize the interface with the specified culture, depending on the user settings
switch (Settings.Default.Language) {
default:
CultureInfo.CurrentUICulture = new CultureInfo("en-US");
break;
case "Français":
CultureInfo.CurrentUICulture = new CultureInfo("fr-FR");
break;
case "Deutsch":
CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
break;
}
// check if there is an instance running
if (!Mutex.WaitOne(TimeSpan.Zero, true)) {
MessageBox.Show(Translation.mutexError, Translation.multipleInstances, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// set some default properties
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// set the process priority to "low"
Process process = Process.GetCurrentProcess();
process.PriorityClass = ProcessPriorityClass.BelowNormal;
// run the main window
Application.Run(new Main());
// release the mutex instance
Mutex.ReleaseMutex();
}
#endregion
#region #accessors
#endregion
}
} | mit | C# |
4012a3080dee599434f25a4c13d54941adbdb88f | fix bug in script command | sethreno/schemazen,ruediger-stevens/schemazen,keith-hall/schemazen,Zocdoc/schemazen,sethreno/schemazen | console/Script.cs | console/Script.cs | using System;
using System.IO;
using model;
namespace console {
public class Script : ICommand {
private DataArg data;
private bool delete;
private Operand destination;
private Operand source;
public bool Parse(string[] args) {
if (args.Length < 3) {
return false;
}
source = Operand.Parse(args[1]);
destination = Operand.Parse(args[2]);
data = DataArg.Parse(args);
foreach (string arg in args) {
if (arg.ToLower() == "-d") delete = true;
}
if (source == null || destination == null) return false;
if (source.OpType != OpType.Database) return false;
if (destination.OpType != OpType.ScriptDir) return false;
return true;
}
public string GetUsageText() {
return @"script <source> <destination> [-d]
Generate scripts for the specified database.
<source> The connection string to the database to script.
Example:
""server=localhost;database=DEVDB;Trusted_Connection=yes;""
<destination> Path to the directory where scripts will be created
-d Delete existing scripts without prompt.
";
}
public bool Run() {
// load the model
var db = new Database();
db.Connection = source.Value;
db.Dir = destination.Value;
db.Load();
// generate scripts
if (!delete && Directory.Exists(destination.Value)) {
Console.Write("{0} already exists do you want to replace it? (Y/N)", destination.Value);
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key != ConsoleKey.Y) {
return false;
}
Console.WriteLine();
}
if (data != null) {
foreach (string pattern in data.Value.Split(',')) {
if (string.IsNullOrEmpty(pattern)) {
continue;
}
foreach (Table t in db.FindTablesRegEx(pattern)) {
db.DataTables.Add(t);
}
}
}
db.ScriptToDir(delete);
Console.WriteLine("Snapshot successfully created at " + destination.Value);
return true;
}
}
} | using System;
using System.IO;
using model;
namespace console {
public class Script : ICommand {
private DataArg data;
private bool delete;
private Operand destination;
private Operand source;
public bool Parse(string[] args) {
if (args.Length < 3) {
return false;
}
source = Operand.Parse(args[1]);
if (!args[2].ToLower().StartsWith("dir:")) {
args[2] = "dir:" + args[2];
}
destination = Operand.Parse(args[2]);
data = DataArg.Parse(args);
foreach (string arg in args) {
if (arg.ToLower() == "-d") delete = true;
}
if (source == null || destination == null) return false;
if (source.OpType != OpType.Database) return false;
if (destination.OpType != OpType.ScriptDir) return false;
return true;
}
public string GetUsageText() {
return @"script <source> <destination> [-d]
Generate scripts for the specified database.
<source> The connection string to the database to script.
Example:
""server=localhost;database=DEVDB;Trusted_Connection=yes;""
<destination> Path to the directory where scripts will be created
-d Delete existing scripts without prompt.
";
}
public bool Run() {
// load the model
var db = new Database();
db.Connection = source.Value;
db.Dir = destination.Value;
db.Load();
// generate scripts
if (!delete && Directory.Exists(destination.Value)) {
Console.Write("{0} already exists do you want to replace it? (Y/N)", destination.Value);
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key != ConsoleKey.Y) {
return false;
}
Console.WriteLine();
}
if (data != null) {
foreach (string pattern in data.Value.Split(',')) {
if (string.IsNullOrEmpty(pattern)) {
continue;
}
foreach (Table t in db.FindTablesRegEx(pattern)) {
db.DataTables.Add(t);
}
}
}
db.ScriptToDir(delete);
Console.WriteLine("Snapshot successfully created at " + destination.Value);
return true;
}
}
} | mit | C# |
2300607bae189811aff4533208aef1218611fbec | Bump version 1.4.1.0 | rhythmagency/formulate,rhythmagency/formulate,rhythmagency/formulate | src/formulate.meta/Constants.cs | src/formulate.meta/Constants.cs | namespace formulate.meta
{
/// <summary>
/// Constants relating to Formulate itself (i.e., does not
/// include constants used by Formulate).
/// </summary>
public class Constants
{
/// <summary>
/// This is the version of Formulate. It is used on
/// assemblies and during the creation of the
/// installer package.
/// </summary>
/// <remarks>
/// Do not reformat this code. A grunt task reads this
/// version number with a regular expression.
/// </remarks>
public const string Version = "1.4.1.0";
/// <summary>
/// The name of the Formulate package.
/// </summary>
public const string PackageName = "Formulate";
/// <summary>
/// The name of the Formulate package, in camel case.
/// </summary>
public const string PackageNameCamelCase = "formulate";
}
} | namespace formulate.meta
{
/// <summary>
/// Constants relating to Formulate itself (i.e., does not
/// include constants used by Formulate).
/// </summary>
public class Constants
{
/// <summary>
/// This is the version of Formulate. It is used on
/// assemblies and during the creation of the
/// installer package.
/// </summary>
/// <remarks>
/// Do not reformat this code. A grunt task reads this
/// version number with a regular expression.
/// </remarks>
public const string Version = "1.4.0.0";
/// <summary>
/// The name of the Formulate package.
/// </summary>
public const string PackageName = "Formulate";
/// <summary>
/// The name of the Formulate package, in camel case.
/// </summary>
public const string PackageNameCamelCase = "formulate";
}
} | mit | C# |
13aa391f4c505bf16dcb6331c4f0f5faf8cee83a | make random once | Cologler/jasily.cologler | Jasily.Core/RandomExtensions.cs | Jasily.Core/RandomExtensions.cs | using System.Collections.Generic;
using System.Linq;
namespace System
{
public static class RandomExtensions
{
private static Random randomNumberGenerator;
public static Random RandomNumberGenerator
=> randomNumberGenerator ?? (randomNumberGenerator = new Random());
#region extension for collection
public static T Random<T>(this T[] t, Random random = null)
{
if (t.Length == 0) return default(T);
if (t.Length == 1) return t[0];
random = random ?? RandomNumberGenerator;
return t[random.Next(t.Length)];
}
public static T Random<T>(this IList<T> t, Random random = null)
{
if (t.Count == 0) return default(T);
if (t.Count == 1) return t[0];
random = random ?? RandomNumberGenerator;
return t[random.Next(t.Count)];
}
public static IEnumerable<T> RandomSort<T>(this IEnumerable<T> source, Random random = null)
{
var array = source.ToArray();
var count = array.Length;
random = random ?? RandomNumberGenerator;
while (count > 0)
{
var index = random.Next(count);
yield return array[index];
array[index] = array[count - 1];
array[count - 1] = default(T);
count--;
}
}
#endregion
public static byte[] NextBytes(this Random random, int byteCount)
{
var buffer = new byte[byteCount];
random.NextBytes(buffer);
return buffer;
}
public static int NextInt32(this Random random) => BitConverter.ToInt32(random.NextBytes(4), 0);
public static long NextInt64(this Random random) => BitConverter.ToInt64(random.NextBytes(8), 0);
}
} | using System.Collections.Generic;
using System.Linq;
namespace System
{
public static class RandomExtensions
{
public static T Random<T>(this T[] t)
{
if (t.Length == 0) return default(T);
if (t.Length == 1) return t[0];
return t[new Random().Next(t.Length)];
}
public static T Random<T>(this IList<T> t)
{
if (t.Count == 0) return default(T);
if (t.Count == 1) return t[0];
return t[new Random().Next(t.Count)];
}
public static IEnumerable<T> RandomSort<T>(this IEnumerable<T> source)
{
var array = source.ToArray();
var count = array.Length;
var random = new Random();
while (count > 0)
{
var index = random.Next(count);
yield return array[index];
array[index] = array[count - 1];
array[count - 1] = default(T);
count--;
}
}
public static byte[] NextBytes(this Random random, int byteCount)
{
var buffer = new byte[byteCount];
random.NextBytes(buffer);
return buffer;
}
public static long NextInt32(Random random) => BitConverter.ToInt32(random.NextBytes(4), 0);
public static long NextInt64(Random random) => BitConverter.ToInt64(random.NextBytes(8), 0);
}
} | mit | C# |
9e477140c1ca3e8c012ea2ca4d805886fcbc0948 | Build against netcoreapp2.1 instead of net471 | naoey/osu,2yangk23/osu,smoogipoo/osu,UselessToucan/osu,DrabWeb/osu,NeoAdonis/osu,ZLima12/osu,naoey/osu,2yangk23/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,ppy/osu,johnneijzen/osu,DrabWeb/osu,naoey/osu,DrabWeb/osu,ppy/osu,peppy/osu-new,EVAST9919/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ZLima12/osu,smoogipoo/osu,smoogipooo/osu,EVAST9919/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu | build.cake | build.cake | #tool "nuget:?package=JetBrains.ReSharper.CommandLineTools"
#tool "nuget:?package=NVika.MSBuild"
var NVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First();
var CodeFileSanityToolPath = DownloadFile("https://github.com/peppy/CodeFileSanity/releases/download/v0.2.5/CodeFileSanity.exe");
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "Build");
var framework = Argument("framework", "netcoreapp2.1");
var configuration = Argument("configuration", "Release");
var osuDesktop = new FilePath("./osu.Desktop/osu.Desktop.csproj");
var osuSolution = new FilePath("./osu.sln");
var testProjects = GetFiles("**/*.Tests.csproj");
///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Compile")
.Does(() => {
DotNetCoreBuild(osuDesktop.FullPath, new DotNetCoreBuildSettings {
Framework = framework,
Configuration = configuration
});
});
Task("Test")
.ContinueOnError()
.DoesForEach(testProjects, testProject => {
DotNetCoreTest(testProject.FullPath, new DotNetCoreTestSettings {
Framework = framework,
Configuration = configuration,
Logger = $"trx;LogFileName={testProject.GetFilename()}.trx",
ResultsDirectory = "./TestResults/"
});
});
Task("Restore Nuget")
.Does(() => NuGetRestore(osuSolution));
Task("InspectCode")
.IsDependentOn("Restore Nuget")
.Does(() => {
InspectCode(osuSolution, new InspectCodeSettings {
CachesHome = "inspectcode",
OutputFile = "inspectcodereport.xml",
});
StartProcess(NVikaToolPath, @"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors");
});
Task("CodeFileSanity")
.Does(() => {
var result = StartProcess(CodeFileSanityToolPath);
if (result != 0)
throw new Exception("Code sanity failed.");
});
Task("Build")
.IsDependentOn("CodeFileSanity")
.IsDependentOn("Compile")
.IsDependentOn("InspectCode")
.IsDependentOn("Test");
RunTarget(target); | #tool "nuget:?package=JetBrains.ReSharper.CommandLineTools"
#tool "nuget:?package=NVika.MSBuild"
var NVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First();
var CodeFileSanityToolPath = DownloadFile("https://github.com/peppy/CodeFileSanity/releases/download/v0.2.5/CodeFileSanity.exe");
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "Build");
var framework = Argument("framework", "net471");
var configuration = Argument("configuration", "Release");
var osuDesktop = new FilePath("./osu.Desktop/osu.Desktop.csproj");
var osuSolution = new FilePath("./osu.sln");
var testProjects = GetFiles("**/*.Tests.csproj");
///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Compile")
.Does(() => {
DotNetCoreBuild(osuDesktop.FullPath, new DotNetCoreBuildSettings {
Framework = framework,
Configuration = configuration
});
});
Task("Test")
.ContinueOnError()
.DoesForEach(testProjects, testProject => {
DotNetCoreTest(testProject.FullPath, new DotNetCoreTestSettings {
Framework = framework,
Configuration = configuration,
Logger = $"trx;LogFileName={testProject.GetFilename()}.trx",
ResultsDirectory = "./TestResults/"
});
});
Task("Restore Nuget")
.Does(() => NuGetRestore(osuSolution));
Task("InspectCode")
.IsDependentOn("Restore Nuget")
.Does(() => {
InspectCode(osuSolution, new InspectCodeSettings {
CachesHome = "inspectcode",
OutputFile = "inspectcodereport.xml",
});
StartProcess(NVikaToolPath, @"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors");
});
Task("CodeFileSanity")
.Does(() => {
var result = StartProcess(CodeFileSanityToolPath);
if (result != 0)
throw new Exception("Code sanity failed.");
});
Task("Build")
.IsDependentOn("CodeFileSanity")
.IsDependentOn("Compile")
.IsDependentOn("InspectCode")
.IsDependentOn("Test");
RunTarget(target); | mit | C# |
24c8b0059d7b9e2852dc0e900b3f6d7a86309907 | update version | IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates | build.cake | build.cake | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var buildArtifacts = Directory("./artifacts/packages");
var packageVersion = "2.2.1";
///////////////////////////////////////////////////////////////////////////////
// Clean
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[]
{
buildArtifacts,
Directory("./feed/content/UI")
});
});
///////////////////////////////////////////////////////////////////////////////
// Copy
///////////////////////////////////////////////////////////////////////////////
Task("Copy")
.IsDependentOn("Clean")
.Does(() =>
{
CreateDirectory("./feed/content");
// copy the singel csproj templates
var files = GetFiles("./src/**/*.*");
CopyFiles(files, "./feed/content", true);
// copy the UI files
files = GetFiles("./ui/**/*.*");
CopyFiles(files, "./feed/content/ui", true);
});
///////////////////////////////////////////////////////////////////////////////
// Pack
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Clean")
.IsDependentOn("Copy")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = packageVersion,
OutputDirectory = buildArtifacts
};
if (AppVeyor.IsRunningOnAppVeyor)
{
settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings);
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target); | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var buildArtifacts = Directory("./artifacts/packages");
var packageVersion = "2.2.0";
///////////////////////////////////////////////////////////////////////////////
// Clean
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[]
{
buildArtifacts,
Directory("./feed/content/UI")
});
});
///////////////////////////////////////////////////////////////////////////////
// Copy
///////////////////////////////////////////////////////////////////////////////
Task("Copy")
.IsDependentOn("Clean")
.Does(() =>
{
CreateDirectory("./feed/content");
// copy the singel csproj templates
var files = GetFiles("./src/**/*.*");
CopyFiles(files, "./feed/content", true);
// copy the UI files
files = GetFiles("./ui/**/*.*");
CopyFiles(files, "./feed/content/ui", true);
});
///////////////////////////////////////////////////////////////////////////////
// Pack
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Clean")
.IsDependentOn("Copy")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = packageVersion,
OutputDirectory = buildArtifacts
};
if (AppVeyor.IsRunningOnAppVeyor)
{
settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings);
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target); | apache-2.0 | C# |
e07b1085591e318cc2efc9a83e401afdc94ff35b | Add Splat.Drawing to the cake build | paulcbetts/splat | build.cake | build.cake | #load nuget:https://pkgs.dev.azure.com/dotnet/ReactiveUI/_packaging/ReactiveUI/nuget/v3/index.json?package=ReactiveUI.Cake.Recipe&prerelease
Environment.SetVariableNames();
// Whitelisted Packages
var packageWhitelist = new[]
{
MakeAbsolute(File("./src/Splat/Splat.csproj")),
MakeAbsolute(File("./src/Splat.Autofac/Splat.Autofac.csproj")),
MakeAbsolute(File("./src/Splat.DryIoc/Splat.DryIoc.csproj")),
MakeAbsolute(File("./src/Splat.Log4Net/Splat.Log4Net.csproj")),
MakeAbsolute(File("./src/Splat.Microsoft.Extensions.DependencyInjection/Splat.Microsoft.Extensions.DependencyInjection.csproj")),
MakeAbsolute(File("./src/Splat.Microsoft.Extensions.Logging/Splat.Microsoft.Extensions.Logging.csproj")),
MakeAbsolute(File("./src/Splat.Ninject/Splat.Ninject.csproj")),
MakeAbsolute(File("./src/Splat.NLog/Splat.NLog.csproj")),
MakeAbsolute(File("./src/Splat.Serilog/Splat.Serilog.csproj")),
MakeAbsolute(File("./src/Splat.SimpleInjector/Splat.SimpleInjector.csproj")),
MakeAbsolute(File("./src/Splat.Drawing/Splat.Drawing.csproj")),
};
var packageTestWhitelist = new[]
{
MakeAbsolute(File("./src/Splat.Tests/Splat.Tests.csproj")),
MakeAbsolute(File("./src/Splat.Autofac.Tests/Splat.Autofac.Tests.csproj")),
MakeAbsolute(File("./src/Splat.DryIoc.Tests/Splat.DryIoc.Tests.csproj")),
MakeAbsolute(File("./src/Splat.Microsoft.Extensions.DependencyInjection.Tests/Splat.Microsoft.Extensions.DependencyInjection.Tests.csproj")),
MakeAbsolute(File("./src/Splat.Ninject.Tests/Splat.Ninject.Tests.csproj")),
MakeAbsolute(File("./src/Splat.SimpleInjector.Tests/Splat.SimpleInjector.Tests.csproj")),
};
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
title: "Splat",
whitelistPackages: packageWhitelist,
whitelistTestPackages: packageTestWhitelist,
artifactsDirectory: "./artifacts",
sourceDirectory: "./src");
ToolSettings.SetToolSettings(context: Context, usePrereleaseMsBuild: true);
Build.Run();
| #load nuget:https://pkgs.dev.azure.com/dotnet/ReactiveUI/_packaging/ReactiveUI/nuget/v3/index.json?package=ReactiveUI.Cake.Recipe&prerelease
Environment.SetVariableNames();
// Whitelisted Packages
var packageWhitelist = new[]
{
MakeAbsolute(File("./src/Splat/Splat.csproj")),
MakeAbsolute(File("./src/Splat.Autofac/Splat.Autofac.csproj")),
MakeAbsolute(File("./src/Splat.DryIoc/Splat.DryIoc.csproj")),
MakeAbsolute(File("./src/Splat.Log4Net/Splat.Log4Net.csproj")),
MakeAbsolute(File("./src/Splat.Microsoft.Extensions.DependencyInjection/Splat.Microsoft.Extensions.DependencyInjection.csproj")),
MakeAbsolute(File("./src/Splat.Microsoft.Extensions.Logging/Splat.Microsoft.Extensions.Logging.csproj")),
MakeAbsolute(File("./src/Splat.Ninject/Splat.Ninject.csproj")),
MakeAbsolute(File("./src/Splat.NLog/Splat.NLog.csproj")),
MakeAbsolute(File("./src/Splat.Serilog/Splat.Serilog.csproj")),
MakeAbsolute(File("./src/Splat.SimpleInjector/Splat.SimpleInjector.csproj")),
};
var packageTestWhitelist = new[]
{
MakeAbsolute(File("./src/Splat.Tests/Splat.Tests.csproj")),
MakeAbsolute(File("./src/Splat.Autofac.Tests/Splat.Autofac.Tests.csproj")),
MakeAbsolute(File("./src/Splat.DryIoc.Tests/Splat.DryIoc.Tests.csproj")),
MakeAbsolute(File("./src/Splat.Microsoft.Extensions.DependencyInjection.Tests/Splat.Microsoft.Extensions.DependencyInjection.Tests.csproj")),
MakeAbsolute(File("./src/Splat.Ninject.Tests/Splat.Ninject.Tests.csproj")),
MakeAbsolute(File("./src/Splat.SimpleInjector.Tests/Splat.SimpleInjector.Tests.csproj")),
};
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
title: "Splat",
whitelistPackages: packageWhitelist,
whitelistTestPackages: packageTestWhitelist,
artifactsDirectory: "./artifacts",
sourceDirectory: "./src");
ToolSettings.SetToolSettings(context: Context, usePrereleaseMsBuild: true);
Build.Run();
| mit | C# |
cadfaa4593147e89c2b9f44c3a14655c2cea0d8b | Add Subarray extension methods | IvionSauce/MeidoBot | MeidoCommon/ExtensionMethods.cs | MeidoCommon/ExtensionMethods.cs | using System;
using System.Linq;
using System.Collections.Generic;
namespace MeidoCommon.ExtensionMethods
{
public static class ExtensionMethods
{
public static IEnumerable<T> NoNull<T>(this IEnumerable<T> seq) where T : class
{
if (seq != null)
return seq.Where(el => el != null);
else
return Enumerable.Empty<T>();
}
public static T[] Subarray<T>(this IList<T> items, int start)
{
if (items == null)
throw new ArgumentNullException(nameof(items));
if (start > items.Count)
throw new ArgumentOutOfRangeException(nameof(start), "Cannot be greater than items' count.");
return Subarray(items, start, items.Count - start);
}
public static T[] Subarray<T>(this IList<T> items, int start, int count)
{
if (items == null)
throw new ArgumentNullException(nameof(items));
if (start < 0)
throw new ArgumentOutOfRangeException(nameof(start), "Cannot be negative.");
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), "Cannot be negative.");
if ( (start + count) > items.Count )
throw new ArgumentException("Requested range would go out of bounds.");
// Early return.
if (count == 0)
return Array.Empty<T>();
var retval = new T[count];
// If items is actually an array use the efficient Array.Copy.
if (items is T[] arr)
{
Array.Copy(arr, start, retval, 0, count);
}
else
{
for (int i = 0; i < count; i++)
{
retval[i] = items[start + i];
}
}
return retval;
}
}
} | using System.Linq;
using System.Collections.Generic;
namespace MeidoCommon.ExtensionMethods
{
public static class ExtensionMethods
{
public static IEnumerable<T> NoNull<T>(this IEnumerable<T> seq) where T : class
{
if (seq != null)
return seq.Where(el => el != null);
else
return Enumerable.Empty<T>();
}
}
} | bsd-2-clause | C# |
0d5d3ccdb0152b74434e26260f42b2736efcbe45 | Use List | ASP-NET-Core-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,RehanSaeed/ASP.NET-MVC-Boilerplate | Source/Boilerplate.Templates/Content/ApiTemplate/ViewModels/PageResult.cs | Source/Boilerplate.Templates/Content/ApiTemplate/ViewModels/PageResult.cs | namespace ApiTemplate.ViewModels
{
using System.Collections.Generic;
#if (Swagger)
using ApiTemplate.ViewModelSchemaFilters;
using Swashbuckle.AspNetCore.SwaggerGen;
[SwaggerSchemaFilter(typeof(PageResultCarSchemaFilter))]
#endif
public class PageResult<T>
where T : class
{
public int Page { get; set; }
public int Count { get; set; }
public bool HasNextPage { get => this.Page < this.TotalPages; }
public bool HasPreviousPage { get => this.Page > 1; }
public int TotalCount { get; set; }
public int TotalPages { get; set; }
public List<T> Items { get; set; }
}
}
| namespace ApiTemplate.ViewModels
{
using System.Collections.Generic;
#if (Swagger)
using ApiTemplate.ViewModelSchemaFilters;
using Swashbuckle.AspNetCore.SwaggerGen;
[SwaggerSchemaFilter(typeof(PageResultCarSchemaFilter))]
#endif
public class PageResult<T>
where T : class
{
public int Page { get; set; }
public int Count { get; set; }
public bool HasNextPage { get => this.Page < this.TotalPages; }
public bool HasPreviousPage { get => this.Page > 1; }
public int TotalCount { get; set; }
public int TotalPages { get; set; }
public IEnumerable<T> Items { get; set; }
}
}
| mit | C# |
0a0b5d2177f37e12efecd6d27bda1efcd5187c3d | Add links to photo details and question details views. | dsteinweg/TeacherPouch,dsteinweg/TeacherPouch,dsteinweg/TeacherPouch,dsteinweg/TeacherPouch | TeacherPouch.Web/Views/Questions/QuestionIndex.cshtml | TeacherPouch.Web/Views/Questions/QuestionIndex.cshtml | @model QuestionIndexViewModel
@{
ViewBag.Title = "Question Index";
}
<h2>Question Index</h2>
@if (Model.Questions.SafeAny())
{
<table class="index">
<thead>
<tr>
<th>ID</th>
<th>Photo ID</th>
<th>Question</th>
<th>Sentence Starters</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var question in Model.Questions)
{
<tr>
<td>@question.ID</td>
<td>@Html.ActionLink(question.PhotoID.ToString(), MVC.Photos.PhotoDetails(question.PhotoID))</td>
<td>@Html.ActionLink(question.Text, MVC.Questions.QuestionDetails(question.ID))</td>
<td>@question.SentenceStarters</td>
<td>
@if (Model.DisplayAdminLinks)
{
<span>
@Html.ActionLink("Details", MVC.Questions.QuestionDetails(question.ID)) |
@Html.ActionLink("Edit", MVC.Questions.QuestionEdit(question.ID)) |
@Html.ActionLink("Delete", MVC.Questions.QuestionDelete(question.ID))
</span>
}
</td>
</tr>
}
</tbody>
</table>
}
else
{
@:No questions found.
}
| @model QuestionIndexViewModel
@{
ViewBag.Title = "Question Index";
}
<h2>Question Index</h2>
@if (Model.Questions.SafeAny())
{
<table class="index">
<thead>
<tr>
<th>ID</th>
<th>Photo ID</th>
<th>Question</th>
<th>Sentence Starters</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var question in Model.Questions)
{
<tr>
<td>@question.ID</td>
<td>@question.PhotoID</td>
<td>@question.Text</td>
<td>@question.SentenceStarters</td>
<td>
@if (Model.DisplayAdminLinks)
{
<span>
@Html.ActionLink("Details", MVC.Questions.QuestionDetails(question.ID)) |
@Html.ActionLink("Edit", MVC.Questions.QuestionEdit(question.ID)) |
@Html.ActionLink("Delete", MVC.Questions.QuestionDelete(question.ID))
</span>
}
</td>
</tr>
}
</tbody>
</table>
}
else
{
@:No questions found.
}
| mit | C# |
c375dafd76b9a628b85c08d1d578b91dc1ba661c | change type of PrefsParam.all Dictionary to List | fuqunaga/PrefsGUI | Runtime/PrefsParam/PrefsParam.cs | Runtime/PrefsParam/PrefsParam.cs | using PrefsGUI.KVS;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace PrefsGUI
{
/// <summary>
/// Origin of Prefs*
/// </summary>
public abstract class PrefsParam : ISerializationCallbackReceiver
{
public static Color syncedColor = new Color32(255, 143, 63, 255);
public string key;
public PrefsParam(string key)
{
this.key = key;
Regist();
}
public virtual void Delete() { PrefsKVS.DeleteKey(key); }
#region abstract
public abstract Type GetInnerType();
public abstract object GetObject();
public abstract void SetSyncedObject(object obj, Action onIfAlreadyGet);
public abstract bool DoGUI(string label = null);
public abstract bool IsDefault { get; }
public abstract void SetCurrentToDefault();
#endregion
#region RegistAllInstance
public static readonly List<PrefsParam> all = new List<PrefsParam>();
public static readonly Dictionary<string, PrefsParam> allDic = new Dictionary<string, PrefsParam>();
public void OnBeforeSerialize() { }
public void OnAfterDeserialize() { Regist(); } // To Regist Array/List In Inspector. Constructor not called.
void Regist()
{
if ( allDic.TryGetValue(key, out var prev) )
{
all.Remove(prev);
}
allDic[key] = this;
all.Add(this);
}
#endregion
}
} | using PrefsGUI.KVS;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace PrefsGUI
{
/// <summary>
/// Origin of Prefs*
/// </summary>
public abstract class PrefsParam : ISerializationCallbackReceiver
{
public string key;
public static Color syncedColor = new Color32(255, 143, 63, 255);
public static bool enableWarning = true;
public PrefsParam(string key)
{
this.key = key;
Regist();
}
public virtual void Delete() { PrefsKVS.DeleteKey(key); }
#region abstract
public abstract Type GetInnerType();
public abstract object GetObject();
public abstract void SetSyncedObject(object obj, Action onIfAlreadyGet);
public abstract bool DoGUI(string label = null);
public abstract bool IsDefault { get; }
public abstract void SetCurrentToDefault();
#endregion
#region RegistAllInstance
public static Dictionary<string, PrefsParam> all = new Dictionary<string, PrefsParam>();
public void OnBeforeSerialize() { }
public void OnAfterDeserialize() { Regist(); } // To Regist Array/List In Inspector. Constructor not called.
void Regist() { all[key] = this; }
#endregion
}
} | mit | C# |
956a5afc666252a26487f99ccdbc27ed01a47f81 | Update the EthernetDevice to have the latest set of functions | shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg | trunk/src/bindings/EthernetDevice.cs | trunk/src/bindings/EthernetDevice.cs |
using System;
using System.Runtime.InteropServices;
namespace TAPCfg {
public class EthernetDevice : IDisposable {
private const int MTU = 1522;
private IntPtr handle;
private bool disposed = false;
public EthernetDevice() {
handle = tapcfg_init();
}
public void Start() {
tapcfg_start(handle);
}
public byte[] Read() {
int length;
byte[] buffer = new byte[MTU];
length = tapcfg_read(handle, buffer, buffer.Length);
byte[] outbuf = new byte[length];
Array.Copy(buffer, 0, outbuf, 0, length);
return outbuf;
}
public void Write(byte[] data) {
byte[] buffer = new byte[MTU];
Array.Copy(data, 0, buffer, 0, data.Length);
int ret = tapcfg_write(handle, buffer, data.Length);
}
public void Enabled(bool enabled) {
if (enabled)
tapcfg_iface_change_status(handle, 1);
else
tapcfg_iface_change_status(handle, 0);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (!disposed) {
if (disposing) {
// Managed resources can be disposed here
}
tapcfg_stop(handle);
tapcfg_destroy(handle);
handle = IntPtr.Zero;
disposed = true;
}
}
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start();
dev.Enabled(true);
System.Threading.Thread.Sleep(100000);
}
[DllImport("libtapcfg")]
private static extern IntPtr tapcfg_init();
[DllImport("libtapcfg")]
private static extern void tapcfg_destroy(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_start(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern void tapcfg_stop(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_can_read(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_read(IntPtr tapcfg, byte[] buf, int count);
[DllImport("libtapcfg")]
private static extern int tapcfg_can_write(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_write(IntPtr tapcfg, byte[] buf, int count);
[DllImport("libtapcfg")]
private static extern string tapcfg_get_ifname(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_get_status(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_change_status(IntPtr tapcfg, int enabled);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_set_ipv4(IntPtr tapcfg, string addr, Byte netbits);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_set_ipv6(IntPtr tapcfg, string addr, Byte netbits);
}
}
|
using System;
using System.Runtime.InteropServices;
namespace TAPCfg {
public class EthernetDevice : IDisposable {
private const int MTU = 1522;
private IntPtr handle;
private bool disposed = false;
public EthernetDevice() {
handle = tapcfg_init();
}
public void Start() {
tapcfg_start(handle);
}
public byte[] Read() {
int length;
byte[] buffer = new byte[MTU];
length = tapcfg_read(handle, buffer, buffer.Length);
byte[] outbuf = new byte[length];
Array.Copy(buffer, 0, outbuf, 0, length);
return outbuf;
}
public void Write(byte[] data) {
byte[] buffer = new byte[MTU];
Array.Copy(data, 0, buffer, 0, data.Length);
int ret = tapcfg_write(handle, buffer, data.Length);
}
public void Enabled(bool enabled) {
if (enabled)
tapcfg_iface_change_status(handle, 1);
else
tapcfg_iface_change_status(handle, 0);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (!disposed) {
if (disposing) {
// Managed resources can be disposed here
}
tapcfg_stop(handle);
tapcfg_destroy(handle);
handle = IntPtr.Zero;
disposed = true;
}
}
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start();
dev.Enabled(true);
System.Threading.Thread.Sleep(100000);
}
[DllImport("libtapcfg")]
private static extern IntPtr tapcfg_init();
[DllImport("libtapcfg")]
private static extern void tapcfg_destroy(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_start(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern void tapcfg_stop(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_has_data(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_read(IntPtr tapcfg, byte[] buf, int count);
[DllImport("libtapcfg")]
private static extern int tapcfg_write(IntPtr tapcfg, byte[] buf, int count);
[DllImport("libtapcfg")]
private static extern string tapcfg_get_ifname(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_get_status(IntPtr tapcfg);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_change_status(IntPtr tapcfg, int enabled);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_set_ipv4(IntPtr tapcfg, string addr, Byte netbits);
[DllImport("libtapcfg")]
private static extern int tapcfg_iface_set_ipv6(IntPtr tapcfg, string addr, Byte netbits);
}
}
| lgpl-2.1 | C# |
7bde74c6cce002cb2b3cb61baff64488196d52c0 | bump version | Fody/PropertyChanged | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("2.2.3")] | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("2.2.2")] | mit | C# |
026a0cfc692467bb39fa3a0366a255c8e1fcfcc7 | Comment is no longer reqired | nkreipke/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core | src/NHibernate/Engine/Transaction/IIsolatedWork.cs | src/NHibernate/Engine/Transaction/IIsolatedWork.cs | using System.Data;
namespace NHibernate.Engine.Transaction
{
/// <summary>
/// Represents work that needs to be performed in a manner
/// which isolates it from any current application unit of
/// work transaction.
/// </summary>
public interface IIsolatedWork
{
/// <summary>
/// Perform the actual work to be done.
/// </summary>
/// <param name="connection">The ADP connection to use.</param>
void DoWork(IDbConnection connection, IDbTransaction transaction);
}
} | using System.Data;
namespace NHibernate.Engine.Transaction
{
/// <summary>
/// Represents work that needs to be performed in a manner
/// which isolates it from any current application unit of
/// work transaction.
/// </summary>
public interface IIsolatedWork
{
/// <summary>
/// Perform the actual work to be done.
/// </summary>
/// <param name="connection">The ADP connection to use.</param>
void DoWork(IDbConnection connection, IDbTransaction transaction);
// 2009-05-04 Another time we need a TransactionManager to manage isolated
// work for a given connection.
}
} | lgpl-2.1 | C# |
38735577c52d2d0573f245152c8a5d590d2e3155 | Fix autofac lifetime creation | huysentruitw/projecto | src/Projecto.Autofac/ProjectorBuilderExtensions.cs | src/Projecto.Autofac/ProjectorBuilderExtensions.cs | /*
* Copyright 2017 Wouter Huysentruit
*
* 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 Autofac;
using Projecto.Infrastructure;
namespace Projecto.Autofac
{
/// <summary>
/// <see cref="ProjectorBuilder{TProjectContext}"/> extension methods.
/// </summary>
public static class ProjectorBuilderExtensions
{
/// <summary>
/// Registers all projections that are registered as <see cref="IProjection{TProjectContext}"/> on the Autofac container.
/// </summary>
/// <typeparam name="TProjectContext">The type of the project context (used to pass custom information to the handler).</typeparam>
/// <param name="builder">The builder.</param>
/// <param name="componentContext">The Autofac component context.</param>
/// <returns></returns>
public static ProjectorBuilder<TProjectContext>
UseAutofac<TProjectContext>(this ProjectorBuilder<TProjectContext> builder, IComponentContext componentContext)
{
var projections = componentContext.Resolve<IEnumerable<IProjection<TProjectContext>>>();
builder.Register(projections);
var lifetimeScopeFactory = componentContext.Resolve<Func<ILifetimeScope>>();
builder.SetProjectScopeFactory((_, __) => new AutofacProjectScope(() => lifetimeScopeFactory().BeginLifetimeScope()));
return builder;
}
}
}
| /*
* Copyright 2017 Wouter Huysentruit
*
* 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 Autofac;
using Projecto.Infrastructure;
namespace Projecto.Autofac
{
/// <summary>
/// <see cref="ProjectorBuilder{TProjectContext}"/> extension methods.
/// </summary>
public static class ProjectorBuilderExtensions
{
/// <summary>
/// Registers all projections that are registered as <see cref="IProjection{TProjectContext}"/> on the Autofac container.
/// </summary>
/// <typeparam name="TProjectContext">The type of the project context (used to pass custom information to the handler).</typeparam>
/// <param name="builder">The builder.</param>
/// <param name="componentContext">The Autofac component context.</param>
/// <returns></returns>
public static ProjectorBuilder<TProjectContext>
UseAutofac<TProjectContext>(this ProjectorBuilder<TProjectContext> builder, IComponentContext componentContext)
{
var projections = componentContext.Resolve<IEnumerable<IProjection<TProjectContext>>>();
builder.Register(projections);
var lifetimeScopeFactory = componentContext.Resolve<Func<ILifetimeScope>>();
builder.SetProjectScopeFactory((_, __) => new AutofacProjectScope(lifetimeScopeFactory));
return builder;
}
}
}
| apache-2.0 | C# |
05c432d995f1988f7410a224df9aa5b2b4c1f507 | Include self references | stofte/ream-query | src/ReamQuery.Server/Services/ReferenceProvider.cs | src/ReamQuery.Server/Services/ReferenceProvider.cs | namespace ReamQuery.Server.Services
{
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using ReamQuery.Core;
public class ReferenceProvider
{
Lazy<IEnumerable<MetadataReference>> _references = new Lazy<IEnumerable<MetadataReference>>(() => {
var list = new List<MetadataReference>();
foreach(var stream in ReamQuery.Resource.Resources.Metadata())
{
list.Add(MetadataReference.CreateFromStream(stream));
}
return list;
});
public IEnumerable<MetadataReference> GetReferences()
{
var list = new List<MetadataReference>();
foreach(var stream in ReamQuery.Resource.Resources.Metadata())
{
list.Add(MetadataReference.CreateFromStream(stream));
}
var coreAsm = new Uri(typeof(IGenerated).Assembly.CodeBase).LocalPath;
var serverAsm = new Uri(typeof(Emitter).Assembly.CodeBase).LocalPath;
list.Add(MetadataReference.CreateFromFile(coreAsm));
list.Add(MetadataReference.CreateFromFile(serverAsm));
return list;
// return _references.Value;
}
}
} | namespace ReamQuery.Server.Services
{
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
public class ReferenceProvider
{
Lazy<IEnumerable<MetadataReference>> _references = new Lazy<IEnumerable<MetadataReference>>(() => {
var list = new List<MetadataReference>();
foreach(var stream in ReamQuery.Resource.Resources.Metadata())
{
list.Add(MetadataReference.CreateFromStream(stream));
}
return list;
});
public IEnumerable<MetadataReference> GetReferences()
{
var list = new List<MetadataReference>();
foreach(var stream in ReamQuery.Resource.Resources.Metadata())
{
list.Add(MetadataReference.CreateFromStream(stream));
}
return list;
// return _references.Value;
}
}
} | mit | C# |
406610507c7a5355de5d8664e854d55e159b80d4 | Update Worker template to not throw unexpectedly (#29543) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Worker.cs | src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Worker.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Company.Application1
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
try
{
await Task.Delay(1000, stoppingToken);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Company.Application1
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}
| apache-2.0 | C# |
44373aa12beb05bc6f7d297a2321c33e01f9740e | update copyright date | wcm-io-devops/aem-manager | AEMManager/Properties/AssemblyInfo.cs | AEMManager/Properties/AssemblyInfo.cs | 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("AEM Manager")]
[assembly: AssemblyDescription("Taskbar application for managing AEM instances")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("wcm.io")]
[assembly: AssemblyProduct("wcm.io AEM Manager")]
[assembly: AssemblyCopyright("©2010-2018 pro!vision GmbH, wcm.io")]
[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("7eb3bb90-a3f2-4a71-aee0-fbc04cabfb32")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.3.5.0")]
[assembly: AssemblyFileVersion("2.3.5.0")]
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfiguratorAttribute(Watch = true)]
| 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("AEM Manager")]
[assembly: AssemblyDescription("Taskbar application for managing AEM instances")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("wcm.io")]
[assembly: AssemblyProduct("wcm.io AEM Manager")]
[assembly: AssemblyCopyright("©2010-2017 pro!vision GmbH, wcm.io")]
[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("7eb3bb90-a3f2-4a71-aee0-fbc04cabfb32")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.3.5.0")]
[assembly: AssemblyFileVersion("2.3.5.0")]
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfiguratorAttribute(Watch = true)]
| apache-2.0 | C# |
14ff565769a6b4ec3d6175679da5dec5e017c4f8 | Add toggle to send reports | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Jobs/JobHandler.cs | Battery-Commander.Web/Jobs/JobHandler.cs | using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;
namespace BatteryCommander.Web.Jobs
{
internal static class JobHandler
{
public static Boolean Send_Reports => true;
public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger(typeof(JobHandler));
JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);
JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);
JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);
JobManager.UseUtcTime();
JobManager.JobFactory = new JobFactory(app.ApplicationServices);
var registry = new Registry();
registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().AtEst(hours: 9);
registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(0).Weeks().On(DayOfWeek.Tuesday).At(hours: 13, minutes: 0);
if (Send_Reports)
{
registry.Schedule<PERSTATReportJob>().ToRunEvery(1).Days().AtEst(hours: 6, minutes: 30);
registry.Schedule<SensitiveItemsReport>().WithName("Green3_AM").ToRunEvery(1).Days().AtEst(hours: 7, minutes: 30);
registry.Schedule<SensitiveItemsReport>().WithName("Green3_PM").ToRunEvery(1).Days().AtEst(hours: 21, minutes: 30);
}
JobManager.Initialize(registry);
}
private class JobFactory : IJobFactory
{
private readonly IServiceProvider serviceProvider;
public JobFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public IJob GetJobInstance<T>() where T : IJob
{
return serviceProvider.GetService(typeof(T)) as IJob;
}
}
}
} | using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;
namespace BatteryCommander.Web.Jobs
{
internal static class JobHandler
{
public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger(typeof(JobHandler));
JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);
JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);
JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);
JobManager.UseUtcTime();
JobManager.JobFactory = new JobFactory(app.ApplicationServices);
var registry = new Registry();
registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().AtEst(hours: 9);
registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(0).Weeks().On(DayOfWeek.Tuesday).At(hours: 13, minutes: 0);
registry.Schedule<PERSTATReportJob>().ToRunEvery(1).Days().AtEst(hours: 6, minutes: 30);
registry.Schedule<SensitiveItemsReport>().WithName("Green3_AM").ToRunEvery(1).Days().AtEst(hours: 7, minutes: 30);
registry.Schedule<SensitiveItemsReport>().WithName("Green3_PM").ToRunEvery(1).Days().AtEst(hours: 22, minutes: 30);
JobManager.Initialize(registry);
}
private class JobFactory : IJobFactory
{
private readonly IServiceProvider serviceProvider;
public JobFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public IJob GetJobInstance<T>() where T : IJob
{
return serviceProvider.GetService(typeof(T)) as IJob;
}
}
}
} | mit | C# |
56eb66065fc8409ab1e1bd61733fbfe9fc922a07 | Disable "Save" while sending invitations | JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,stevenhillcox/voting-application,tpkelly/voting-application,Generic-Voting-Application/voting-application,tpkelly/voting-application,stevenhillcox/voting-application | VotingApplication/VotingApplication.Web/Views/Routes/ManageInvitees.cshtml | VotingApplication/VotingApplication.Web/Views/Routes/ManageInvitees.cshtml | <div ng-app="GVA.Creation" ng-controller="ManageInviteesController">
<div class="centered">
<h2>Poll Invitees</h2>
<h4>Invited</h4>
<p ng-if="invitedUsers.length === 0">You haven't invited anybody yet</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="invitee in invitedUsers">
<span class="invitee-pill-text">{{invitee.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitedVoter(invitee)" aria-hidden="true"></span>
</div>
</div>
<h4>Pending</h4>
<input id="new-invitee" name="new-invitee" ng-model="inviteString" ng-change="emailUpdated()" ng-trim="false" />
<span class="glyphicon glyphicon-plus" ng-click="addInvitee(inviteString);"></span>
<p ng-if="pendingUsers.length === 0">No pending invitations</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="pending in pendingUsers">
<span class="invitee-pill-text">{{pending.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deletePendingVoter(pending)" aria-hidden="true"></span>
</div>
</div>
<div class="manage-section">
<button class="manage-btn" ng-click="discardChanges()">Cancel</button>
<button class="manage-btn" ng-disabled="isSaving || sendingInvitations" ng-click="saveChanges()">Save</button>
<button class="manage-btn" ng-disabled="isSaving || sendingInvitations" ng-click="addInvitee(inviteString); sendInvitations();" ng-if="pendingUsers.length > 0">Invite Pending</button>
</div>
</div>
</div>
| <div ng-app="GVA.Creation" ng-controller="ManageInviteesController">
<div class="centered">
<h2>Poll Invitees</h2>
<h4>Invited</h4>
<p ng-if="invitedUsers.length === 0">You haven't invited anybody yet</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="invitee in invitedUsers">
<span class="invitee-pill-text">{{invitee.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitedVoter(invitee)" aria-hidden="true"></span>
</div>
</div>
<h4>Pending</h4>
<input id="new-invitee" name="new-invitee" ng-model="inviteString" ng-change="emailUpdated()" ng-trim="false" />
<span class="glyphicon glyphicon-plus" ng-click="addInvitee(inviteString);"></span>
<p ng-if="pendingUsers.length === 0">No pending invitations</p>
<div class="pill-box">
<div class="invitee-pill" ng-repeat="pending in pendingUsers">
<span class="invitee-pill-text">{{pending.Email}}</span>
<span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deletePendingVoter(pending)" aria-hidden="true"></span>
</div>
</div>
<div class="manage-section">
<button class="manage-btn" ng-click="discardChanges()">Cancel</button>
<button class="manage-btn" ng-disabled="isSaving" ng-click="saveChanges()">Save</button>
<button class="manage-btn" ng-if="pendingUsers.length > 0" ng-disabled="sendingInvitations" ng-click="addInvitee(inviteString); sendInvitations();">Invite Pending</button>
</div>
</div>
</div>
| apache-2.0 | C# |
e677f5b6a96d33405363809e4badac9b54683a96 | Make PerformExit no-op | DrabWeb/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,Tom94/osu-framework | osu.Framework.iOS/iOSGameHost.cs | osu.Framework.iOS/iOSGameHost.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Audio;
using osu.Framework.Input;
using osu.Framework.Input.Handlers;
using osu.Framework.IO.Stores;
using osu.Framework.iOS.Audio;
using osu.Framework.iOS.Input;
using osu.Framework.Platform;
using osu.Framework.Platform.MacOS;
using osu.Framework.Threading;
namespace osu.Framework.iOS
{
public class IOSGameHost : GameHost
{
private readonly IOSGameView gameView;
public IOSGameHost(IOSGameView gameView)
{
this.gameView = gameView;
IOSGameWindow.GameView = gameView;
Window = new IOSGameWindow();
}
protected override void PerformExit(bool immediately)
{
// we shouldn't exit on iOS, as Window.Run does not block
}
public override ITextInputSource GetTextInput() => new IOSTextInput(gameView);
protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() =>
new InputHandler[] { new IOSTouchHandler(gameView), new IOSKeyboardHandler(gameView) };
protected override Storage GetStorage(string baseName) => new MacOSStorage(baseName, this);
public override void OpenFileExternally(string filename) => throw new NotImplementedException();
public override void OpenUrlExternally(string url) => throw new NotImplementedException();
public override AudioManager CreateAudioManager(ResourceStore<byte[]> trackStore, ResourceStore<byte[]> sampleStore, Scheduler eventScheduler) =>
new IOSAudioManager(trackStore, sampleStore) { EventScheduler = eventScheduler };
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Audio;
using osu.Framework.Input;
using osu.Framework.Input.Handlers;
using osu.Framework.IO.Stores;
using osu.Framework.iOS.Audio;
using osu.Framework.iOS.Input;
using osu.Framework.Platform;
using osu.Framework.Platform.MacOS;
using osu.Framework.Threading;
namespace osu.Framework.iOS
{
public class IOSGameHost : GameHost
{
private readonly IOSGameView gameView;
public IOSGameHost(IOSGameView gameView)
{
this.gameView = gameView;
IOSGameWindow.GameView = gameView;
Window = new IOSGameWindow();
}
public override ITextInputSource GetTextInput() => new IOSTextInput(gameView);
protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() =>
new InputHandler[] { new IOSTouchHandler(gameView), new IOSKeyboardHandler(gameView) };
protected override Storage GetStorage(string baseName) => new MacOSStorage(baseName, this);
public override void OpenFileExternally(string filename) => throw new NotImplementedException();
public override void OpenUrlExternally(string url) => throw new NotImplementedException();
public override AudioManager CreateAudioManager(ResourceStore<byte[]> trackStore, ResourceStore<byte[]> sampleStore, Scheduler eventScheduler) =>
new IOSAudioManager(trackStore, sampleStore) { EventScheduler = eventScheduler };
}
}
| mit | C# |
c3b0e1e7084abbe0b38adf26f63bdcb94a606426 | Update AssemblyInfo.cs | JamesStuddart/debonair | Debonair.Data/Properties/AssemblyInfo.cs | Debonair.Data/Properties/AssemblyInfo.cs | 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("Debonair")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("James Studdart")]
[assembly: AssemblyProduct("Debonair")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b8c24577-fae7-4c04-ab54-8c94262c2fe2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Debonair")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("James Studdart")]
[assembly: AssemblyProduct("Debonair")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b8c24577-fae7-4c04-ab54-8c94262c2fe2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0)]
| mit | C# |
9f8370892b1126db135bbcb2bde50557008c5b31 | Update SDK version to 4.0.3 | NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | /*******
Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********/
using System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "4.0.3"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| /*******
Copyright 2017-2018 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********/
using System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "4.0.2"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| apache-2.0 | C# |
e1af8aacb67a62dcf3150429c89181d8ef77883a | Add some tests for Hid.dll | jmelosegui/pinvoke,fearthecowboy/pinvoke,vbfox/pinvoke,AArnott/pinvoke | src/Hid.Tests/Hid.cs | src/Hid.Tests/Hid.cs | // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using Microsoft.Win32.SafeHandles;
using PInvoke;
using Xunit;
using static PInvoke.Hid;
public class Hid
{
[Fact]
public void HidD_GetHidGuid_ReturnExpectedValue()
{
// The GUID is a well know value
Assert.Equal(HidD_GetHidGuid(), Guid.Parse("4d1e55b2-f16f-11cf-88cb-001111000030"));
}
[Fact]
public void HidP_GetCaps_ThrowForInvalidHandle()
{
Assert.Throws<ArgumentException>(() =>
HidP_GetCaps(new SafePreparsedDataHandle(new IntPtr(0), false)));
}
[Fact]
public void HidD_GetManufacturerString_ThrowForInvalidHandle()
{
Assert.Throws<Win32Exception>(() =>
HidD_GetManufacturerString(new SafeFileHandle(new IntPtr(0), false)));
}
[Fact]
public void HidD_GetProductString_ThrowForInvalidHandle()
{
Assert.Throws<Win32Exception>(() =>
HidD_GetProductString(new SafeFileHandle(new IntPtr(0), false)));
}
[Fact]
public void HidD_GetSerialNumberString_ThrowForInvalidHandle()
{
Assert.Throws<Win32Exception>(() =>
HidD_GetSerialNumberString(new SafeFileHandle(new IntPtr(0), false)));
}
[Fact]
public void HidD_GetAttributes_ThrowForInvalidHandle()
{
Assert.Throws<Win32Exception>(() =>
HidD_GetAttributes(new SafeFileHandle(new IntPtr(0), false)));
}
[Fact]
public void HidD_GetPreparsedData_ThrowForInvalidHandle()
{
Assert.Throws<Win32Exception>(() =>
HidD_GetPreparsedData(new SafeFileHandle(new IntPtr(0), false)));
}
} | // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using PInvoke;
using Xunit;
using static PInvoke.Hid;
public class Hid
{
[Fact(Skip = "No tests yet")]
public void NoTests()
{
}
}
| mit | C# |
bb4b61c55ffc40dfaad067b4322c1e2b04cba03f | Remove CLS compliance warnings | Phrynohyas/eve-o-preview,Phrynohyas/eve-o-preview | Eve-O-Preview/Properties/AssemblyInfo.cs | Eve-O-Preview/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("EVE-O Preview")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EVE-O Preview")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("04f08f8d-9e98-423b-acdb-4effb31c0d35")]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: AssemblyFileVersion("4.0.0.0")]
[assembly: CLSCompliant(false)] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("EVE-O Preview")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EVE-O Preview")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("04f08f8d-9e98-423b-acdb-4effb31c0d35")]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: AssemblyFileVersion("4.0.0.0")]
[assembly: CLSCompliant(true)] | mit | C# |
b8342b0b25d5fa9799923546e6ef479952e402ef | Make sure Visual Studio can find the newly-included assemblies | laurentkempe/GitDiffMargin | GitDiffMargin/Properties/AssemblyInfo.cs | GitDiffMargin/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
using Tvl.VisualStudio.Shell;
// 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("Git Diff Margin")]
[assembly: AssemblyDescription("Git Diff Margin displays live changes of the currently edited file on Visual Studio margin and scroll bar.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Laurent Kempé")]
[assembly: AssemblyProduct("Git Diff Margin")]
[assembly: AssemblyCopyright("Laurent Kempé")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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)]
// 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("3.2.0.0")]
[assembly: AssemblyFileVersion("3.2.0.0")]
#if true // Use this block if Visual Studio 2010 still needs to be supported
[assembly: Guid("c279cada-3e46-4971-9355-50f43053d1b3")]
[assembly: ProvideBindingPath]
#else // Switch to this block when we only need Visual Studio 2012 or newer
[assembly: ProvideCodeBase(
AssemblyName = "Tvl.VisualStudio.Shell.Utility.10",
Version = "1.0.0.0",
CodeBase = "$PackageFolder$\\Tvl.VisualStudio.Shell.Utility.10.dll")]
[assembly: ProvideCodeBase(
AssemblyName = "Tvl.VisualStudio.Text.Utility.10",
Version = "1.0.0.0",
CodeBase = "$PackageFolder$\\Tvl.VisualStudio.Text.Utility.10.dll")]
#endif
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Git Diff Margin")]
[assembly: AssemblyDescription("Git Diff Margin displays live changes of the currently edited file on Visual Studio margin and scroll bar.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Laurent Kempé")]
[assembly: AssemblyProduct("Git Diff Margin")]
[assembly: AssemblyCopyright("Laurent Kempé")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
// 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)]
// 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("3.2.0.0")]
[assembly: AssemblyFileVersion("3.2.0.0")]
| mit | C# |
6e2ca4e76f7914a31c3e9e83c8649a4f46639d34 | Update page title | alsafonov/gitresources,ethomson/gitresources,ethomson/gitresources,alsafonov/gitresources | GitResources/Views/Shared/_Layout.cshtml | GitResources/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
@{
var pageTitle = (ViewBag.Title != null && ViewBag.Title.Length > 0) ?
"Git Resources: " + ViewBag.Title :
"Git Resources";
}
<title>@pageTitle</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<!--
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Git Resources", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
<li>@Html.ActionLink("API", "Index", "Help", new { area = "HelpPage" }, null)</li>
</ul>
</div>
</div>
</div>
-->
<div class="container body-content">
@RenderBody()
@RenderSection("SPAViews", required: false)
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("Scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - My ASP.NET Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<!--
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
<li>@Html.ActionLink("API", "Index", "Help", new { area = "HelpPage" }, null)</li>
</ul>
</div>
</div>
</div>
-->
<div class="container body-content">
@RenderBody()
@RenderSection("SPAViews", required: false)
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("Scripts", required: false)
</body>
</html>
| mit | C# |
159f3f3cd754088ea99c00b4db2b4c57695f2bfe | Add current state to header and more mutability | chkn/Tempest | Desktop/Tempest/MessageHeader.cs | Desktop/Tempest/MessageHeader.cs | //
// MessageHeader.cs
//
// Author:
// Eric Maupin <[email protected]>
//
// Copyright (c) 2011 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Tempest
{
[Flags]
public enum HeaderState
: byte
{
Protocol = 1,
Type = 2,
Length = 4,
IV = 8,
MessageId = 16,
TypeMap = 32
}
public class MessageHeader
{
public HeaderState State
{
get;
set;
}
public Protocol Protocol
{
get;
internal set;
}
public Message Message
{
get;
internal set;
}
/// <summary>
/// Gets the total length of the message (including <see cref="HeaderLength"/>).
/// </summary>
public int MessageLength
{
get;
internal set;
}
public bool HasTypeHeader
{
get;
internal set;
}
public int HeaderLength
{
get;
internal set;
}
public ISerializationContext SerializationContext
{
get;
internal set;
}
public byte[] IV
{
get;
internal set;
}
public bool IsStillEncrypted
{
get;
internal set;
}
/// <summary>
/// Gets whether the message is a response to another message or not.
/// </summary>
public bool IsResponse
{
get;
internal set;
}
public int MessageId
{
get;
internal set;
}
}
} | //
// MessageHeader.cs
//
// Author:
// Eric Maupin <[email protected]>
//
// Copyright (c) 2011 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Tempest
{
public class MessageHeader
{
internal MessageHeader (Protocol protocol, Message message)
{
if (protocol == null)
throw new ArgumentNullException ("protocol");
if (message == null)
throw new ArgumentNullException ("message");
Protocol = protocol;
Message = message;
}
public Protocol Protocol
{
get;
private set;
}
public Message Message
{
get;
private set;
}
/// <summary>
/// Gets the total length of the message (including <see cref="HeaderLength"/>).
/// </summary>
public int MessageLength
{
get;
internal set;
}
public int HeaderLength
{
get;
internal set;
}
public ISerializationContext SerializationContext
{
get;
internal set;
}
public byte[] IV
{
get;
internal set;
}
/// <summary>
/// Gets whether the message is a response to another message or not.
/// </summary>
public bool IsResponse
{
get;
internal set;
}
public int MessageId
{
get;
internal set;
}
}
} | mit | C# |
095529b1c3d13690e005ff56596b5046ecc88494 | Fix mail sending | Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder | Pathfinder/Game/MailServer/Extensions.cs | Pathfinder/Game/MailServer/Extensions.cs | using Hacknet;
namespace Pathfinder.Game.MailServer
{
public static class Extensions
{
public static void AddEmailToServer(this Hacknet.MailServer server,
string sender = null,
string recip = null,
string subject = null,
string body = null,
bool dontFilter = false)
{
sender = dontFilter ? sender ?? "UNKNOWN" : ComputerLoader.filter(sender ?? "UNKNOWN");
recip = dontFilter || recip == null ? recip : ComputerLoader.filter(recip);
subject = dontFilter ? subject ?? "UNKNOWN" : ComputerLoader.filter(subject ?? "UNKNOWN");
body = dontFilter ? body ?? "UNKNOWN" : ComputerLoader.filter(body ?? "UNKNOWN");
if (recip != null)
server.AddMailToServer(recip, Hacknet.MailServer.generateEmail(subject, body, sender));
}
public static void AddMailToServer(this Hacknet.MailServer server, string recip, string mail)
=> server.setupComplete = () => server.addMail(mail, recip);
}
}
| using Hacknet;
namespace Pathfinder.Game.MailServer
{
public static class Extensions
{
public static void AddEmailToServer(this Hacknet.MailServer server,
string sender = null,
string recip = null,
string subject = null,
string body = null,
bool dontFilter = false)
{
sender = dontFilter ? sender ?? "UNKNOWN" : ComputerLoader.filter(sender ?? "UNKNOWN");
recip = dontFilter || recip == null ? recip : ComputerLoader.filter(sender);
subject = dontFilter ? subject ?? "UNKNOWN" : ComputerLoader.filter(subject ?? "UNKNOWN");
body = dontFilter ? body ?? "UNKNOWN" : ComputerLoader.filter(body ?? "UNKNOWN");
if (recip != null)
server.AddMailToServer(recip, Hacknet.MailServer.generateEmail(subject, body, sender));
}
public static void AddMailToServer(this Hacknet.MailServer server, string recip, string mail)
=> server.setupComplete = () => server.addMail(mail, recip);
}
}
| mit | C# |
6d512291864506bf312b6b292310570f63ac43dd | add try-catch for parsing osu files. | Deliay/osuSync,Deliay/Sync | OtherPlugins/NowPlaying/OsuFileParser.cs | OtherPlugins/NowPlaying/OsuFileParser.cs | using osu_database_reader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NowPlaying
{
public static class OsuFileParser
{
public static BeatmapEntry ParseText(string content)
{
BeatmapEntry entry = null;
var parser_data = PickValues(ref content);
try
{
entry = new BeatmapEntry();
entry.Artist = parser_data["Artist"];
entry.ArtistUnicode = parser_data["ArtistUnicode"];
entry.Title = parser_data["Title"];
entry.TitleUnicode = parser_data["TitleUnicode"];
entry.Creator = parser_data["Creator"];
entry.SongSource = parser_data["Source"];
entry.SongTags = parser_data["Tags"];
entry.BeatmapId = int.Parse(parser_data["BeatmapID"]);
entry.BeatmapSetId = int.Parse(parser_data["BeatmapSetID"]);
entry.Difficulty = parser_data["Version"];
entry.DiffAR = float.Parse(parser_data["ApproachRate"]);
entry.DiffOD = float.Parse(parser_data["OverallDifficulty"]);
entry.DiffCS = float.Parse(parser_data["CircleSize"]);
entry.DiffHP = float.Parse(parser_data["HPDrainRate"]);
}
catch
{
return null;
}
return entry;
}
static Dictionary<string, string> PickValues(ref string content)
{
MatchCollection result = Regex.Matches(content, $@"^(\w+):(.*)$", RegexOptions.Multiline);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (Match match in result)
{
dic.Add(match.Groups[1].Value, match.Groups[2].Value.Replace("\r", string.Empty));
}
return dic;
}
}
}
| using osu_database_reader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NowPlaying
{
public static class OsuFileParser
{
public static BeatmapEntry ParseText(string content)
{
BeatmapEntry entry = new BeatmapEntry();
var parser_data = PickValues(ref content);
entry.Artist = parser_data["Artist"];
entry.ArtistUnicode = parser_data["ArtistUnicode"];
entry.Title = parser_data["Title"];
entry.TitleUnicode = parser_data["TitleUnicode"];
entry.Creator = parser_data["Creator"];
entry.SongSource = parser_data["Source"];
entry.SongTags = parser_data["Tags"];
entry.BeatmapId = int.Parse(parser_data["BeatmapID"]);
entry.BeatmapSetId = int.Parse(parser_data["BeatmapSetID"]);
entry.Difficulty = parser_data["Version"];
entry.DiffAR = float.Parse(parser_data["ApproachRate"]);
entry.DiffOD = float.Parse(parser_data["OverallDifficulty"]);
entry.DiffCS = float.Parse(parser_data["CircleSize"]);
entry.DiffHP = float.Parse(parser_data["HPDrainRate"]);
return entry;
}
static Dictionary<string, string> PickValues(ref string content)
{
MatchCollection result = Regex.Matches(content, $@"^(\w+):(.*)$", RegexOptions.Multiline);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (Match match in result)
{
dic.Add(match.Groups[1].Value, match.Groups[2].Value.Replace("\r", string.Empty));
}
return dic;
}
}
}
| mit | C# |
e8061f6735c837bca777f3c639951a692c411f25 | bump version to 2.4.1 | piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker | Piwik.Tracker/Properties/AssemblyInfo.cs | Piwik.Tracker/Properties/AssemblyInfo.cs | 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("PiwikTracker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Piwik")]
[assembly: AssemblyProduct("PiwikTracker")]
[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("8121d06f-a801-42d2-a144-0036a0270bf3")]
// 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.1")]
| 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("PiwikTracker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Piwik")]
[assembly: AssemblyProduct("PiwikTracker")]
[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("8121d06f-a801-42d2-a144-0036a0270bf3")]
// 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")]
| bsd-3-clause | C# |
c6648112e59f8a5c3429af35f72b99d8ceceb2c2 | Simplify binding flow in `InterpretationSection` | NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu | osu.Game/Screens/Edit/Verify/InterpretationSection.cs | osu.Game/Screens/Edit/Verify/InterpretationSection.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Overlays.Settings;
namespace osu.Game.Screens.Edit.Verify
{
internal class InterpretationSection : EditorRoundedScreenSettingsSection
{
[Resolved]
private VerifyScreen verify { get; set; }
protected override string HeaderText => "Interpretation";
[BackgroundDependencyLoader]
private void load()
{
Flow.Add(new SettingsEnumDropdown<DifficultyRating>
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
TooltipText = "Affects checks that depend on difficulty level",
Current = verify.InterpretedDifficulty.GetBoundCopy()
});
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Overlays.Settings;
namespace osu.Game.Screens.Edit.Verify
{
internal class InterpretationSection : EditorRoundedScreenSettingsSection
{
[Resolved]
private VerifyScreen verify { get; set; }
protected override string HeaderText => "Interpretation";
private Bindable<DifficultyRating> interpretedDifficulty;
[BackgroundDependencyLoader]
private void load()
{
interpretedDifficulty = verify.InterpretedDifficulty.GetBoundCopy();
var dropdown = new SettingsEnumDropdown<DifficultyRating>
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
TooltipText = "Affects checks that depend on difficulty level"
};
dropdown.Current.BindTo(interpretedDifficulty);
Flow.Add(dropdown);
}
}
}
| mit | C# |
eb8e02a5be6dd4970ef94be82a2986772a69a249 | Remove reference from add note screen | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EAS.Web/Views/EmployerCommitments/SubmitCommitmentEntry.cshtml | src/SFA.DAS.EAS.Web/Views/EmployerCommitments/SubmitCommitmentEntry.cshtml | @using SFA.DAS.EAS.Web.Models
@model SubmitCommitmentViewModel
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Add a note</h1>
<div class="form-group">
<p>You're about to send a request to your training provider, asking them to add one or more apprentices to your cohort. Once you send it, they'll be able to see your request in their online account.</p>
<p>Before you send your request, you can add a note for your training provider to read.</p>
</div>
<form method="POST" action="@Url.Action("SubmitCommitment")">
@Html.AntiForgeryToken()
<table>
<tbody>
<tr>
<th scope="row">Training provider name</th>
<td>@Model.Commitment.ProviderName</td>
<td></td>
</tr>
</tbody>
</table>
<div class="form-group">
<label class="form-label" for="Message">Note (optional)</label>
<p>For example, please add the 25 engineers we agreed on contract #30815</p>
<textarea class="form-control form-control-3-4" id="Message" name="Message"
cols="40" rows="10"
aria-required="true">@Model.SubmitCommitmentModel.Message</textarea>
</div>
<input type="hidden" id="saveOrSend" name="saveOrSend" value="@Model.SaveOrSend" />
<button type="submit" class="button">Send request to provider</button>
</form>
</div>
</div>
| @using SFA.DAS.EAS.Web.Models
@model SubmitCommitmentViewModel
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Add a note</h1>
<div class="form-group">
<p>You're about to send a request to your training provider, asking them to add one or more apprentices to your cohort. Once you send it, they'll be able to see your request in their online account.</p>
<p>Before you send your request, you can add a note for your training provider to read.</p>
</div>
<form method="POST" action="@Url.Action("SubmitCommitment")">
@Html.AntiForgeryToken()
<table>
<tbody>
<tr>
<th scope="row">Name</th>
<td>@Model.Commitment.Name</td>
<td></td>
</tr>
<tr>
<th scope="row">Training provider name</th>
<td>@Model.Commitment.ProviderName</td>
<td></td>
</tr>
</tbody>
</table>
<div class="form-group">
<label class="form-label" for="Message">Note (optional)</label>
<p>For example, please add the 25 engineers we agreed on contract #30815</p>
<textarea class="form-control form-control-3-4" id="Message" name="Message"
cols="40" rows="10"
aria-required="true">@Model.SubmitCommitmentModel.Message</textarea>
</div>
<input type="hidden" id="saveOrSend" name="saveOrSend" value="@Model.SaveOrSend" />
<button type="submit" class="button">Send request to provider</button>
</form>
</div>
</div>
| mit | C# |
c578e5e2f035d1a73b4d23753d97d29b6abcfc2e | adjust version | wanlitao/HangfireExtension | Hangfire.SQLite/Properties/AssemblyInfo.cs | Hangfire.SQLite/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Hangfire.SQLite")]
[assembly: AssemblyDescription("Hangfire plugin for SQLite Storage")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GreatBillows")]
[assembly: AssemblyProduct("Hangfire.SQLite")]
[assembly: AssemblyCopyright("Copyright © GreatBillows 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("77c7e1c1-f530-461a-a93e-6ab249a4ebe0")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1")]
[assembly: AssemblyFileVersion("1.1.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Hangfire.SQLite")]
[assembly: AssemblyDescription("Hangfire plugin for SQLite Storage")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GreatBillows")]
[assembly: AssemblyProduct("Hangfire.SQLite")]
[assembly: AssemblyCopyright("Copyright © GreatBillows 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("77c7e1c1-f530-461a-a93e-6ab249a4ebe0")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]
| apache-2.0 | C# |
584f19f80ebfe73a0ab797d848f12680e06c07f1 | fix in db | SoftMetalicana/ImpactMan | ImpactMan/ImpactMan/Core/AccountManager.cs | ImpactMan/ImpactMan/Core/AccountManager.cs | using System;
using System.Data.Entity.Infrastructure;
using System.Linq;
using ImpactMan.Context.Db;
namespace ImpactMan.Core
{
using System.Collections.Generic;
using Context.Models;
/// <summary>
/// This class takes care of the login and signup processes and the related checks and interaction with the DB.
/// </summary>
public class AccountManager
{
private ImpactManContext context;
public AccountManager(ImpactManContext context)
{
this.context = context;
if (context.Users.Local.Count == 0)
{
context.Users.Local.Add(new User()
{
Name = "MARIAN",
Password = "123"
});
}
}
public bool Login(User user)
{
return UserExists(user) && IsPasswordCorrect(user);
}
public bool Register(User user)
{
if (UserExists(user))
{
return false;
}
try
{
context.Users.Add(user);
context.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
private bool UserExists(User userX)
{
if (this.context.Users.Select(u => u.Name).ToList().Contains(userX.Name))
{
return true;
}
return false;
}
private bool IsPasswordCorrect(User user)
{
if (this.context.Users.Where(u => u.Name == user.Name).First().Password == user.Password)
{
return true;
}
else
{
return false;
}
}
}
}
| using System;
using System.Data.Entity.Infrastructure;
using System.Linq;
using ImpactMan.Context.Db;
namespace ImpactMan.Core
{
using System.Collections.Generic;
using Context.Models;
/// <summary>
/// This class takes care of the login and signup processes and the related checks and interaction with the DB.
/// </summary>
public class AccountManager
{
private ImpactManContext context;
public AccountManager(ImpactManContext context)
{
this.context = context;
if (context.Users.Local.Count == 0)
{
context.Users.Local.Add(new User()
{
Name = "MARIAN",
Password = "123"
});
}
}
public bool Login(User user)
{
return UserExists(user) && IsPasswordCorrect(user);
}
public bool Register(User user)
{
if (UserExists(user))
{
return false;
}
try
{
context.Users.Add(user);
context.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
private bool UserExists(User userX)
{
if (userX.Name != String.Empty && this.context.Users.Select(u => userX.Name).ToList().Contains(userX.Name))
{
return true;
}
return false;
}
private bool IsPasswordCorrect(User user)
{
if (this.context.Users.First(u => u.Name == user.Name).Password == user.Password)
{
return true;
}
else
{
return false;
}
}
}
}
| mit | C# |
f5e2e8ef68921e7bfb2304f2af3409537613c883 | Check for null ItemUri when getting uri for item | Adamsimsy/Sitecore.LinkedData | LinkedData/Repository/LinkedDataManager.cs | LinkedData/Repository/LinkedDataManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Converters;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Links;
using VDS.RDF;
using VDS.RDF.Parsing;
using VDS.RDF.Writing;
namespace LinkedData.Repository
{
public static class LinkedDataManager
{
private static readonly string RdfFilePath = System.Web.HttpContext.Current.Server.MapPath("~/HelloWorld.rdf");
public static void WriteGraph(IGraph graph)
{
var rdfxmlwriter = new RdfXmlWriter();
rdfxmlwriter.Save(graph, RdfFilePath);
}
public static IGraph ReadGraph()
{
var graph = new Graph();
FileLoader.Load(graph, RdfFilePath);
return graph;
}
public static string ItemToUri(Item item)
{
//var itemUriConverter = new IndexFieldItemUriValueConverter();
//ItemUri itemUri = (ItemUri) ((SitecoreItemUniqueId) item);
//var str = itemUriConverter.ConvertFrom(item);
return item.Uri != null ? item.Uri.ToString() : string.Empty;
}
public static Item UriToItem(string uri)
{
var itemUri = new ItemUri(uri);
var database = Sitecore.Configuration.Factory.GetDatabase(itemUri.DatabaseName);
return database.GetItem(itemUri.ItemID, itemUri.Language, itemUri.Version);
}
public static void WriteTriple(IGraph g, Triple triple)
{
g.Retract(triple);
g.Assert(triple);
WriteGraph(g);
}
public static Triple ToTriple(IGraph g, Item item, ItemLink itemLink)
{
IUriNode sub = g.CreateUriNode(ItemToUri(item));
IUriNode says = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
ILiteralNode obj = g.CreateLiteralNode(ItemToUri(itemLink.GetTargetItem()));
return new Triple(sub, says, obj);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Converters;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Links;
using VDS.RDF;
using VDS.RDF.Parsing;
using VDS.RDF.Writing;
namespace LinkedData.Repository
{
public static class LinkedDataManager
{
private static readonly string RdfFilePath = System.Web.HttpContext.Current.Server.MapPath("~/HelloWorld.rdf");
public static void WriteGraph(IGraph graph)
{
var rdfxmlwriter = new RdfXmlWriter();
rdfxmlwriter.Save(graph, RdfFilePath);
}
public static IGraph ReadGraph()
{
var graph = new Graph();
FileLoader.Load(graph, RdfFilePath);
return graph;
}
public static string ItemToUri(Item item)
{
//var itemUriConverter = new IndexFieldItemUriValueConverter();
//ItemUri itemUri = (ItemUri) ((SitecoreItemUniqueId) item);
//var str = itemUriConverter.ConvertFrom(item);
return item.Uri.ToString();
}
public static Item UriToItem(string uri)
{
var itemUri = new ItemUri(uri);
var database = Sitecore.Configuration.Factory.GetDatabase(itemUri.DatabaseName);
return database.GetItem(itemUri.ItemID, itemUri.Language, itemUri.Version);
}
public static void WriteTriple(IGraph g, Triple triple)
{
g.Retract(triple);
g.Assert(triple);
WriteGraph(g);
}
public static Triple ToTriple(IGraph g, Item item, ItemLink itemLink)
{
IUriNode sub = g.CreateUriNode(ItemToUri(item));
IUriNode says = g.CreateUriNode(UriFactory.Create("http://example.org/says"));
ILiteralNode obj = g.CreateLiteralNode(ItemToUri(itemLink.GetTargetItem()));
return new Triple(sub, says, obj);
}
}
}
| mit | C# |
708fe49221dbca0942cbd86e1b8ec6d705055924 | Add MealVoucher payment method (#178) | Viincenttt/MollieApi,Viincenttt/MollieApi | Mollie.Api/Models/Payment/PaymentMethod.cs | Mollie.Api/Models/Payment/PaymentMethod.cs | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Mollie.Api.Models.Payment {
[JsonConverter(typeof(StringEnumConverter))]
public enum PaymentMethod {
[EnumMember(Value = "bancontact")] Bancontact,
[EnumMember(Value = "banktransfer")] BankTransfer,
[EnumMember(Value = "belfius")] Belfius,
[EnumMember(Value = "bitcoin")] Bitcoin,
[EnumMember(Value = "creditcard")] CreditCard,
[EnumMember(Value = "directdebit")] DirectDebit,
[EnumMember(Value = "eps")] Eps,
[EnumMember(Value = "giftcard")] GiftCard,
[EnumMember(Value = "giropay")] Giropay,
[EnumMember(Value = "ideal")] Ideal,
[EnumMember(Value = "inghomepay")] IngHomePay,
[EnumMember(Value = "kbc")] Kbc,
[EnumMember(Value = "paypal")] PayPal,
[EnumMember(Value = "paysafecard")] PaySafeCard,
[EnumMember(Value = "sofort")] Sofort,
[EnumMember(Value = "refund")] Refund,
[EnumMember(Value = "klarnapaylater")] KlarnaPayLater,
[EnumMember(Value = "klarnasliceit")] KlarnaSliceIt,
[EnumMember(Value = "przelewy24")] Przelewy24,
[EnumMember(Value = "applepay")] ApplePay,
[EnumMember(Value = "mealvoucher")] MealVoucher
}
} | using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Mollie.Api.Models.Payment {
[JsonConverter(typeof(StringEnumConverter))]
public enum PaymentMethod {
[EnumMember(Value = "bancontact")] Bancontact,
[EnumMember(Value = "banktransfer")] BankTransfer,
[EnumMember(Value = "belfius")] Belfius,
[EnumMember(Value = "bitcoin")] Bitcoin,
[EnumMember(Value = "creditcard")] CreditCard,
[EnumMember(Value = "directdebit")] DirectDebit,
[EnumMember(Value = "eps")] Eps,
[EnumMember(Value = "giftcard")] GiftCard,
[EnumMember(Value = "giropay")] Giropay,
[EnumMember(Value = "ideal")] Ideal,
[EnumMember(Value = "inghomepay")] IngHomePay,
[EnumMember(Value = "kbc")] Kbc,
[EnumMember(Value = "paypal")] PayPal,
[EnumMember(Value = "paysafecard")] PaySafeCard,
[EnumMember(Value = "sofort")] Sofort,
[EnumMember(Value = "refund")] Refund,
[EnumMember(Value = "klarnapaylater")] KlarnaPayLater,
[EnumMember(Value = "klarnasliceit")] KlarnaSliceIt,
[EnumMember(Value = "przelewy24")] Przelewy24,
[EnumMember(Value = "applepay")] ApplePay,
}
} | mit | C# |
4217cd5a2810df2d9d88f02fbbd240220887e546 | Add post-build event to update docs; | KonH/UDBase | Scripts/Editor/Tools/CSprojUpdater.cs | Scripts/Editor/Tools/CSprojUpdater.cs | using System.Xml;
namespace UDBase.EditorTools {
public static class CSProjUpdater {
public static void UpdateCsprojFile(string fileName) {
var doc = new XmlDocument();
doc.Load(fileName);
// <PropertyGroup>
// <DocumentationFile>$(OutputPath)Assembly-CSharp.xml</DocumentationFile>
// </PropertyGroup>
var namespaceUri = doc.LastChild.Attributes["xmlns"].Value;
var group = doc.CreateElement("PropertyGroup", namespaceUri);
var docFile = doc.CreateElement("DocumentationFile", namespaceUri);
docFile.InnerText = "$(OutputPath)Assembly-CSharp.xml";
group.AppendChild(docFile);
doc.LastChild.AppendChild(group);
UnityEngine.Debug.Log($"Xml documentation generation added to project '{fileName}'");
// <Target Name="PostBuild" AfterTargets="PostBuildEvent">
// <Exec Command="call cd $(SolutionDir)Tools\
call "$(SolutionDir)Tools\GenerateDocs.bat"" />
// </Target>
var target = doc.CreateElement("Target", namespaceUri);
{
var nameAttr = doc.CreateAttribute("Name");
nameAttr.Value = "PostBuild";
target.Attributes.Append(nameAttr);
var targetAttr = doc.CreateAttribute("AfterTargets");
targetAttr.Value = "PostBuildEvent";
target.Attributes.Append(targetAttr);
var exec = doc.CreateElement("Exec", namespaceUri);
{
var commandAttr = doc.CreateAttribute("Command");
commandAttr.Value = "call cd $(SolutionDir)Tools\ncall \"$(SolutionDir)Tools\\GenerateDocs.bat\"";
exec.Attributes.Append(commandAttr);
}
target.AppendChild(exec);
}
doc.LastChild.AppendChild(target);
UnityEngine.Debug.Log($"Markdown post-process added to project '{fileName}'");
doc.Save(fileName);
}
}
}
| using System.Xml;
namespace UDBase.EditorTools {
public static class CSProjUpdater {
public static void UpdateCsprojFile(string fileName) {
var doc = new XmlDocument();
doc.Load(fileName);
// <PropertyGroup>
// <DocumentationFile>$(OutputPath)Assembly-CSharp.xml</DocumentationFile>
// </PropertyGroup>
var namespaceUri = doc.LastChild.Attributes["xmlns"].Value;
var group = doc.CreateElement("PropertyGroup", namespaceUri);
var docFile = doc.CreateElement("DocumentationFile", namespaceUri);
docFile.InnerText = "$(OutputPath)Assembly-CSharp.xml";
group.AppendChild(docFile);
doc.LastChild.AppendChild(group);
doc.Save(fileName);
UnityEngine.Debug.Log($"Xml documentation generation added to project '{fileName}'");
}
}
}
| mit | C# |
6b12428de984f39b51724ca6fa77d510a417e161 | Document interface | SnowflakePowered/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,SnowflakePowered/snowflake,RonnChyran/snowflake,faint32/snowflake-1,RonnChyran/snowflake,faint32/snowflake-1,RonnChyran/snowflake | Snowflake.API/Game/IGameMediaCache.cs | Snowflake.API/Game/IGameMediaCache.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing.Imaging;
using System.Drawing;
namespace Snowflake.Game
{
/// <summary>
/// The IGameMediaCache allows Snowflake to store metadata-media about a game
/// Each IGameInfo object can access their IGameMediaCache by keying against the UUID.
/// IGameMediaCache is implemented by GameMediaCache as a folder per-game with a single file for each object
/// Images are saved and retrieved in PNG format regardless of original format. Music and video are stored in their original format
/// It is recommended that music and video are stored in .mp3 or vorbis .ogg format, and h.264 in a .mp4 container or VP8 .webm , respectively.
/// </summary>
public interface IGameMediaCache
{
/// <summary>
/// The root path of the game media cache, where all game media cache folders are stored
/// </summary>
string RootPath { get; }
/// <summary>
/// The cache key of the game media cache, usually the UUID of the game this corresponds to
/// </summary>
string CacheKey { get; }
/// <summary>
/// Sets the front box art and saves it as a PNG file.
/// The same file data can be retrieved by GetBoxartFrontImage
/// </summary>
/// <param name="boxartFrontUri">The URI to download. This can be a file URI</param>
void SetBoxartFront(Uri boxartFrontUri);
/// <summary>
/// Sets the back box art and saves it as a PNG file.
/// The same file data can be retrieved by GetBoxartBackImage
/// </summary>
/// <param name="boxartBackUri">The URI to download. This can be a file URI</param>
void SetBoxartBack(Uri boxartBackUri);
/// <summary>
/// Sets the full box art and saves it as a PNG file.
/// The same file data can be retrieved by GetBoxartFullImage
/// </summary>
/// <param name="boxartFullUri">The URI to download. This can be a file URI</param>
void SetBoxartFull(Uri boxartFrontUri);
/// <summary>
/// Sets the fanart and saves it as a PNG file.
/// The same file data can be retrieved by GetGameFanartImage
/// </summary>
/// <param name="fanartUri">The URI to download. This can be a file URI</param>
void SetGameFanart(Uri fanartUri);
/// <summary>
/// Download and sets the game video. It is recommended the video format be in h.264 in a .mp4 container or VP8 in a .webm container
/// </summary>
/// <param name="videoUri">The URI to download</param>
void SetGameVideo(Uri videoUri);
/// <summary>
/// Download and sets the game music. It is recommended the audio format be in .mp3 MPEG-layer 3 format or .ogg Vorbis format
/// </summary>
/// <param name="musicUri">The URI to download</param>
void SetGameMusic(Uri musicUri);
/// <summary>
/// Get the front boxart image data. Returns null if not exists.
/// </summary>
/// <returns>The front boxart image as a System.Drawing.Image object</returns>
Image GetBoxartFrontImage();
/// <summary>
/// Get the back boxart image data.
/// </summary>
/// <returns>The front boxart image as a System.Drawing.Image object. Returns null if not exists.</returns>
Image GetBoxartBackImage();
/// <summary>
/// Get the full boxart image data.
/// </summary>
/// <returns>The full boxart image as a System.Drawing.Image object. Returns null if not exists</returns>
Image GetBoxartFullImage();
/// <summary>
/// Get the fanart image data.
/// </summary>
/// <returns>The fanart image as a System.Drawing.Image object. Returns null if not exists</returns>
Image GetGameFanartImage();
/// <summary>
/// Gets the video file name. Empty if not exists
/// </summary>
string GameVideoFileName { get; }
/// <summary>
/// Gets the video file name. Empty if not exists
/// </summary>
string GameMusicFileName { get; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing.Imaging;
using System.Drawing;
namespace Snowflake.Game
{
public interface IGameMediaCache
{
string RootPath { get; }
string CacheKey { get; }
void SetBoxartFront(Uri boxartFrontUri);
void SetBoxartBack(Uri boxartBackUri);
void SetBoxartFull(Uri boxartFrontUri);
void SetGameFanart(Uri fanartUri);
void SetGameVideo(Uri videoUri);
void SetGameMusic(Uri musicUri);
Image GetBoxartFrontImage();
Image GetBoxartBackImage();
Image GetBoxartFullImage();
Image GetGameFanartImage();
string GameVideoFileName { get; }
string GameMusicFileName { get; }
}
}
| mpl-2.0 | C# |
ee4ebdd791a8a08754dd0c069af29e004f36c0b9 | Add CFNetwork to list of Xamarin iOS dependencies, should fix Xamarin/iOS linking issues | CartoDB/mobile-sdk,CartoDB/mobile-sdk,CartoDB/mobile-sdk,CartoDB/mobile-sdk,CartoDB/mobile-sdk,CartoDB/mobile-sdk | ios/csharp/Properties/AssemblyInfo.cs | ios/csharp/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using ObjCRuntime;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("CartoMobileSDK.iOS")]
[assembly: AssemblyDescription ("Carto Mobile SDK for iOS")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("CartoDB")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("(c) CartoDB 2016, All rights reserved")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
[assembly: LinkWith("libcarto_mobile_sdk.a", LinkTarget.ArmV7|LinkTarget.ArmV7s|LinkTarget.Arm64|LinkTarget.Simulator|LinkTarget.Simulator64, ForceLoad=true, IsCxx=true, Frameworks="OpenGLES GLKit UIKit CoreGraphics CoreText CFNetwork Foundation")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using ObjCRuntime;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("CartoMobileSDK.iOS")]
[assembly: AssemblyDescription ("Carto Mobile SDK for iOS")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("CartoDB")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("(c) CartoDB 2016, All rights reserved")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
[assembly: LinkWith("libcarto_mobile_sdk.a", LinkTarget.ArmV7|LinkTarget.ArmV7s|LinkTarget.Arm64|LinkTarget.Simulator|LinkTarget.Simulator64, ForceLoad=true, IsCxx=true, Frameworks="OpenGLES GLKit UIKit CoreGraphics CoreText Foundation")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| bsd-3-clause | C# |
9d213d309f9553d6b341b8e65bb722c7919ddda5 | fix callbackUri escaping in authentication process; | ceee/PocketSharp | PocketSharp/Components/Authentification.cs | PocketSharp/Components/Authentification.cs | using PocketSharp.Models;
using System;
namespace PocketSharp
{
/// <summary>
/// PocketClient
/// </summary>
public partial class PocketClient
{
/// <summary>
/// Retrieves the requestCode from Pocket.
/// </summary>
/// <returns></returns>
public string GetRequestCode()
{
// check if request code is available
if (CallbackUri == null)
{
throw new APIException("Authentication methods need a callbackUri on initialization of the PocketClient class");
}
// do request
RequestCode response = Get<RequestCode>("oauth/request", Utilities.CreateParamInList("redirect_uri", CallbackUri));
// save code to client
RequestCode = response.Code;
// generate redirection URI and return
return RequestCode;
}
/// <summary>
/// Generate Authentication URI from requestCode
/// </summary>
/// <param name="requestCode">The requestCode.</param>
/// <returns></returns>
public Uri GenerateAuthenticationUri(string requestCode = null)
{
// check if request code is available
if(RequestCode == null && requestCode == null)
{
throw new APIException("Call GetRequestCode() first to receive a request_code");
}
// override property with given param if available
if(requestCode != null)
{
RequestCode = requestCode;
}
return new Uri(string.Format(authentificationUri, RequestCode, CallbackUri));
}
/// <summary>
/// Requests the access code after authentification
/// </summary>
/// <returns></returns>
public string GetAccessCode(string requestCode = null)
{
// check if request code is available
if(RequestCode == null && requestCode == null)
{
throw new APIException("Call GetRequestCode() first to receive a request_code");
}
// override property with given param if available
if(requestCode != null)
{
RequestCode = requestCode;
}
// do request
AccessCode response = Get<AccessCode>("oauth/authorize", Utilities.CreateParamInList("code", RequestCode));
// save code to client
AccessCode = response.Code;
return AccessCode;
}
}
}
| using PocketSharp.Models;
using System;
namespace PocketSharp
{
/// <summary>
/// PocketClient
/// </summary>
public partial class PocketClient
{
/// <summary>
/// Retrieves the requestCode from Pocket.
/// </summary>
/// <returns></returns>
public string GetRequestCode()
{
// check if request code is available
if (CallbackUri == null)
{
throw new APIException("Authentication methods need a callbackUri on initialization of the PocketClient class");
}
// do request
RequestCode response = Get<RequestCode>("oauth/request", Utilities.CreateParamInList("redirect_uri", CallbackUri));
// save code to client
RequestCode = response.Code;
// generate redirection URI and return
return RequestCode;
}
/// <summary>
/// Generate Authentication URI from requestCode
/// </summary>
/// <param name="requestCode">The requestCode.</param>
/// <returns></returns>
public Uri GenerateAuthenticationUri(string requestCode = null)
{
// check if request code is available
if(RequestCode == null && requestCode == null)
{
throw new APIException("Call GetRequestCode() first to receive a request_code");
}
// override property with given param if available
if(requestCode != null)
{
RequestCode = requestCode;
}
return new Uri(string.Format(authentificationUri, RequestCode, Uri.EscapeDataString(CallbackUri)));
}
/// <summary>
/// Requests the access code after authentification
/// </summary>
/// <returns></returns>
public string GetAccessCode(string requestCode = null)
{
// check if request code is available
if(RequestCode == null && requestCode == null)
{
throw new APIException("Call GetRequestCode() first to receive a request_code");
}
// override property with given param if available
if(requestCode != null)
{
RequestCode = requestCode;
}
// do request
AccessCode response = Get<AccessCode>("oauth/authorize", Utilities.CreateParamInList("code", RequestCode));
// save code to client
AccessCode = response.Code;
return AccessCode;
}
}
}
| mit | C# |
71c5a70670382f44b44089ab9307056972926ce1 | Bump Version (SPAD.neXt 0.9.4.33 +) | c0nnex/SPAD.neXt,c0nnex/SPAD.neXt | SPAD.Interfaces/Properties/AssemblyInfo.cs | SPAD.Interfaces/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Markup;
// 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("SPAD.neXt.Interfaces")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SPAD.neXt.Interfaces")]
[assembly: AssemblyCopyright("Copyright © 2014-2016 Ulrich Strauss")]
[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("2b25a2bf-891e-4970-b709-e53f1ebecb41")]
[assembly: XmlnsPrefix("http://www.fsgs.com/SPAD.neXt.Interfaces", "Interfaces")]
[assembly: XmlnsDefinition("http://www.fsgs.com/SPAD.neXt.Interfaces", "SPAD.neXt.Interfaces")]
[assembly: XmlnsDefinition("http://www.fsgs.com/SPAD.neXt.Interfaces", "SPAD.neXt.Interfaces.Events")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.5.5")]
[assembly: AssemblyFileVersion("0.9.5.5")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Markup;
// 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("SPAD.neXt.Interfaces")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SPAD.neXt.Interfaces")]
[assembly: AssemblyCopyright("Copyright © 2014-2016 Ulrich Strauss")]
[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("2b25a2bf-891e-4970-b709-e53f1ebecb41")]
[assembly: XmlnsPrefix("http://www.fsgs.com/SPAD.neXt.Interfaces", "Interfaces")]
[assembly: XmlnsDefinition("http://www.fsgs.com/SPAD.neXt.Interfaces", "SPAD.neXt.Interfaces")]
[assembly: XmlnsDefinition("http://www.fsgs.com/SPAD.neXt.Interfaces", "SPAD.neXt.Interfaces.Events")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.5.4")]
[assembly: AssemblyFileVersion("0.9.5.4")] | mit | C# |
c55921aadea68f82edeb399635aab84bbe432933 | Fix Binding error when running as x64 | tainicom/TreeViewEx | TreeViewEx/Properties/AssemblyInfo.cs | TreeViewEx/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
// 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: InternalsVisibleTo("TreeViewEx.Test,PublicKey="
+ "002400000480000094000000060200000024000052534131000400000100010035833343f8533b"
+ "82ef2ba1c6c2d71d289456655c7ccbb0647d861d0259d58bf0dd98f92cd9ea40618b5ed4b8729b"
+ "9fcde9303efff3ab483057078d89598ea542edea150340e0f842a99aa7585cec36ded398f9121e"
+ "b0c19b6ef7791ac7b53940fce9bd04ae225097b69e7354da663168ddc415216903ac68a5d2698b"
+ "0dd9edc1")]
[assembly: AssemblyTitle("TreeViewEx")]
[assembly: AssemblyDescription("Library for a multi select TreeView")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("-")]
[assembly: AssemblyProduct("TreeViewEx")]
[assembly: AssemblyCopyright("Copyright © Goroll 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
// 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: InternalsVisibleTo("TreeViewEx.Test,PublicKey="
+ "002400000480000094000000060200000024000052534131000400000100010035833343f8533b"
+ "82ef2ba1c6c2d71d289456655c7ccbb0647d861d0259d58bf0dd98f92cd9ea40618b5ed4b8729b"
+ "9fcde9303efff3ab483057078d89598ea542edea150340e0f842a99aa7585cec36ded398f9121e"
+ "b0c19b6ef7791ac7b53940fce9bd04ae225097b69e7354da663168ddc415216903ac68a5d2698b"
+ "0dd9edc1")]
[assembly: AssemblyTitle("TreeViewEx")]
[assembly: AssemblyDescription("Library for a multi select TreeView")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("-")]
[assembly: AssemblyProduct("TreeViewEx")]
[assembly: AssemblyCopyright("Copyright © Goroll 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.SourceAssembly, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
| mit | C# |
e7dec390d8d6c5d1fdf6dcd84cd5141721031c85 | Add Trim() call | tigrouind/AITD-roomviewer | Assets/Scripts/VarParser.cs | Assets/Scripts/VarParser.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
public class VarParser
{
readonly Dictionary<string, Dictionary<int, string>> sections
= new Dictionary<string, Dictionary<int, string>>();
public string GetText(string sectionName, int value)
{
Dictionary<int, string> section;
if (sections.TryGetValue(sectionName, out section))
{
string text;
if(section.TryGetValue(value, out text))
{
return text;
}
}
return string.Empty;
}
public void Load(string filePath, params string[] sectionsToParse)
{
var allLines = ReadLines(filePath);
Dictionary<int, string> currentSection = null;
Regex regex = new Regex("^(?<from>[0-9]+)(-(?<to>[0-9]+))? (?<text>.*)");
foreach (string line in allLines)
{
//check if new section
if (line.Length > 0 && line[0] >= 'A' && line[0] <= 'Z')
{
currentSection = CreateNewSection(line, sectionsToParse);
}
else if (currentSection != null)
{
//parse line if inside section
Match match = regex.Match(line);
if (match.Success)
{
string from = match.Groups["from"].Value;
string to = match.Groups["to"].Value;
string text = match.Groups["text"].Value.Trim();
AddEntry(currentSection, from, to, text);
}
}
}
}
Dictionary<int, string> CreateNewSection(string name, string[] sectionsToParse)
{
Dictionary<int, string> section;
if (sectionsToParse.Length == 0 || Array.IndexOf(sectionsToParse, name) >= 0)
{
section = new Dictionary<int, string>();
sections.Add(name.Trim(), section);
}
else
{
section = null;
}
return section;
}
void AddEntry(Dictionary<int, string> section, string fromString, string toString, string text)
{
if (!(string.IsNullOrEmpty(text) || text.Trim() == string.Empty))
{
int from = int.Parse(fromString);
int to = string.IsNullOrEmpty(toString) ? from : int.Parse(toString);
for(int i = from; i <= to ; i++)
{
section[i] = text;
}
}
}
IEnumerable<string> ReadLines(string filePath)
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
public class VarParser
{
readonly Dictionary<string, Dictionary<int, string>> sections
= new Dictionary<string, Dictionary<int, string>>();
public string GetText(string sectionName, int value)
{
Dictionary<int, string> section;
if (sections.TryGetValue(sectionName, out section))
{
string text;
if(section.TryGetValue(value, out text))
{
return text;
}
}
return string.Empty;
}
public void Load(string filePath, params string[] sectionsToParse)
{
var allLines = ReadLines(filePath);
Dictionary<int, string> currentSection = null;
Regex regex = new Regex("^(?<from>[0-9]+)(-(?<to>[0-9]+))? (?<text>.*)");
foreach (string line in allLines)
{
//check if new section
if (line.Length > 0 && line[0] >= 'A' && line[0] <= 'Z')
{
currentSection = CreateNewSection(line, sectionsToParse);
}
else if (currentSection != null)
{
//parse line if inside section
Match match = regex.Match(line);
if (match.Success)
{
string from = match.Groups["from"].Value;
string to = match.Groups["to"].Value;
string text = match.Groups["text"].Value;
AddEntry(currentSection, from, to, text);
}
}
}
}
Dictionary<int, string> CreateNewSection(string name, string[] sectionsToParse)
{
Dictionary<int, string> section;
if (sectionsToParse.Length == 0 || Array.IndexOf(sectionsToParse, name) >= 0)
{
section = new Dictionary<int, string>();
sections.Add(name.Trim(), section);
}
else
{
section = null;
}
return section;
}
void AddEntry(Dictionary<int, string> section, string fromString, string toString, string text)
{
if (!(string.IsNullOrEmpty(text) || text.Trim() == string.Empty))
{
int from = int.Parse(fromString);
int to = string.IsNullOrEmpty(toString) ? from : int.Parse(toString);
for(int i = from; i <= to ; i++)
{
section[i] = text;
}
}
}
IEnumerable<string> ReadLines(string filePath)
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
} | mit | C# |
828703c01d0f9659781d28e5b09e36cf99ead840 | Update SimpleExpressionQuery.cs | PowerMogli/Rabbit.Db | src/RabbitDB/Query/Generic/SimpleExpressionQuery.cs | src/RabbitDB/Query/Generic/SimpleExpressionQuery.cs | using System;
using System.Data;
using System.Linq.Expressions;
using RabbitDB.Expressions;
using RabbitDB.Storage;
namespace RabbitDB.Query.Generic
{
internal class ExpressionQuery<T> : IQuery, IArgumentQuery
{
protected Expression<Func<T, bool>> _expression;
public QueryParameterCollection Arguments { get; set; }
public string SqlStatement { get; private set; }
internal ExpressionQuery(Expression<Func<T, bool>> expression)
{
_expression = expression;
}
public IDbCommand Compile(IDbProvider dbProvider)
{
SqlExpressionBuilder<T> sqlExpressionBuilder = new SqlExpressionBuilder<T>(dbProvider);
sqlExpressionBuilder.CreateSelect(_expression);
string query = sqlExpressionBuilder.ToString();
QueryParameterCollection queryParameterCollection =
sqlExpressionBuilder.Parameters != null
? QueryParameterCollection.Create<T>(sqlExpressionBuilder.Parameters.ToArray())
: new QueryParameterCollection();
SqlQuery sqlQuery = new SqlQuery(query, queryParameterCollection);
return sqlQuery.Compile(dbProvider);
}
}
}
| using System;
using System.Data;
using System.Linq.Expressions;
using RabbitDB.Expressions;
using RabbitDB.Storage;
namespace RabbitDB.Query.Generic
{
class SimpleExpressionQuery<T> : IQuery
{
private Expression<Func<T, bool>> _condition;
private ExpressionSqlBuilder<T> _expressionBuilder;
internal SimpleExpressionQuery(Expression<Func<T, bool>> condition)
{
_condition = condition;
}
public IDbCommand Compile(IDbProvider provider)
{
return null;
}
}
}
| apache-2.0 | C# |
7d63987df0d0523c46b22410f16f6d45b83807dd | Add checksum calc | MadnessFreak/IntegrityChecker | Code/Data/ResourceSystem.cs | Code/Data/ResourceSystem.cs | using System;
using System.IO;
using System.Runtime.InteropServices;
namespace IntegrityChecker.Data
{
public static class ResourceSystem
{
/// <summary>
/// Marshals a structure to an <see cref="System.Byte"/>-Array.
/// </summary>
/// <typeparam name="T">The <see cref="System.Type"/> of the structure.</typeparam>
/// <param name="structure">The structure.</param>
/// <returns>An <see cref="System.Byte"/>-Array of the structure.</returns>
public static byte[] MarshalStructure<T>(object structure)
{
var structSize = Marshal.SizeOf(typeof(T));
var buffer = new byte[structSize];
var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Marshal.StructureToPtr(structure, handle.AddrOfPinnedObject(), false);
handle.Free();
return buffer;
}
/// <summary>
/// Writes a value to the current stream.
/// </summary>
/// <typeparam name="T">The <see cref="System.Type"/> of the structure.</typeparam>
/// <param name="writer">The binary writer.</param>
/// <param name="structure">The structure.</param>
public static void MarshalAndWriteStructure<T>(this BinaryWriter writer, object structure)
{
if (writer != null && writer.BaseStream.CanWrite)
{
writer.Write(MarshalStructure<T>(structure));
}
}
/// <summary>
/// Calculates the checksum of the target file.
/// </summary>
/// <param name="path">The target file path.</param>
/// <returns>The checksum of the target file.</returns>
public static int ComputeChecksum(string path)
{
try
{
var file = File.Open(path, FileMode.Open, FileAccess.Read);
var checksum = 0x25;
var num = (file.Length + 4) % 4;
var buffer = new byte[(file.Length + 4) - num];
var startIndex = 0;
file.Read(buffer, 0, (int)file.Length);
while (startIndex < buffer.Length)
{
checksum ^= BitConverter.ToInt32(buffer, startIndex);
startIndex += 4;
}
file.Flush();
file.Close();
file = null;
return checksum;
}
catch
{
return 0x00000000;
}
}
}
}
| using System;
using System.IO;
using System.Runtime.InteropServices;
namespace IntegrityChecker.Data
{
public static class ResourceSystem
{
/// <summary>
/// Marshals a structure to an <see cref="System.Byte"/>-Array.
/// </summary>
/// <typeparam name="T">The <see cref="System.Type"/> of the structure.</typeparam>
/// <param name="structure">The structure.</param>
/// <returns>An <see cref="System.Byte"/>-Array of the structure.</returns>
public static byte[] MarshalStructure<T>(object structure)
{
var structSize = Marshal.SizeOf(typeof(T));
var buffer = new byte[structSize];
var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Marshal.StructureToPtr(structure, handle.AddrOfPinnedObject(), false);
handle.Free();
return buffer;
}
/// <summary>
/// Writes a value to the current stream.
/// </summary>
/// <typeparam name="T">The <see cref="System.Type"/> of the structure.</typeparam>
/// <param name="writer">The binary writer.</param>
/// <param name="structure">The structure.</param>
public static void MarshalAndWriteStructure<T>(this BinaryWriter writer, object structure)
{
if (writer != null && writer.BaseStream.CanWrite)
{
writer.Write(MarshalStructure<T>(structure));
}
}
}
}
| mit | C# |
e38cd6e5f774c23703baf0c664529904bf6ac614 | Create arango exception which consists only of message. | yojimbo87/ArangoDB-NET,kangkot/ArangoDB-NET | src/Arango/Arango.Client/API/ArangoException.cs | src/Arango/Arango.Client/API/ArangoException.cs | using System;
using System.Net;
namespace Arango.Client
{
public class ArangoException : Exception
{
/// <summary>
/// HTTP status code which caused the exception.
/// </summary>
public HttpStatusCode HttpStatusCode { get; set; }
/// <summary>
/// Exception message of the web request object.
/// </summary>
public string WebExceptionMessage { get; set; }
public ArangoException()
{
}
public ArangoException(string message)
: base(message)
{
}
public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage)
: base(message)
{
HttpStatusCode = httpStatusCode;
WebExceptionMessage = webExceptionMessage;
}
public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage, Exception inner)
: base(message, inner)
{
HttpStatusCode = httpStatusCode;
WebExceptionMessage = webExceptionMessage;
}
}
}
| using System;
using System.Net;
namespace Arango.Client
{
public class ArangoException : Exception
{
/// <summary>
/// HTTP status code which caused the exception.
/// </summary>
public HttpStatusCode HttpStatusCode { get; set; }
/// <summary>
/// Exception message of the web request object.
/// </summary>
public string WebExceptionMessage { get; set; }
public ArangoException()
{
}
public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage)
: base(message)
{
HttpStatusCode = httpStatusCode;
WebExceptionMessage = webExceptionMessage;
}
public ArangoException(HttpStatusCode httpStatusCode, string message, string webExceptionMessage, Exception inner)
: base(message, inner)
{
HttpStatusCode = httpStatusCode;
WebExceptionMessage = webExceptionMessage;
}
}
}
| mit | C# |
2e3ddf536c2737dddaa2a8ab10a7946026179c0e | Refactor code. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Helpers/ClaimsHelper.cs | src/CompetitionPlatform/Helpers/ClaimsHelper.cs | using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using CompetitionPlatform.Models;
namespace CompetitionPlatform.Helpers
{
public static class ClaimsHelper
{
public static CompetitionPlatformUser GetUser(IIdentity identity)
{
var claimsIdentity = (ClaimsIdentity)identity;
var claims = claimsIdentity.Claims;
var claimsList = claims as IList<Claim> ?? claims.ToList();
var firstName = claimsList.Where(c => c.Type == ClaimTypes.GivenName)
.Select(c => c.Value).SingleOrDefault();
var lastName = claimsList.Where(c => c.Type == ClaimTypes.Surname)
.Select(c => c.Value).SingleOrDefault();
var email = claimsList.Where(c => c.Type == ClaimTypes.Email)
.Select(c => c.Value).SingleOrDefault();
var documents = claimsList.Where(c => c.Type == "documents")
.Select(c => c.Value).SingleOrDefault();
var user = new CompetitionPlatformUser
{
Email = email,
FirstName = firstName,
LastName = lastName,
Documents = documents
};
return user;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using CompetitionPlatform.Models;
namespace CompetitionPlatform.Helpers
{
public static class ClaimsHelper
{
public static CompetitionPlatformUser GetUser(IIdentity identity)
{
var claimsIdentity = (ClaimsIdentity)identity;
IEnumerable<Claim> claims = claimsIdentity.Claims;
var claimsList = claims as IList<Claim> ?? claims.ToList();
var firstName = claimsList.Where(c => c.Type == ClaimTypes.GivenName)
.Select(c => c.Value).SingleOrDefault();
var lastName = claimsList.Where(c => c.Type == ClaimTypes.Surname)
.Select(c => c.Value).SingleOrDefault();
var email = claimsList.Where(c => c.Type == ClaimTypes.Email)
.Select(c => c.Value).SingleOrDefault();
var documents = claimsList.Where(c => c.Type == "documents")
.Select(c => c.Value).SingleOrDefault();
var user = new CompetitionPlatformUser
{
Email = email,
FirstName = firstName,
LastName = lastName,
Documents = documents
};
return user;
}
}
}
| mit | C# |
6c05362ad9eca2a0be27dae5b37f41c7cf0d2090 | Use expression body | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/RoutableViewModel.cs | WalletWasabi.Fluent/ViewModels/RoutableViewModel.cs | using System;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels
{
public abstract class RoutableViewModel : ViewModelBase, IRoutableViewModel
{
private NavigationStateViewModel _navigationState;
private NavigationTarget _navigationTarget;
protected RoutableViewModel(NavigationStateViewModel navigationState, NavigationTarget navigationTarget)
{
_navigationState = navigationState;
_navigationTarget = navigationTarget;
}
public string UrlPathSegment { get; } = Guid.NewGuid().ToString().Substring(0, 5);
public IScreen HostScreen => _navigationTarget switch
{
NavigationTarget.Dialog => _navigationState.DialogScreen?.Invoke(),
_ => _navigationState.HomeScreen?.Invoke(),
};
public void Navigate()
{
switch (_navigationTarget)
{
case NavigationTarget.Default:
case NavigationTarget.Home:
_navigationState.HomeScreen?.Invoke().Router.Navigate.Execute(this);
break;
case NavigationTarget.Dialog:
_navigationState.DialogScreen?.Invoke().Router.Navigate.Execute(this);
break;
}
}
public void NavigateAndReset()
{
switch (_navigationTarget)
{
case NavigationTarget.Default:
case NavigationTarget.Home:
_navigationState.HomeScreen?.Invoke().Router.NavigateAndReset.Execute(this);
break;
case NavigationTarget.Dialog:
_navigationState.DialogScreen?.Invoke().Router.NavigateAndReset.Execute(this);
break;
}
}
public void GoBack()
{
switch (_navigationTarget)
{
case NavigationTarget.Default:
case NavigationTarget.Home:
_navigationState.HomeScreen?.Invoke().Router.NavigateBack.Execute();
break;
case NavigationTarget.Dialog:
_navigationState.DialogScreen?.Invoke().Router.NavigateBack.Execute();
break;
}
}
public void ClearNavigation()
{
switch (_navigationTarget)
{
case NavigationTarget.Default:
case NavigationTarget.Home:
_navigationState.HomeScreen?.Invoke().Router.NavigationStack.Clear();
break;
case NavigationTarget.Dialog:
_navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear();
break;
}
}
}
} | using System;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels
{
public abstract class RoutableViewModel : ViewModelBase, IRoutableViewModel
{
private NavigationStateViewModel _navigationState;
private NavigationTarget _navigationTarget;
protected RoutableViewModel(NavigationStateViewModel navigationState, NavigationTarget navigationTarget)
{
_navigationState = navigationState;
_navigationTarget = navigationTarget;
}
public string UrlPathSegment { get; } = Guid.NewGuid().ToString().Substring(0, 5);
public IScreen HostScreen
{
get
{
return _navigationTarget switch
{
NavigationTarget.Dialog => _navigationState.DialogScreen?.Invoke(),
_ => _navigationState.HomeScreen?.Invoke(),
};
}
}
public void Navigate()
{
switch (_navigationTarget)
{
case NavigationTarget.Default:
case NavigationTarget.Home:
_navigationState.HomeScreen?.Invoke().Router.Navigate.Execute(this);
break;
case NavigationTarget.Dialog:
_navigationState.DialogScreen?.Invoke().Router.Navigate.Execute(this);
break;
}
}
public void NavigateAndReset()
{
switch (_navigationTarget)
{
case NavigationTarget.Default:
case NavigationTarget.Home:
_navigationState.HomeScreen?.Invoke().Router.NavigateAndReset.Execute(this);
break;
case NavigationTarget.Dialog:
_navigationState.DialogScreen?.Invoke().Router.NavigateAndReset.Execute(this);
break;
}
}
public void GoBack()
{
switch (_navigationTarget)
{
case NavigationTarget.Default:
case NavigationTarget.Home:
_navigationState.HomeScreen?.Invoke().Router.NavigateBack.Execute();
break;
case NavigationTarget.Dialog:
_navigationState.DialogScreen?.Invoke().Router.NavigateBack.Execute();
break;
}
}
public void ClearNavigation()
{
switch (_navigationTarget)
{
case NavigationTarget.Default:
case NavigationTarget.Home:
_navigationState.HomeScreen?.Invoke().Router.NavigationStack.Clear();
break;
case NavigationTarget.Dialog:
_navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear();
break;
}
}
}
} | mit | C# |
d841985fa8a673e2e8d45126a02e08e6119c2973 | add new api method | LykkeCity/EthereumApiDotNetCore,LykkeCity/EthereumApiDotNetCore,LykkeCity/EthereumApiDotNetCore | src/EthereumApi/Controllers/ClientController.cs | src/EthereumApi/Controllers/ClientController.cs | using System.Threading.Tasks;
using Core.Exceptions;
using EthereumApi.Models;
using EthereumApiSelfHosted.Models;
using Microsoft.AspNetCore.Mvc;
using Services;
namespace EthereumApi.Controllers
{
[Route("api/client")]
[Produces("application/json")]
public class ClientController : Controller
{
private readonly IContractQueueService _contractQueueService;
public ClientController(IContractQueueService contractQueueService)
{
_contractQueueService = contractQueueService;
}
[Route("register")]
[HttpPost]
[Produces(typeof(RegisterResponse))]
public async Task<IActionResult> NewClientOld()
{
var contract = await _contractQueueService.GetContractAndSave(null);
var response = new RegisterResponse
{
Contract = contract
};
return Ok(response);
}
[Route("register/{userWallet}")]
[HttpGet]
[Produces(typeof(RegisterResponse))]
public async Task<IActionResult> NewClient(string userWallet)
{
if (string.IsNullOrWhiteSpace(userWallet))
throw new BackendException(BackendExceptionType.MissingRequiredParams);
var contract = await _contractQueueService.GetContractAndSave(userWallet);
var response = new RegisterResponse
{
Contract = contract
};
return Ok(response);
}
[Route("addWallet/{userWallet}")]
[HttpPost]
public async Task<IActionResult> AddUserWallet([FromBody]AddWalletModel model)
{
if (!ModelState.IsValid)
throw new BackendException(BackendExceptionType.MissingRequiredParams);
await _contractQueueService.UpdateUserWallet(model.UserContract, model.UserWallet);
return Ok();
}
}
}
| using System.Threading.Tasks;
using Core.Exceptions;
using EthereumApi.Models;
using EthereumApiSelfHosted.Models;
using Microsoft.AspNetCore.Mvc;
using Services;
namespace EthereumApi.Controllers
{
[Route("api/client")]
[Produces("application/json")]
public class ClientController : Controller
{
private readonly IContractQueueService _contractQueueService;
public ClientController(IContractQueueService contractQueueService)
{
_contractQueueService = contractQueueService;
}
[Route("register/{userWallet}")]
[HttpPost]
[Produces(typeof(RegisterResponse))]
public async Task<IActionResult> NewClient(string userWallet)
{
if (string.IsNullOrWhiteSpace(userWallet))
throw new BackendException(BackendExceptionType.MissingRequiredParams);
var contract = await _contractQueueService.GetContractAndSave(userWallet);
var response = new RegisterResponse
{
Contract = contract
};
return Ok(response);
}
[Route("addWallet/{userWallet}")]
[HttpPost]
public async Task<IActionResult> AddUserWallet([FromBody]AddWalletModel model)
{
if (!ModelState.IsValid)
throw new BackendException(BackendExceptionType.MissingRequiredParams);
await _contractQueueService.UpdateUserWallet(model.UserContract, model.UserWallet);
return Ok();
}
}
}
| mit | C# |
6a5cf11dd0d470cf23c0130573220b97f58b18c3 | Fix net461 bug | adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress | src/SharpCompress/Polyfills/StreamExtensions.cs | src/SharpCompress/Polyfills/StreamExtensions.cs | #if !NETSTANDARD2_1
using System.Buffers;
namespace System.IO
{
public static class StreamExtensions
{
public static void Write(this Stream stream, ReadOnlySpan<byte> buffer)
{
byte[] temp = ArrayPool<byte>.Shared.Rent(buffer.Length);
buffer.CopyTo(temp);
try
{
stream.Write(temp, 0, buffer.Length);
}
finally
{
ArrayPool<byte>.Shared.Return(temp);
}
}
}
}
#endif | #if !NETSTANDARD2_1
using System.Buffers;
namespace System.IO
{
public static class StreamExtensions
{
public static void Write(this Stream stream, ReadOnlySpan<byte> buffer)
{
var temp = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
stream.Write(temp, 0, buffer.Length);
}
finally
{
ArrayPool<byte>.Shared.Return(temp);
}
}
}
}
#endif | mit | C# |
ed467132e6f64c65faad29ad3a7f4a5dc2de3157 | Update LogPerformanceAttribute.cs | Squidex/squidex,pushrbx/squidex,pushrbx/squidex,pushrbx/squidex,pushrbx/squidex,Squidex/squidex,Squidex/squidex,pushrbx/squidex,Squidex/squidex,Squidex/squidex | src/Squidex/Pipeline/LogPerformanceAttribute.cs | src/Squidex/Pipeline/LogPerformanceAttribute.cs | // ==========================================================================
// LogPerformanceAttribute.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;
using Squidex.Infrastructure.Log;
namespace Squidex.Pipeline
{
public sealed class LogPerformanceAttribute : ActionFilterAttribute
{
private readonly ISemanticLog log;
public LogPerformanceAttribute(ISemanticLog log)
{
this.log = log;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
context.HttpContext.Items["Watch"] = Stopwatch.StartNew();
}
public override void OnActionExecuted(ActionExecutedContext context)
{
var stopWatch = (Stopwatch)context.HttpContext.Items["Watch"];
stopWatch.Stop();
log.LogInformation(w => w.WriteProperty("elapsedRequestMs", stopWatch.ElapsedMilliseconds));
}
}
}
| // ==========================================================================
// LogPerformanceAttribute.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;
using Squidex.Infrastructure.Log;
namespace Squidex.Pipeline
{
public sealed class LogPerformanceAttribute : ActionFilterAttribute
{
private readonly ISemanticLog log;
public LogPerformanceAttribute(ISemanticLog log)
{
this.log = log;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
context.HttpContext.Items["Watch"] = Stopwatch.StartNew();
}
public override void OnActionExecuted(ActionExecutedContext context)
{
var stopWatch = (Stopwatch)context.HttpContext.Items["Watch"];
log.LogInformation(w => w.WriteProperty("elapsedRequestMs", stopWatch.ElapsedMilliseconds));
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.