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 |
|---|---|---|---|---|---|---|---|---|
ea066c2612973a24c06e1bd112ffe60b1c8afef3 | Fix IsUpdatesChannel missing from ToApi() | Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server | src/Tgstation.Server.Host/Models/ChatChannel.cs | src/Tgstation.Server.Host/Models/ChatChannel.cs | using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Host.Models
{
/// <inheritdoc />
public sealed class ChatChannel : Api.Models.ChatChannel
{
/// <summary>
/// The row Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// The <see cref="Api.Models.Internal.ChatBot.Id"/>
/// </summary>
public long ChatSettingsId { get; set; }
/// <summary>
/// The <see cref="Models.ChatBot"/>
/// </summary>
public ChatBot ChatSettings { get; set; }
/// <summary>
/// Convert the <see cref="ChatChannel"/> to it's API form
/// </summary>
/// <returns>A new <see cref="Api.Models.ChatChannel"/></returns>
public Api.Models.ChatChannel ToApi() => new Api.Models.ChatChannel
{
DiscordChannelId = DiscordChannelId,
IsAdminChannel = IsAdminChannel,
IsWatchdogChannel = IsWatchdogChannel,
IsUpdatesChannel = IsUpdatesChannel,
IrcChannel = IrcChannel
};
}
}
| using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Host.Models
{
/// <inheritdoc />
public sealed class ChatChannel : Api.Models.ChatChannel
{
/// <summary>
/// The row Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// The <see cref="Api.Models.Internal.ChatBot.Id"/>
/// </summary>
public long ChatSettingsId { get; set; }
/// <summary>
/// The <see cref="Models.ChatBot"/>
/// </summary>
public ChatBot ChatSettings { get; set; }
/// <summary>
/// Convert the <see cref="ChatChannel"/> to it's API form
/// </summary>
/// <returns>A new <see cref="Api.Models.ChatChannel"/></returns>
public Api.Models.ChatChannel ToApi() => new Api.Models.ChatChannel
{
DiscordChannelId = DiscordChannelId,
IsAdminChannel = IsAdminChannel,
IsWatchdogChannel = IsWatchdogChannel,
IrcChannel = IrcChannel
};
}
}
| agpl-3.0 | C# |
a21e16877ef9cc281596e7aaf2c68435ce349a92 | Fix option helptext | zebraxxl/Winium.Desktop,2gis/Winium.Desktop | src/Winium.Desktop.Driver/CommandLineOptions.cs | src/Winium.Desktop.Driver/CommandLineOptions.cs | namespace Winium.Desktop.Driver
{
#region using
using CommandLine;
using CommandLine.Text;
#endregion
internal class CommandLineOptions
{
#region Public Properties
[Option("log-path", Required = false,
HelpText = "write server log to file instead of stdout, increases log level to INFO")]
public string LogPath { get; set; }
[Option("port", Required = false, HelpText = "port to listen on")]
public int? Port { get; set; }
[Option("url-base", Required = false, HelpText = "base URL path prefix for commands, e.g. wd/url")]
public string UrlBase { get; set; }
[Option("verbose", Required = false, HelpText = "log verbosely")]
public bool Verbose { get; set; }
[Option("silent", Required = false, HelpText = "log nothing")]
public bool Silent { get; set; }
#endregion
#region Public Methods and Operators
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
}
#endregion
}
}
| namespace Winium.Desktop.Driver
{
#region using
using CommandLine;
using CommandLine.Text;
#endregion
internal class CommandLineOptions
{
#region Public Properties
[Option("log-path", Required = false,
HelpText = "write server log to file instead of stdout, increases log level to INFO")]
public string LogPath { get; set; }
[Option("port", Required = false, HelpText = "port to listen on")]
public int? Port { get; set; }
[Option("url-base", Required = false, HelpText = "base URL path prefix for commands, e.g. wd/url")]
public string UrlBase { get; set; }
[Option("verbose", Required = false, HelpText = "log verbosely")]
public bool Verbose { get; set; }
[Option("silent", Required = false, HelpText = "log verbosely")]
public bool Silent { get; set; }
#endregion
#region Public Methods and Operators
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
}
#endregion
}
}
| mpl-2.0 | C# |
c584574f24129d22fc0f6e07a0e21b652cf9d3c5 | Fix HelenaZ | bunashibu/kikan | Assets/Scripts/Skill/Helena/HelenaZ.cs | Assets/Scripts/Skill/Helena/HelenaZ.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UniRx;
using UniRx.Triggers;
namespace Bunashibu.Kikan {
[RequireComponent(typeof(SkillSynchronizer))]
public class HelenaZ : Skill {
void Awake() {
_synchronizer = GetComponent<SkillSynchronizer>();
_hitRistrictor = new HitRistrictor(_hitInfo);
Observable.Timer(TimeSpan.FromSeconds(_existTime))
.Where(_ => this != null)
.Subscribe(_ => {
gameObject.SetActive(false);
Observable.Timer(TimeSpan.FromSeconds(5.0f))
.Where(none => this != null)
.Subscribe(none => {
Destroy(gameObject);
});
});
this.UpdateAsObservable()
.Where(_ => _skillUserObj != null)
.Where(_ => photonView.isMine)
.Take(1)
.Subscribe(_ => {
var skillUser = _skillUserObj.GetComponent<Player>();
Vector2 direction = (skillUser.Renderers[0].flipX) ? Vector2.left : Vector2.right;
_synchronizer.SyncForce(skillUser.PhotonView.viewID, _force, direction, false);
});
Observable.Timer(TimeSpan.FromSeconds(_firstDamageTime))
.Subscribe(_ => {
_attackInfo = new AttackInfo(_continuousDamagePercent, _attackInfo.MaxDeviation, _attackInfo.CriticalPercent);
});
}
void OnTriggerStay2D(Collider2D collider) {
if (PhotonNetwork.isMasterClient) {
var target = collider.gameObject.GetComponent<IPhoton>();
if (target == null)
return;
if (TeamChecker.IsSameTeam(collider.gameObject, _skillUserObj))
return;
if (_hitRistrictor.ShouldRistrict(collider.gameObject))
return;
DamageCalculator.Calculate(_skillUserObj, _attackInfo);
_synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, DamageCalculator.Damage, DamageCalculator.IsCritical, HitEffectType.Helena);
}
}
[SerializeField] private AttackInfo _attackInfo;
[SerializeField] private HitInfo _hitInfo;
private SkillSynchronizer _synchronizer;
private HitRistrictor _hitRistrictor;
private float _existTime = 5.0f;
private float _force = 15.0f;
private int _continuousDamagePercent = 20;
private float _firstDamageTime = 0.3f;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UniRx;
using UniRx.Triggers;
namespace Bunashibu.Kikan {
[RequireComponent(typeof(SkillSynchronizer))]
public class HelenaZ : Skill {
void Awake() {
_synchronizer = GetComponent<SkillSynchronizer>();
_hitRistrictor = new HitRistrictor(_hitInfo);
Observable.Timer(TimeSpan.FromSeconds(_existTime))
.Where(_ => this != null)
.Subscribe(_ => {
gameObject.SetActive(false);
Observable.Timer(TimeSpan.FromSeconds(5.0f))
.Where(none => this != null)
.Subscribe(none => {
Destroy(gameObject);
});
});
this.UpdateAsObservable()
.Where(_ => _skillUserObj != null)
.Take(1)
.Subscribe(_ => {
var skillUser = _skillUserObj.GetComponent<Player>();
Vector2 direction = (skillUser.Renderers[0].flipX) ? Vector2.left : Vector2.right;
_synchronizer.SyncForce(skillUser.PhotonView.viewID, _force, direction, false);
});
Observable.Timer(TimeSpan.FromSeconds(_firstDamageTime))
.Subscribe(_ => {
_attackInfo = new AttackInfo(_continuousDamagePercent, _attackInfo.MaxDeviation, _attackInfo.CriticalPercent);
});
}
void OnTriggerStay2D(Collider2D collider) {
if (PhotonNetwork.isMasterClient) {
var target = collider.gameObject.GetComponent<IPhoton>();
if (target == null)
return;
if (TeamChecker.IsSameTeam(collider.gameObject, _skillUserObj))
return;
if (_hitRistrictor.ShouldRistrict(collider.gameObject))
return;
DamageCalculator.Calculate(_skillUserObj, _attackInfo);
_synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, DamageCalculator.Damage, DamageCalculator.IsCritical, HitEffectType.Helena);
}
}
[SerializeField] private AttackInfo _attackInfo;
[SerializeField] private HitInfo _hitInfo;
private SkillSynchronizer _synchronizer;
private HitRistrictor _hitRistrictor;
private float _existTime = 5.0f;
private float _force = 15.0f;
private int _continuousDamagePercent = 20;
private float _firstDamageTime = 0.3f;
}
}
| mit | C# |
0173fe127240eb8a7d6d31fb29edd763c0eb67cd | Fix If conditional always evaluating as true (#20) | exodrifter/unity-rumor | Nodes/Conditionals/If.cs | Nodes/Conditionals/If.cs | using Exodrifter.Rumor.Engine;
using Exodrifter.Rumor.Expressions;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Exodrifter.Rumor.Nodes
{
/// <summary>
/// An if conditional statement.
/// </summary>
[Serializable]
public class If : Conditional
{
/// <summary>
/// The chained conditional statement to evaluate if this statement
/// evaluates as false.
/// </summary>
public readonly Conditional elif;
/// <summary>
/// Creates a new if block.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="children">The children of the if.</param>
public If(Expression expression, IEnumerable<Node> children)
: base(expression, children)
{
this.elif = null;
}
/// <summary>
/// Creates a new if block with a chained elif statement.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="children">The children of the if.</param>
/// <param name="elif">The chained if statement.</param>
public If(Expression expression, IEnumerable<Node> children, Elif elif)
: base(expression, children)
{
this.elif = elif;
}
/// <summary>
/// Creates a new if block with a chained else statement.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="children">The children of the if.</param>
/// <param name="else">The chained else statement.</param>
public If(Expression expression, IEnumerable<Node> children, Else @else)
: base(expression, children)
{
this.elif = @else;
}
public override IEnumerator<RumorYield> Exec(Engine.Rumor rumor)
{
var value = Evaluate(rumor);
if (value != null
&& (value.IsBool() && value.AsBool()
|| value.IsFloat() && value.AsFloat() != 0
|| value.IsInt() && value.AsInt() != 0
|| value.IsString() && value.AsString() != ""
|| value.IsObject() && value.AsObject() != null)) {
rumor.EnterBlock(Children);
}
else {
if (elif != null) {
var yield = elif.Exec(rumor);
while (yield.MoveNext()) {
yield return yield.Current;
}
}
}
yield return null;
}
#region Serialization
public If(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public override void GetObjectData
(SerializationInfo info, StreamingContext context)
{
}
#endregion
}
}
| using Exodrifter.Rumor.Engine;
using Exodrifter.Rumor.Expressions;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Exodrifter.Rumor.Nodes
{
/// <summary>
/// An if conditional statement.
/// </summary>
[Serializable]
public class If : Conditional
{
/// <summary>
/// The chained conditional statement to evaluate if this statement
/// evaluates as false.
/// </summary>
public readonly Conditional elif;
/// <summary>
/// Creates a new if block.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="children">The children of the if.</param>
public If(Expression expression, IEnumerable<Node> children)
: base(expression, children)
{
this.elif = null;
}
/// <summary>
/// Creates a new if block with a chained elif statement.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="children">The children of the if.</param>
/// <param name="elif">The chained if statement.</param>
public If(Expression expression, IEnumerable<Node> children, Elif elif)
: base(expression, children)
{
this.elif = elif;
}
/// <summary>
/// Creates a new if block with a chained else statement.
/// </summary>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="children">The children of the if.</param>
/// <param name="else">The chained else statement.</param>
public If(Expression expression, IEnumerable<Node> children, Else @else)
: base(expression, children)
{
this.elif = @else;
}
public override IEnumerator<RumorYield> Exec(Engine.Rumor rumor)
{
var value = Evaluate(rumor);
if (value != null
&& (value.IsBool() && value.AsBool()
|| value.IsFloat() && value.AsFloat() != 0
|| value.IsInt() && value.AsInt() != 0
|| value.IsString() && value.AsString() != ""
|| value.AsObject() != null)) {
rumor.EnterBlock(Children);
}
else {
if (elif != null) {
var yield = elif.Exec(rumor);
while (yield.MoveNext()) {
yield return yield.Current;
}
}
}
yield return null;
}
#region Serialization
public If(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public override void GetObjectData
(SerializationInfo info, StreamingContext context)
{
}
#endregion
}
}
| mit | C# |
717ca8a209e9d7339a90745085a304fcb30915d2 | Throw exceptions returned by service context. | ItzWarty/Dargon.Services,the-dargon-project/Dargon.Services | Client/ServiceInvocationInterceptor.cs | Client/ServiceInvocationInterceptor.cs | using System;
using Castle.DynamicProxy;
using Dargon.Services.PortableObjects;
using Dargon.Services.Utilities;
namespace Dargon.Services.Client {
public class ServiceInvocationInterceptor : IInterceptor {
private readonly IServiceContext serviceContext;
public ServiceInvocationInterceptor(IServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
public void Intercept(IInvocation invocation) {
var methodName = invocation.Method.Name;
var methodArguments = invocation.Arguments;
var result = serviceContext.Invoke(methodName, methodArguments);
var exception = result as Exception;
if (exception != null) {
throw exception;
} else {
invocation.ReturnValue = result;;
}
}
}
} | using System;
using Castle.DynamicProxy;
using Dargon.Services.PortableObjects;
using Dargon.Services.Utilities;
namespace Dargon.Services.Client {
public class ServiceInvocationInterceptor : IInterceptor {
private readonly IServiceContext serviceContext;
public ServiceInvocationInterceptor(IServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
public void Intercept(IInvocation invocation) {
var methodName = invocation.Method.Name;
var methodArguments = invocation.Arguments;
invocation.ReturnValue = serviceContext.Invoke(methodName, methodArguments);
}
}
} | bsd-2-clause | C# |
d219d064ffe8373bd23e10a761d519fc4cbdb1e0 | Add tooltips for hud menu buttons | k-t/SharpHaven | MonoHaven.Client/UI/Widgets/HudMenu.cs | MonoHaven.Client/UI/Widgets/HudMenu.cs | using System;
using System.Linq;
using MonoHaven.Graphics;
namespace MonoHaven.UI.Widgets
{
public class HudMenu : Widget
{
private static readonly Drawable background;
private static readonly Drawable[] images;
private static readonly string[] tooltips;
private static readonly int buttonCount;
static HudMenu()
{
background = App.Resources.Get<Drawable>("gfx/hud/invsq");
images = new[] {
"custom/gfx/hud/slen/invu", "custom/gfx/hud/slen/invd",
"custom/gfx/hud/slen/equu", "custom/gfx/hud/slen/equd",
"custom/gfx/hud/slen/chru", "custom/gfx/hud/slen/chrd",
"custom/gfx/hud/slen/budu", "custom/gfx/hud/slen/budd",
"custom/gfx/hud/slen/optu", "custom/gfx/hud/slen/optd" }
.Select(x => App.Resources.Get<Drawable>(x))
.ToArray();
tooltips = new[] {
"Inventory",
"Equipment",
"Character",
"Kin",
"Options"
};
buttonCount = images.Length / 2;
}
public HudMenu(Widget parent) : base(parent)
{
Resize((background.Width - 1) * buttonCount, background.Height - 1);
int x = 0;
for (int i = 0; i < buttonCount; i++)
{
var btn = new ImageButton(this)
{
Image = images[i * 2],
PressedImage = images[i * 2 + 1]
};
btn.Resize(images[i * 2].Size);
btn.Move(x + 1, 1);
btn.Tooltip = new Tooltip(tooltips[i]);
x += background.Width - 1;
var button = (Button)i;
btn.Click += () => ButtonClick.Raise(button);
}
}
protected override void OnDraw(DrawingContext dc)
{
int x = 0;
for (int i = 0; i < buttonCount; i++)
{
dc.Draw(background, x, 0);
x += background.Width - 1;
}
}
public event Action<Button> ButtonClick;
public enum Button
{
Inventory = 0,
Equipment = 1,
Character = 2,
BuddyList = 3,
Options = 4
}
}
}
| using System;
using System.Linq;
using MonoHaven.Graphics;
namespace MonoHaven.UI.Widgets
{
public class HudMenu : Widget
{
private static readonly Drawable background;
private static readonly Drawable[] buttonImages;
private static readonly int buttonCount;
static HudMenu()
{
background = App.Resources.Get<Drawable>("gfx/hud/invsq");
buttonImages = new[] {
"custom/gfx/hud/slen/invu", "custom/gfx/hud/slen/invd",
"custom/gfx/hud/slen/equu", "custom/gfx/hud/slen/equd",
"custom/gfx/hud/slen/chru", "custom/gfx/hud/slen/chrd",
"custom/gfx/hud/slen/budu", "custom/gfx/hud/slen/budd",
"custom/gfx/hud/slen/optu", "custom/gfx/hud/slen/optd" }
.Select(x => App.Resources.Get<Drawable>(x))
.ToArray();
buttonCount = buttonImages.Length / 2;
}
public HudMenu(Widget parent) : base(parent)
{
Resize((background.Width - 1) * buttonCount, background.Height - 1);
int x = 0;
for (int i = 0; i < buttonCount; i++)
{
var btn = new ImageButton(this)
{
Image = buttonImages[i * 2],
PressedImage = buttonImages[i * 2 + 1]
};
btn.Resize(buttonImages[i * 2].Size);
btn.Move(x + 1, 1);
x += background.Width - 1;
var button = (Button)i;
btn.Click += () => ButtonClick.Raise(button);
}
}
protected override void OnDraw(DrawingContext dc)
{
int x = 0;
for (int i = 0; i < buttonCount; i++)
{
dc.Draw(background, x, 0);
x += background.Width - 1;
}
}
public event Action<Button> ButtonClick;
public enum Button
{
Inventory = 0,
Equipment = 1,
Character = 2,
BuddyList = 3,
Options = 4
}
}
}
| mit | C# |
da9d391bca637805d1973874fd0493d661fa24a6 | Create application when executing create command | appharbor/appharbor-cli | src/AppHarbor/Commands/CreateCommand.cs | src/AppHarbor/Commands/CreateCommand.cs | using System;
namespace AppHarbor.Commands
{
public class CreateCommand : ICommand
{
private readonly AppHarborApi _appHarborApi;
public CreateCommand(AppHarborApi appHarborApi)
{
_appHarborApi = appHarborApi;
}
public void Execute(string[] arguments)
{
var result = _appHarborApi.CreateApplication(arguments[0], arguments[1]);
throw new NotImplementedException();
}
}
}
| using System;
namespace AppHarbor.Commands
{
public class CreateCommand : ICommand
{
private readonly AppHarborApi _appHarborApi;
public CreateCommand(AppHarborApi appHarborApi)
{
_appHarborApi = appHarborApi;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
3432499e1a25d89fcb4f5deedf76c5909ef49075 | Update AssemblyInfo.cs | NConsole/NConsole | src/NConsole/Properties/AssemblyInfo.cs | src/NConsole/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("NConsole")]
[assembly: AssemblyDescription("NConsole is a .NET library to parse command line arguments and execute commands.")]
[assembly: AssemblyCompany("Rico Suter")]
[assembly: AssemblyProduct("NConsole")]
[assembly: AssemblyCopyright("Copyright © Rico Suter, 2015")]
[assembly: AssemblyVersion("0.1.*")]
[assembly: InternalsVisibleTo("NConsole.Tests")]
| using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("NConsole")]
[assembly: AssemblyDescription(".NET library to parse command line arguments and execute commands.")]
[assembly: AssemblyCompany("Rico Suter")]
[assembly: AssemblyProduct("NConsole")]
[assembly: AssemblyCopyright("Copyright © Rico Suter, 2015")]
[assembly: AssemblyVersion("0.1.*")]
[assembly: InternalsVisibleTo("NConsole.Tests")] | mit | C# |
14901aa911f9eb0ae3e1a7ef9267c1022c9e4606 | Add Audio properties to IAudiomanagement | thephez/Vlc.DotNet,someonehan/Vlc.DotNet,briancowan/Vlc.DotNet,thephez/Vlc.DotNet,xue-blood/wpfVlc,marcomeyer/Vlc.DotNet,briancowan/Vlc.DotNet,raydtang/Vlc.DotNet,agherardi/Vlc.DotNet,jeremyVignelles/Vlc.DotNet,RickyGAkl/Vlc.DotNet,RickyGAkl/Vlc.DotNet,agherardi/Vlc.DotNet,raydtang/Vlc.DotNet,ZeBobo5/Vlc.DotNet,xue-blood/wpfVlc,marcomeyer/Vlc.DotNet,someonehan/Vlc.DotNet | src/Vlc.DotNet.Core/IAudioManagement.cs | src/Vlc.DotNet.Core/IAudioManagement.cs | namespace Vlc.DotNet.Core
{
public interface IAudioManagement
{
IAudioOutputsManagement Outputs { get; }
bool IsMute { get; set; }
void ToggleMute();
int Volume { get; set; }
ITracksManagement Tracks { get; }
int Channel { get; set; }
long Delay { get; set; }
}
}
| namespace Vlc.DotNet.Core
{
public interface IAudioManagement
{
IAudioOutputsManagement Outputs { get; }
}
}
| mit | C# |
a59caea2e6e9afcc4c6c0bfb24e16f6dc7c6d601 | Bump version to 0.13.3 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.13.3")]
[assembly: AssemblyInformationalVersionAttribute("0.13.3")]
[assembly: AssemblyFileVersionAttribute("0.13.3")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.13.3";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.13.2")]
[assembly: AssemblyInformationalVersionAttribute("0.13.2")]
[assembly: AssemblyFileVersionAttribute("0.13.2")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.13.2";
}
}
| apache-2.0 | C# |
99c067cc5869340ed90d9cce58d657aeec913d22 | Fix namespace in _ViewImports | vbliznikov/colabedit,vbliznikov/colabedit,vbliznikov/colabedit,vbliznikov/colabedit | src/web-editor/Views/_ViewImports.cshtml | src/web-editor/Views/_ViewImports.cshtml | @using CollabEdit
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@addTagHelper "*, Microsoft.AspNetCore.SpaServices"
| @using WebApplicationBasic
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@addTagHelper "*, Microsoft.AspNetCore.SpaServices"
| mit | C# |
c9eccffd163488bd3cb6e89e043fbd8afc77a3d2 | Fix to the last commit. | ashmind/AgentHeisenbug | AgentHeisenbug/Annotations/HeisenbugDebugExternalAnnotationFileProvider.cs | AgentHeisenbug/Annotations/HeisenbugDebugExternalAnnotationFileProvider.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Impl.Reflection2.ExternalAnnotations;
using JetBrains.Util;
namespace AgentHeisenbug.Annotations {
#if DEBUG
[PsiComponent]
public class HeisenbugDebugExternalAnnotationFileProvider : IExternalAnnotationsFileProvider {
[NotNull] private readonly FileSystemPath _path;
public HeisenbugDebugExternalAnnotationFileProvider() {
_path = FileSystemPath.Parse(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).NotNull())
.Combine("../../../#annotations");
}
public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null) {
if (assemblyName == null)
return Enumerable.Empty<FileSystemPath>();
var directoryForAssembly = _path.Combine(assemblyName.Name);
if (!directoryForAssembly.ExistsDirectory)
return Enumerable.Empty<FileSystemPath>();
return directoryForAssembly.GetDirectoryEntries("*.xml", true);
}
}
#endif
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Impl.Reflection2.ExternalAnnotations;
using JetBrains.Util;
namespace AgentHeisenbug.Annotations {
#if DEBUG
[PsiComponent]
public class HeisenbugDebugExternalAnnotationFileProvider : IExternalAnnotationsFileProvider {
[NotNull] private readonly FileSystemPath _path;
public HeisenbugDebugExternalAnnotationFileProvider() {
_path = FileSystemPath.Parse(Assembly.GetExecutingAssembly().Location)
.Combine("../../../#annotations");
}
public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null) {
if (assemblyName == null)
return Enumerable.Empty<FileSystemPath>();
var directoryForAssembly = _path.Combine(assemblyName.Name);
if (!directoryForAssembly.ExistsDirectory)
return Enumerable.Empty<FileSystemPath>();
return directoryForAssembly.GetDirectoryEntries("*.xml", true);
}
}
#endif
}
| mit | C# |
fddbbd5c80d027502c7747843c4151d3dc029ed8 | fix ValueMonthCalendar to be in US date form | jarmo/RAutomation,modulexcite/RAutomation,jarmo/RAutomation,modulexcite/RAutomation,jarmo/RAutomation,modulexcite/RAutomation,jarmo/RAutomation,modulexcite/RAutomation | ext/WindowsForms/WindowsForms/ValueMonthCalendar.cs | ext/WindowsForms/WindowsForms/ValueMonthCalendar.cs | using System;
using System.Globalization;
using System.Windows.Forms;
using UIA.Extensions.AutomationProviders.Interfaces;
namespace WindowsForms
{
public class ValueMonthCalendar : ValueControl
{
private readonly MonthCalendar _monthCalendar;
public ValueMonthCalendar(MonthCalendar monthCalendar) : base(monthCalendar)
{
_monthCalendar = monthCalendar;
}
public override string Value
{
get { return _monthCalendar.SelectionStart.ToString("d", EnglishCulture); }
set { _monthCalendar.SetDate(DateTime.Parse(value, EnglishCulture)); }
}
private static CultureInfo EnglishCulture
{
get { return new CultureInfo("en-US"); }
}
}
} | using System;
using System.Windows.Forms;
using UIA.Extensions.AutomationProviders.Interfaces;
namespace WindowsForms
{
public class ValueMonthCalendar : ValueControl
{
private readonly MonthCalendar _monthCalendar;
public ValueMonthCalendar(MonthCalendar monthCalendar) : base(monthCalendar)
{
_monthCalendar = monthCalendar;
}
public override string Value
{
get { return _monthCalendar.SelectionStart.ToShortDateString(); }
set { _monthCalendar.SetDate(DateTime.Parse(value)); }
}
}
} | mit | C# |
0282db8dd669bc21e764924475b2b0be15758c5f | Exclude bot owners from command cooldown. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | src/MitternachtBot/Modules/Permissions/Services/CommandCooldownService.cs | src/MitternachtBot/Modules/Permissions/Services/CommandCooldownService.cs | using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using Mitternacht.Common.Collections;
using Mitternacht.Common.ModuleBehaviors;
using Mitternacht.Services;
using Mitternacht.Services.Database.Models;
namespace Mitternacht.Modules.Permissions.Services {
public class CommandCooldownService : ILateBlocker, IMService {
private readonly DbService _db;
private readonly IBotCredentials _creds;
public ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> ActiveCooldowns { get; } = new ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>>();
public CommandCooldownService(DbService db, IBotCredentials creds) {
_db = db;
_creds = creds;
}
private CommandCooldown[] CommandCooldowns(ulong guildId) {
using var uow = _db.UnitOfWork;
return uow.GuildConfigs.For(guildId, set => set.Include(gc => gc.CommandCooldowns)).CommandCooldowns.ToArray();
}
public Task<bool> TryBlockLate(DiscordSocketClient client, IUserMessage message, IGuild guild, IMessageChannel channel, IUser user, string moduleName, string commandName) {
if(guild == null || _creds.IsOwner(user))
return Task.FromResult(false);
var commandCooldowns = CommandCooldowns(guild.Id);
var commandCooldown = commandCooldowns.FirstOrDefault(cc => cc.CommandName.Equals(commandName, StringComparison.OrdinalIgnoreCase));
if(commandCooldown != null) {
var activeCooldownsInGuild = ActiveCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet<ActiveCooldown>());
if(activeCooldownsInGuild.Any(ac => ac.UserId == user.Id && ac.Command.Equals(commandName, StringComparison.OrdinalIgnoreCase))) {
return Task.FromResult(true);
}
activeCooldownsInGuild.Add(new ActiveCooldown() {
UserId = user.Id,
Command = commandName,
});
var _ = Task.Run(async () => {
try {
await Task.Delay(commandCooldown.Seconds * 1000);
activeCooldownsInGuild.RemoveWhere(ac => ac.UserId == user.Id && ac.Command.Equals(commandName, StringComparison.OrdinalIgnoreCase));
} catch { }
});
}
return Task.FromResult(false);
}
}
public class ActiveCooldown {
public string Command { get; set; }
public ulong UserId { get; set; }
}
}
| using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using Mitternacht.Common.Collections;
using Mitternacht.Common.ModuleBehaviors;
using Mitternacht.Services;
using Mitternacht.Services.Database.Models;
namespace Mitternacht.Modules.Permissions.Services {
public class CommandCooldownService : ILateBlocker, IMService {
private readonly DbService _db;
public ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> ActiveCooldowns { get; } = new ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>>();
public CommandCooldownService(DbService db) {
_db = db;
}
private CommandCooldown[] CommandCooldowns(ulong guildId) {
using var uow = _db.UnitOfWork;
return uow.GuildConfigs.For(guildId, set => set.Include(gc => gc.CommandCooldowns)).CommandCooldowns.ToArray();
}
public Task<bool> TryBlockLate(DiscordSocketClient client, IUserMessage message, IGuild guild, IMessageChannel channel, IUser user, string moduleName, string commandName) {
if(guild == null)
return Task.FromResult(false);
var commandCooldowns = CommandCooldowns(guild.Id);
var commandCooldown = commandCooldowns.FirstOrDefault(cc => cc.CommandName.Equals(commandName, StringComparison.OrdinalIgnoreCase));
if(commandCooldown != null) {
var activeCooldownsInGuild = ActiveCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet<ActiveCooldown>());
if(activeCooldownsInGuild.Any(ac => ac.UserId == user.Id && ac.Command.Equals(commandName, StringComparison.OrdinalIgnoreCase))) {
return Task.FromResult(true);
}
activeCooldownsInGuild.Add(new ActiveCooldown() {
UserId = user.Id,
Command = commandName,
});
var _ = Task.Run(async () => {
try {
await Task.Delay(commandCooldown.Seconds * 1000);
activeCooldownsInGuild.RemoveWhere(ac => ac.UserId == user.Id && ac.Command.Equals(commandName, StringComparison.OrdinalIgnoreCase));
} catch { }
});
}
return Task.FromResult(false);
}
}
public class ActiveCooldown {
public string Command { get; set; }
public ulong UserId { get; set; }
}
}
| mit | C# |
4df6cad78d31ff168e42374840e0aaf0c7621c12 | Fix path too long bug | zumicts/Audiotica | Audiotica.Core/Utils/StringExtensions.cs | Audiotica.Core/Utils/StringExtensions.cs | using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Audiotica.Core.Utils
{
public static class StringExtensions
{
public static string CleanForFileName(this string str, string invalidMessage)
{
if (string.IsNullOrEmpty(str))
{
return null;
}
if (str.Length > 35)
{
str = str.Substring(0, 35);
}
/*
* A filename cannot contain any of the following characters:
* \ / : * ? " < > |
*/
var name =
str.Replace("\\", string.Empty)
.Replace("/", string.Empty)
.Replace(":", " ")
.Replace("*", string.Empty)
.Replace("?", string.Empty)
.Replace("\"", "'")
.Replace("<", string.Empty)
.Replace(">", string.Empty)
.Replace("|", " ");
return string.IsNullOrEmpty(name) ? invalidMessage : name;
}
public static async Task<T> DeserializeAsync<T>(this string json)
{
return await Task.Factory.StartNew(
() =>
{
try
{
return JsonConvert.DeserializeObject<T>(json);
}
catch
{
return default(T);
}
}).ConfigureAwait(false);
}
public static string StripHtmlTags(this string str)
{
return HtmlRemoval.StripTagsRegex(str);
}
}
} | using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Audiotica.Core.Utils
{
public static class StringExtensions
{
public static string CleanForFileName(this string str, string invalidMessage)
{
if (string.IsNullOrEmpty(str))
{
return null;
}
/*
* A filename cannot contain any of the following characters:
* \ / : * ? " < > |
*/
var name =
str.Replace("\\", string.Empty)
.Replace("/", string.Empty)
.Replace(":", " ")
.Replace("*", string.Empty)
.Replace("?", string.Empty)
.Replace("\"", "'")
.Replace("<", string.Empty)
.Replace(">", string.Empty)
.Replace("|", " ");
return string.IsNullOrEmpty(name) ? invalidMessage : name;
}
public static async Task<T> DeserializeAsync<T>(this string json)
{
return await Task.Factory.StartNew(
() =>
{
try
{
return JsonConvert.DeserializeObject<T>(json);
}
catch
{
return default(T);
}
}).ConfigureAwait(false);
}
public static string StripHtmlTags(this string str)
{
return HtmlRemoval.StripTagsRegex(str);
}
}
} | apache-2.0 | C# |
98ab104861f5e94ab1716a9b613f12973ae88c9a | add storage accounts link | jittuu/AzureLog,jittuu/AzureLog,jittuu/AzureLog | AzureLog.Web/Views/Shared/_Layout.cshtml | AzureLog.Web/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - AzureLog</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-default 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("AzureLog", "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")</li>
<li>@Html.ActionLink("Storage Accounts", "Index", "StorageAccounts")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<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>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - AzureLog</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-default 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("AzureLog", "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")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<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# |
871de9aa5f4b2359930553c6a236cbe323232ba7 | Add check for .dotnet directory | dotnet/core | samples/dependadotnet/Program.cs | samples/dependadotnet/Program.cs | using System;
using System.IO;
using System.Text.RegularExpressions;
using static System.Console;
if (args is { Length: 0 } || args[0] is not string path)
{
WriteLine("Must specify a repo root directory as input");
return;
}
// yaml top-matter
string topMatter =
@"# generated by dependadotnet
# https://github.com/dotnet/core/tree/master/samples/dependadotnet
version: 2
updates:";
WriteLine(topMatter);
/* Generate the following pattern for each project file:
Note: Wednesday was chosen for quick response to .NET patch Tuesday updates
- package-ecosystem: ""nuget""
directory: ""/"" #projectfilename
schedule:
interval: ""weekly""
day: ""wednesday""
open-pull-requests-limit: 5
*/
string regex = @"PackageReference.*Version=""[0-9]";
string dotnetDir = $"{Path.AltDirectorySeparatorChar}.dotnet";
foreach (string file in Directory.EnumerateFiles(path,"*.*",SearchOption.AllDirectories))
{
if (!IsProject(file))
{
continue;
}
string filename = Path.GetFileName(file);
string? parentDir = Path.GetDirectoryName(file);
string relativeDir = parentDir?.Substring(path.Length).Replace(Path.DirectorySeparatorChar,Path.AltDirectorySeparatorChar) ?? Path.AltDirectorySeparatorChar.ToString();
if (relativeDir.StartsWith(dotnetDir))
{
continue;
}
bool match = false;
foreach (string content in File.ReadLines(file))
{
if (Regex.IsMatch(content, regex))
{
match = true;
break;
}
}
if (!match)
{
continue;
}
WriteLine(
$@" - package-ecosystem: ""nuget""
directory: ""{relativeDir}"" #{filename}
schedule:
interval: ""weekly""
day: ""wednesday""
open-pull-requests-limit: 5");
}
bool IsProject(string filename) => Path.GetExtension(filename) switch
{
".csproj" or ".fsproj" or ".vbproj" or ".props" => true,
_ => false
};
| using System;
using System.IO;
using System.Text.RegularExpressions;
using static System.Console;
if (args is { Length: 0 } || args[0] is not string path)
{
WriteLine("Must specify a repo root directory as input");
return;
}
// yaml top-matter
string topMatter =
@"# generated by dependadotnet
# https://github.com/dotnet/core/tree/master/samples/dependadotnet
version: 2
updates:";
WriteLine(topMatter);
/* Generate the following pattern for each project file:
Note: Wednesday was chosen for quick response to .NET patch Tuesday updates
- package-ecosystem: ""nuget""
directory: ""/"" #projectfilename
schedule:
interval: ""weekly""
day: ""wednesday""
open-pull-requests-limit: 5
*/
string regex = @"PackageReference.*Version=""[0-9]";
foreach (string file in Directory.EnumerateFiles(path,"*.*",SearchOption.AllDirectories))
{
if (!IsProject(file))
{
continue;
}
string filename = Path.GetFileName(file);
string? parentDir = Path.GetDirectoryName(file);
string relativeDir = parentDir?.Substring(path.Length).Replace(Path.DirectorySeparatorChar,Path.AltDirectorySeparatorChar) ?? Path.AltDirectorySeparatorChar.ToString();
bool match = false;
foreach (string content in File.ReadLines(file))
{
if (Regex.IsMatch(content, regex))
{
match = true;
break;
}
}
if (!match)
{
continue;
}
WriteLine(
$@" - package-ecosystem: ""nuget""
directory: ""{relativeDir}"" #{filename}
schedule:
interval: ""weekly""
day: ""wednesday""
open-pull-requests-limit: 5");
}
bool IsProject(string filename) => Path.GetExtension(filename) switch
{
".csproj" or ".fsproj" or ".vbproj" or ".props" => true,
_ => false
};
| mit | C# |
3a8ec2e3f10f9eb5fad6dc4912df53c3b593ad16 | create singleton to database entity context | pashchuk/Hospital-app | HospitalLibrary/DatabaseModel.Context.cs | HospitalLibrary/DatabaseModel.Context.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HospitalLibrary
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class HospitalEntities : DbContext
{
private static volatile HospitalEntities _entity;
private static object _lockObjeck = new object();
public HospitalEntities()
: base("name=HospitalEntities")
{
}
public static HospitalEntities GetEntity()
{
if (_entity == null)
lock (_lockObjeck)
if (_entity == null)
_entity = new HospitalEntities();
return _entity;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Card> cards { get; set; }
public DbSet<Diagnosis> diagnosis { get; set; }
public DbSet<Group> groups { get; set; }
public DbSet<Note> notes { get; set; }
public DbSet<Session> sessions { get; set; }
public DbSet<User> users { get; set; }
}
}
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HospitalLibrary
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class HospitalEntities : DbContext
{
public HospitalEntities()
: base("name=HospitalEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Card> cards { get; set; }
public DbSet<Diagnosis> diagnosis { get; set; }
public DbSet<Group> groups { get; set; }
public DbSet<Note> notes { get; set; }
public DbSet<Session> sessions { get; set; }
public DbSet<User> users { get; set; }
}
}
| apache-2.0 | C# |
a805a8ee500a492f33b889b249a6466ae5e5c4e8 | Remove tray icon on safe exit. | polyethene/IronAHK,polyethene/IronAHK,michaltakac/IronAHK,michaltakac/IronAHK,yatsek/IronAHK,michaltakac/IronAHK,yatsek/IronAHK,yatsek/IronAHK,michaltakac/IronAHK,yatsek/IronAHK,michaltakac/IronAHK,polyethene/IronAHK,yatsek/IronAHK,polyethene/IronAHK | Scripting/Script/Menu.cs | Scripting/Script/Menu.cs | using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
namespace IronAHK.Scripting
{
partial class Script
{
public static void CreateTrayMenu()
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
return;
var menu = new NotifyIcon { ContextMenu = new ContextMenu() };
menu.ContextMenu.MenuItems.Add(new MenuItem("&Reload", delegate { Application.Restart(); }));
menu.ContextMenu.MenuItems.Add(new MenuItem("&Exit", delegate { Environment.Exit(0); }));
var favicon = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Script).FullName + ".favicon.ico");
if (favicon != null)
{
menu.Icon = new Icon(favicon);
menu.Visible = true;
}
ApplicationExit += delegate
{
menu.Visible = false;
menu.Dispose();
};
}
}
}
| using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
namespace IronAHK.Scripting
{
partial class Script
{
public static void CreateTrayMenu()
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
return;
var menu = new NotifyIcon { ContextMenu = new ContextMenu() };
menu.ContextMenu.MenuItems.Add(new MenuItem("&Reload", delegate { Application.Restart(); }));
menu.ContextMenu.MenuItems.Add(new MenuItem("&Exit", delegate { Environment.Exit(0); }));
var favicon = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Script).FullName + ".favicon.ico");
if (favicon != null)
{
menu.Icon = new Icon(favicon);
menu.Visible = true;
}
}
}
}
| bsd-2-clause | C# |
8c162585b8ebcf37f50009d17e44cff55d732784 | Comment out logging for debugging purposes | peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu | osu.Game.Rulesets.Taiko/Difficulty/Skills/Colour.cs | osu.Game.Rulesets.Taiko/Difficulty/Skills/Colour.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
/// <summary>
/// Calculates the colour coefficient of taiko difficulty.
/// </summary>
public class Colour : StrainDecaySkill
{
protected override double SkillMultiplier => 1;
protected override double StrainDecayBase => 0.4;
public Colour(Mod[] mods)
: base(mods)
{
}
protected override double StrainValueOf(DifficultyHitObject current)
{
TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)current).Colour;
double difficulty = colour == null ? 0 : colour.EvaluatedDifficulty;
// if (current != null && colour != null)
// {
// ColourEncoding[] payload = colour.Encoding.Payload;
// string payloadDisplay = "";
// for (int i = 0; i < payload.Length; ++i)
// {
// payloadDisplay += $",({payload[i].MonoRunLength},{payload[i].EncodingRunLength})";
// }
// System.Console.WriteLine($"{current.StartTime},{colour.RepetitionInterval},{colour.Encoding.RunLength}{payloadDisplay}");
// }
return difficulty;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
/// <summary>
/// Calculates the colour coefficient of taiko difficulty.
/// </summary>
public class Colour : StrainDecaySkill
{
protected override double SkillMultiplier => 1;
protected override double StrainDecayBase => 0.4;
public Colour(Mod[] mods)
: base(mods)
{
}
protected override double StrainValueOf(DifficultyHitObject current)
{
TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)current).Colour;
double difficulty = colour == null ? 0 : colour.EvaluatedDifficulty;
if (current != null && colour != null)
{
ColourEncoding[] payload = colour.Encoding.Payload;
string payloadDisplay = "";
for (int i = 0; i < payload.Length; ++i)
{
payloadDisplay += $",({payload[i].MonoRunLength},{payload[i].EncodingRunLength})";
}
System.Console.WriteLine($"{current.StartTime},{colour.RepetitionInterval},{colour.Encoding.RunLength}{payloadDisplay}");
}
return difficulty;
}
}
}
| mit | C# |
71edd314b1785106be7b55c3ed638c6571d70521 | Simplify `SmokeContainer` lifetime logic | ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu | osu.Game.Rulesets.Osu/UI/SmokeContainer.cs | osu.Game.Rulesets.Osu/UI/SmokeContainer.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Osu.Skinning;
using osu.Game.Rulesets.Osu.Skinning.Default;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Osu.UI
{
/// <summary>
/// Manages smoke trails generated from user input.
/// </summary>
public class SmokeContainer : Container, IRequireHighFrequencyMousePosition, IKeyBindingHandler<OsuAction>
{
private SkinnableDrawable? currentSegmentSkinnable;
private Vector2 lastMousePosition;
public override bool ReceivePositionalInputAt(Vector2 _) => true;
public bool OnPressed(KeyBindingPressEvent<OsuAction> e)
{
if (e.Action == OsuAction.Smoke)
{
AddInternal(currentSegmentSkinnable = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.SmokeTrail), _ => new DefaultSmokeSegment()));
// Add initial position immediately.
addPosition();
return true;
}
return false;
}
public void OnReleased(KeyBindingReleaseEvent<OsuAction> e)
{
if (e.Action == OsuAction.Smoke)
{
if (currentSegmentSkinnable?.Drawable is SmokeSegment segment)
{
segment.FinishDrawing(Time.Current);
currentSegmentSkinnable.LifetimeEnd = segment.LifetimeEnd;
currentSegmentSkinnable = null;
}
}
}
protected override bool OnMouseMove(MouseMoveEvent e)
{
lastMousePosition = e.MousePosition;
addPosition();
return base.OnMouseMove(e);
}
private void addPosition() => (currentSegmentSkinnable?.Drawable as SmokeSegment)?.AddPosition(lastMousePosition, Time.Current);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Osu.Skinning;
using osu.Game.Rulesets.Osu.Skinning.Default;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Rulesets.Osu.UI
{
/// <summary>
/// Manages smoke trails generated from user input.
/// </summary>
public class SmokeContainer : Container, IRequireHighFrequencyMousePosition, IKeyBindingHandler<OsuAction>
{
public Vector2 LastMousePosition;
private SkinnableDrawable? currentSegment;
public override bool ReceivePositionalInputAt(Vector2 _) => true;
public bool OnPressed(KeyBindingPressEvent<OsuAction> e)
{
if (e.Action == OsuAction.Smoke)
{
AddInternal(currentSegment = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.SmokeTrail), _ => new DefaultSmokeSegment()));
addPosition(LastMousePosition, Time.Current);
return true;
}
return false;
}
private void addPosition(Vector2 position, double timeCurrent) => (currentSegment?.Drawable as SmokeSegment)?.AddPosition(position, timeCurrent);
public void OnReleased(KeyBindingReleaseEvent<OsuAction> e)
{
if (e.Action == OsuAction.Smoke)
{
(currentSegment?.Drawable as SmokeSegment)?.FinishDrawing(Time.Current);
currentSegment = null;
foreach (Drawable child in Children)
{
var skinnable = (SkinnableDrawable)child;
skinnable.LifetimeEnd = skinnable.Drawable.LifetimeEnd;
}
}
}
protected override bool OnMouseMove(MouseMoveEvent e)
{
if (currentSegment != null)
addPosition(e.MousePosition, Time.Current);
LastMousePosition = e.MousePosition;
return base.OnMouseMove(e);
}
}
}
| mit | C# |
4ecc52912c12f2260c414a22e06afd68d86677b9 | Fix typo in unit test name | paiden/Nett | Test/Nett.UnitTests/TomlConfigTests.cs | Test/Nett.UnitTests/TomlConfigTests.cs | using Xunit;
namespace Nett.UnitTests
{
public class TomlConfigTests
{
[Fact]
public void WhenConfigHasActivator_ActivatorGetsUsed()
{
// Arrange
var config = TomlConfig.Create(cfg => cfg
.ConfigureType<IFoo>(ct => ct
.CreateInstance(() => new Foo())
)
);
string toml = @"[Foo]";
// Act
var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config);
// Assert
Assert.IsType<Foo>(co.Foo);
}
[Fact(DisplayName = "External configuration batch code is executed when configuration is done")]
public void WhenConfigShouldRunExternalConfig_ThisConfigGetsExecuted()
{
// Arrange
var config = TomlConfig.Create(cfg => cfg
.Apply(ExternalConfigurationBatch)
);
string toml = @"[Foo]";
// Act
var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config);
// Assert
Assert.IsType<Foo>(co.Foo);
}
private static void ExternalConfigurationBatch(TomlConfig.ITomlConfigBuilder builder)
{
builder
.ConfigureType<IFoo>(ct => ct
.CreateInstance(() => new Foo())
);
}
class ConfigObject
{
public TestStruct S { get; set; }
}
struct TestStruct
{
public int Value;
}
interface IFoo
{
}
class Foo : IFoo
{
}
class ConfigOjectWithInterface
{
public IFoo Foo { get; set; }
}
}
}
| using Xunit;
namespace Nett.UnitTests
{
public class TomlConfigTests
{
[Fact]
public void WhenConfigHasActivator_ActivatorGetsUsed()
{
// Arrange
var config = TomlConfig.Create(cfg => cfg
.ConfigureType<IFoo>(ct => ct
.CreateInstance(() => new Foo())
)
);
string toml = @"[Foo]";
// Act
var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config);
// Assert
Assert.IsType<Foo>(co.Foo);
}
[Fact(DisplayName = "External configuration batch code is executed when configuration is done")]
public void WhenConfigShouldRunExtenralConfig_ThisConfigGetsExecuted()
{
// Arrange
var config = TomlConfig.Create(cfg => cfg
.Apply(ExternalConfigurationBatch)
);
string toml = @"[Foo]";
// Act
var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config);
// Assert
Assert.IsType<Foo>(co.Foo);
}
private static void ExternalConfigurationBatch(TomlConfig.ITomlConfigBuilder builder)
{
builder
.ConfigureType<IFoo>(ct => ct
.CreateInstance(() => new Foo())
);
}
class ConfigObject
{
public TestStruct S { get; set; }
}
struct TestStruct
{
public int Value;
}
interface IFoo
{
}
class Foo : IFoo
{
}
class ConfigOjectWithInterface
{
public IFoo Foo { get; set; }
}
}
}
| mit | C# |
d070d9ead1bb85971e49215bc5491883313d47c1 | change test for 1128, this worked before | ronnyek/linq2db,LinqToDB4iSeries/linq2db,LinqToDB4iSeries/linq2db,linq2db/linq2db,MaceWindu/linq2db,MaceWindu/linq2db,linq2db/linq2db | Tests/Linq/UserTests/Issue1128Tests.cs | Tests/Linq/UserTests/Issue1128Tests.cs | using System.Threading;
using NUnit.Framework;
namespace Tests.UserTests
{
using LinqToDB;
using LinqToDB.Mapping;
public class Issue1128Tests : TestBase
{
private static int _cnt;
class Issue1128Table
{
public int Id { get; set; }
}
class Issue1128TableDerived : Issue1128Table
{
public string BlaBla { get; set; }
}
MappingSchema SetMappings()
{
// counter added to fix this issue with tests in Firebird
// https://stackoverflow.com/questions/44353607
// it was only working solution for Firebird3
var cnt = Interlocked.Increment(ref _cnt).ToString();
var ms = new MappingSchema(cnt);
var tableName = "Issue1128Table" + cnt;
var mappingBuilder = ms.GetFluentMappingBuilder();
mappingBuilder.Entity<Issue1128Table>()
.HasTableName(tableName)
.Property(x => x.Id).IsColumn().IsNullable(false).HasColumnName("Id").IsPrimaryKey();
return ms;
}
[Test, DataContextSource]
public void TestED(string configuration)
{
var ms = SetMappings();
var ed1 = ms.GetEntityDescriptor(typeof(Issue1128Table));
var ed2 = ms.GetEntityDescriptor(typeof(Issue1128TableDerived));
Assert.AreEqual(ed1.TableName, ed2.TableName);
}
[Test, DataContextSource]
public void Test(string configuration)
{
var ms = SetMappings();
using (var db = GetDataContext(configuration, ms))
{
try
{
db.CreateTable<Issue1128Table>();
}
catch
{
db.DropTable<Issue1128Table>(throwExceptionIfNotExists: false);
db.CreateTable<Issue1128Table>();
}
try
{
db.Insert(new Issue1128TableDerived { Id = 1 });
}
finally
{
db.DropTable<Issue1128Table>();
}
}
}
}
}
| using System.Threading;
using NUnit.Framework;
namespace Tests.UserTests
{
using LinqToDB;
using LinqToDB.Mapping;
public class Issue1128Tests : TestBase
{
private static int _cnt;
class Issue1128Table
{
public int Id { get; set; }
}
class Issue1128TableDerived : Issue1128Table
{
}
MappingSchema SetMappings()
{
// counter added to fix this issue with tests in Firebird
// https://stackoverflow.com/questions/44353607
// it was only working solution for Firebird3
var cnt = Interlocked.Increment(ref _cnt).ToString();
var ms = new MappingSchema(cnt);
var tableName = "Issue1128Table" + cnt;
var mappingBuilder = ms.GetFluentMappingBuilder();
mappingBuilder.Entity<Issue1128Table>()
.HasTableName(tableName)
.Property(x => x.Id).IsColumn().IsNullable(false).HasColumnName("Id").IsPrimaryKey();
return ms;
}
[Test, DataContextSource]
public void TestED(string configuration)
{
var ms = SetMappings();
var ed1 = ms.GetEntityDescriptor(typeof(Issue1128Table));
var ed2 = ms.GetEntityDescriptor(typeof(Issue1128TableDerived));
Assert.AreEqual(ed1.TableName, ed2.TableName);
}
[Test, DataContextSource]
public void Test(string configuration)
{
var ms = SetMappings();
using (var db = GetDataContext(configuration, ms))
{
try
{
db.CreateTable<Issue1128TableDerived>();
}
catch
{
db.DropTable<Issue1128TableDerived>(throwExceptionIfNotExists: false);
db.CreateTable<Issue1128TableDerived>();
}
try
{
db.Insert(new Issue1128TableDerived { Id = 1 });
}
finally
{
db.DropTable<Issue1128TableDerived>();
}
}
}
}
}
| mit | C# |
06e0b06a327fab3a5fce9e9a811e623fba431b42 | Handle Android pen input | peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework | osu.Framework.Android/Input/AndroidTouchHandler.cs | osu.Framework.Android/Input/AndroidTouchHandler.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Android.Views;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges;
using osu.Framework.Platform;
using osuTK.Input;
namespace osu.Framework.Android.Input
{
public class AndroidTouchHandler : InputHandler
{
private readonly AndroidGameView view;
public AndroidTouchHandler(AndroidGameView view)
{
this.view = view;
view.Touch += handleTouches;
view.Hover += handleHover;
}
private void handleTouches(object sender, View.TouchEventArgs e)
{
handlePointerEvent(e.Event);
}
private void handleHover(object sender, View.HoverEventArgs e)
{
handlePointerEvent(e.Event);
}
private void handlePointerEvent(MotionEvent e)
{
PendingInputs.Enqueue(new MousePositionAbsoluteInput
{
Position = new osuTK.Vector2(e.GetX() * view.ScaleX, e.GetY() * view.ScaleY)
});
switch (e.Action & MotionEventActions.Mask)
{
case MotionEventActions.Down:
case MotionEventActions.Move:
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Left, true));
break;
case MotionEventActions.Up:
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Left, false));
break;
}
}
protected override void Dispose(bool disposing)
{
view.Touch -= handleTouches;
view.Hover -= handleHover;
base.Dispose(disposing);
}
public override bool IsActive => true;
public override int Priority => 0;
public override bool Initialize(GameHost host) => true;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Android.Views;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges;
using osu.Framework.Platform;
using osuTK.Input;
namespace osu.Framework.Android.Input
{
public class AndroidTouchHandler : InputHandler
{
private readonly AndroidGameView view;
public AndroidTouchHandler(AndroidGameView view)
{
this.view = view;
view.Touch += handleTouches;
}
private void handleTouches(object sender, View.TouchEventArgs e)
{
PendingInputs.Enqueue(new MousePositionAbsoluteInput
{
Position = new osuTK.Vector2(e.Event.GetX() * view.ScaleX, e.Event.GetY() * view.ScaleY)
});
switch (e.Event.Action & MotionEventActions.Mask)
{
case MotionEventActions.Down:
case MotionEventActions.Move:
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Left, true));
break;
case MotionEventActions.Up:
PendingInputs.Enqueue(new MouseButtonInput(MouseButton.Left, false));
break;
}
}
protected override void Dispose(bool disposing)
{
view.Touch -= handleTouches;
base.Dispose(disposing);
}
public override bool IsActive => true;
public override int Priority => 0;
public override bool Initialize(GameHost host) => true;
}
}
| mit | C# |
4378a1f2aed8e3f7a94d5ddf28c73400da45bebc | Allow virtual SampleChannels to count towards statistics | smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework | osu.Framework/Audio/Sample/SampleChannelVirtual.cs | osu.Framework/Audio/Sample/SampleChannelVirtual.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Audio.Sample
{
/// <summary>
/// A <see cref="SampleChannel"/> which explicitly plays no audio.
/// Aimed for scenarios in which a non-null <see cref="SampleChannel"/> is needed, but one that doesn't necessarily play any sound.
/// </summary>
public sealed class SampleChannelVirtual : SampleChannel
{
public SampleChannelVirtual()
: base(new SampleVirtual(), _ => { })
{
}
public override bool Playing => false;
private class SampleVirtual : Sample
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Audio.Sample
{
/// <summary>
/// A <see cref="SampleChannel"/> which explicitly plays no audio.
/// Aimed for scenarios in which a non-null <see cref="SampleChannel"/> is needed, but one that doesn't necessarily play any sound.
/// </summary>
public sealed class SampleChannelVirtual : SampleChannel
{
public SampleChannelVirtual()
: base(new SampleVirtual(), _ => { })
{
}
public override bool Playing => false;
protected override void UpdateState()
{
// empty override to avoid affecting sample channel count in frame statistics
}
private class SampleVirtual : Sample
{
}
}
}
| mit | C# |
fab5b3c08daa185db62acbddffebf1e861adf361 | Update SharedAssemblyInfo.cs | wieslawsoltes/AvaloniaBehaviors,XamlBehaviors/XamlBehaviors,XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors | src/Shared/SharedAssemblyInfo.cs | src/Shared/SharedAssemblyInfo.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany("Wiesław Šoltés")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2017")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyProduct("Avalonia")]
[assembly: AssemblyTrademark("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
[assembly: AssemblyInformationalVersion("0.5.0")]
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany("Wiesław Šoltés")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2016")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyProduct("Avalonia")]
[assembly: AssemblyTrademark("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
[assembly: AssemblyInformationalVersion("0.5.0")]
| mit | C# |
fe6be0b23ac317d593503d2764c109798ec409f6 | Move BodyPart up | jtkech/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,lukaskabrt/Orchard2,lukaskabrt/Orchard2,xkproject/Orchard2,yiji/Orchard2,lukaskabrt/Orchard2,petedavis/Orchard2,jtkech/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,lukaskabrt/Orchard2,petedavis/Orchard2,xkproject/Orchard2,jtkech/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,yiji/Orchard2,yiji/Orchard2,jtkech/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard | src/Orchard.Cms.Web/Modules/Orchard.Body/Drivers/BodyPartDisplay.cs | src/Orchard.Cms.Web/Modules/Orchard.Body/Drivers/BodyPartDisplay.cs | using System.Linq;
using System.Threading.Tasks;
using Orchard.Body.Model;
using Orchard.Body.Settings;
using Orchard.Body.ViewModels;
using Orchard.ContentManagement.Display.ContentDisplay;
using Orchard.ContentManagement.MetaData;
using Orchard.DisplayManagement.ModelBinding;
using Orchard.DisplayManagement.Views;
namespace Orchard.Body.Drivers
{
public class BodyPartDisplay : ContentPartDisplayDriver<BodyPart>
{
private readonly IContentDefinitionManager _contentDefinitionManager;
public BodyPartDisplay(IContentDefinitionManager contentDefinitionManager)
{
_contentDefinitionManager = contentDefinitionManager;
}
public override IDisplayResult Display(BodyPart bodyPart)
{
return Combine(
Shape<BodyPartViewModel>("BodyPart", m => BuildViewModel(m, bodyPart))
.Location("Detail", "Content:5"),
Shape<BodyPartViewModel>("BodyPart_Summary", m => BuildViewModel(m, bodyPart))
.Location("Summary", "Content:10")
);
}
public override IDisplayResult Edit(BodyPart bodyPart)
{
return Shape<BodyPartViewModel>("BodyPart_Edit", m => BuildViewModel(m, bodyPart));
}
public override async Task<IDisplayResult> UpdateAsync(BodyPart model, IUpdateModel updater)
{
await updater.TryUpdateModelAsync(model, Prefix, t => t.Body);
return Edit(model);
}
private Task BuildViewModel(BodyPartViewModel model, BodyPart bodyPart)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(bodyPart.ContentItem.ContentType);
var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(p => p.PartDefinition.Name == nameof(BodyPart));
var settings = contentTypePartDefinition.GetSettings<BodyPartSettings>();
model.Body = bodyPart.Body;
model.BodyPart = bodyPart;
model.TypePartSettings = settings;
return Task.CompletedTask;
}
}
}
| using System.Linq;
using System.Threading.Tasks;
using Orchard.Body.Model;
using Orchard.Body.Settings;
using Orchard.Body.ViewModels;
using Orchard.ContentManagement.Display.ContentDisplay;
using Orchard.ContentManagement.MetaData;
using Orchard.DisplayManagement.ModelBinding;
using Orchard.DisplayManagement.Views;
namespace Orchard.Body.Drivers
{
public class BodyPartDisplay : ContentPartDisplayDriver<BodyPart>
{
private readonly IContentDefinitionManager _contentDefinitionManager;
public BodyPartDisplay(IContentDefinitionManager contentDefinitionManager)
{
_contentDefinitionManager = contentDefinitionManager;
}
public override IDisplayResult Display(BodyPart bodyPart)
{
return Combine(
Shape<BodyPartViewModel>("BodyPart", m => BuildViewModel(m, bodyPart))
.Location("Detail", "Content:10"),
Shape<BodyPartViewModel>("BodyPart_Summary", m => BuildViewModel(m, bodyPart))
.Location("Summary", "Content:10")
);
}
public override IDisplayResult Edit(BodyPart bodyPart)
{
return Shape<BodyPartViewModel>("BodyPart_Edit", m => BuildViewModel(m, bodyPart));
}
public override async Task<IDisplayResult> UpdateAsync(BodyPart model, IUpdateModel updater)
{
await updater.TryUpdateModelAsync(model, Prefix, t => t.Body);
return Edit(model);
}
private Task BuildViewModel(BodyPartViewModel model, BodyPart bodyPart)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(bodyPart.ContentItem.ContentType);
var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(p => p.PartDefinition.Name == nameof(BodyPart));
var settings = contentTypePartDefinition.GetSettings<BodyPartSettings>();
model.Body = bodyPart.Body;
model.BodyPart = bodyPart;
model.TypePartSettings = settings;
return Task.CompletedTask;
}
}
}
| bsd-3-clause | C# |
31236dc6d80ec6808e46674ce92a1913ab987d27 | Add body abstract type checks for string | Unity3dAzure/MobileServices,Unity3dAzure/AppServices | http/ZumoRequest.cs | http/ZumoRequest.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using UnityEngine;
using System.Text;
using RESTClient;
namespace Azure.AppServices {
public sealed class ZumoRequest : RestRequest {
// NB: Exclude system properties is a workaround to ignore read-only system properties during JSON utility deserialization.
// If set to true then App Services System Properties will be stripped from the request body during deserialization.
private bool excludeSystemProperties;
public ZumoRequest(string url, Method httpMethod = Method.GET, bool excludeSystemProperties = true, AuthenticatedUser user = null) : base(url, httpMethod) {
this.excludeSystemProperties = excludeSystemProperties;
this.AddHeader("ZUMO-API-VERSION", "2.0.0");
this.AddHeader("Accept", "application/json");
this.AddHeader("Content-Type", "application/json; charset=utf-8");
// User Authentictated request
if (user != null && !string.IsNullOrEmpty(user.authenticationToken)) {
this.AddHeader("X-ZUMO-AUTH", user.authenticationToken);
}
}
// Facebook, Microsoft Account, Azure Active Directory
public void AddBodyAccessToken(string token) {
AccessToken accessToken = new AccessToken(token);
this.AddBody<AccessToken>(accessToken);
}
// Twitter
public void AddBodyAccessTokenSecret(string token, string tokenSecret) {
AccessTokenSecret accessTokenSecret = new AccessTokenSecret(token, tokenSecret);
this.AddBody<AccessTokenSecret>(accessTokenSecret);
}
// Google+
public void AddBodyAccessTokenId(string token, string idToken) {
AccessTokenId accessTokenId = new AccessTokenId(token, idToken);
this.AddBody<AccessTokenId>(accessTokenId);
}
public override void AddBody<T>(T data, string contentType = "application/json; charset=utf-8") {
if (typeof(T) == typeof(string)) {
this.AddBody(data.ToString(), contentType);
return;
}
string jsonString = excludeSystemProperties ? JsonHelper.ToJsonExcludingSystemProperties(data) : JsonUtility.ToJson(data);
byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
this.AddBody(bytes, contentType);
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using UnityEngine;
using System.Text;
using RESTClient;
namespace Azure.AppServices {
public sealed class ZumoRequest : RestRequest {
// NB: Exclude system properties is a workaround to ignore read-only system properties during JSON utility deserialization.
// If set to true then App Services System Properties will be stripped from the request body during deserialization.
private bool excludeSystemProperties;
public ZumoRequest(string url, Method httpMethod = Method.GET, bool excludeSystemProperties = true, AuthenticatedUser user = null) : base(url, httpMethod) {
this.excludeSystemProperties = excludeSystemProperties;
this.AddHeader("ZUMO-API-VERSION", "2.0.0");
this.AddHeader("Accept", "application/json");
this.AddHeader("Content-Type", "application/json; charset=utf-8");
// User Authentictated request
if (user != null && !string.IsNullOrEmpty(user.authenticationToken)) {
this.AddHeader("X-ZUMO-AUTH", user.authenticationToken);
}
}
// Facebook, Microsoft Account, Azure Active Directory
public void AddBodyAccessToken(string token) {
AccessToken accessToken = new AccessToken(token);
this.AddBody<AccessToken>(accessToken);
}
// Twitter
public void AddBodyAccessTokenSecret(string token, string tokenSecret) {
AccessTokenSecret accessTokenSecret = new AccessTokenSecret(token, tokenSecret);
this.AddBody<AccessTokenSecret>(accessTokenSecret);
}
// Google+
public void AddBodyAccessTokenId(string token, string idToken) {
AccessTokenId accessTokenId = new AccessTokenId(token, idToken);
this.AddBody<AccessTokenId>(accessTokenId);
}
public override void AddBody<T>(T data, string contentType = "application/json; charset=utf-8") {
string jsonString = excludeSystemProperties ? JsonHelper.ToJsonExcludingSystemProperties(data) : JsonUtility.ToJson(data);
byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
this.AddBody(bytes, contentType);
}
}
}
| mit | C# |
78eb7ac6d3268a85ba67497f1fc3db97181842bc | remove default hello from toolbar | joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net | JoinRpg.Portal/Views/Shared/_LoginPartial.cshtml | JoinRpg.Portal/Views/Shared/_LoginPartial.cshtml | @using Microsoft.AspNetCore.Identity
@using Joinrpg.Web.Identity
@inject SignInManager<JoinIdentityUser> SignInManager
@inject UserManager<JoinIdentityUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-controller="Account" asp-action="LogOff" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<img src="https://www.gravatar.com/avatar/@ViewBag.GravatarHash?d=identicon&s=24" /> @ViewBag.UserDisplayName
</a>
<ul class="dropdown-menu">
<li class="dropdown-item">@Html.ActionLink("Профиль", "Me", "User", new { area = "" }, null)</li>
<li class="dropdown-item">@Html.ActionLink("Аккаунт", "Index", "Manage", new { area = "" }, null)</li>
<li class="dropdown-item"><a href="https://docs.joinrpg.ru"><span class="glyphicon glyphicon-question-sign"></span> Помощь</a></li>
@if (User.IsInRole("admin"))
{
<li class="dropdown-item">@Html.ActionLink("Панель администратора", "Index", "AdminHome", new { area = "Admin" }, null)</li>
}
<li class="dropdown-item"><a href="javascript:document.getElementById('logoutForm').submit()">Выйти</a></li>
</ul>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-controller="Account" asp-action="Register">Регистрация</a></li>
<li><a asp-controller="Account" asp-action="Login">Войти</a></li>
<li><a href="https://docs.joinrpg.ru">Помощь</a></li>
</ul>
}
| @using Microsoft.AspNetCore.Identity
@using Joinrpg.Web.Identity
@inject SignInManager<JoinIdentityUser> SignInManager
@inject UserManager<JoinIdentityUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-controller="Account" asp-action="LogOff" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<img src="https://www.gravatar.com/avatar/@ViewBag.GravatarHash?d=identicon&s=24" /> @ViewBag.UserDisplayName
</a>
<ul class="dropdown-menu">
<li class="dropdown-item">@Html.ActionLink("Профиль", "Me", "User", new { area = "" }, null)</li>
<li class="dropdown-item">@Html.ActionLink("Аккаунт", "Index", "Manage", new { area = "" }, null)</li>
<li class="dropdown-item"><a href="https://docs.joinrpg.ru"><span class="glyphicon glyphicon-question-sign"></span> Помощь</a></li>
@if (User.IsInRole("admin"))
{
<li class="dropdown-item">@Html.ActionLink("Панель администратора", "Index", "AdminHome", new { area = "Admin" }, null)</li>
}
<li class="dropdown-item"><a href="javascript:document.getElementById('logoutForm').submit()">Выйти</a></li>
</ul>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-controller="Account" asp-action="Register">Регистрация</a></li>
<li><a asp-controller="Account" asp-action="Login">Войти</a></li>
<li><a href="https://docs.joinrpg.ru">Помощь</a></li>
</ul>
}
| mit | C# |
e133cb4a9f606a34060573ae886461d923791456 | make RuleSet non-sealed | pragmatrix/Rulez | Rulez/RuleSet.cs | Rulez/RuleSet.cs | using System;
using System.Collections.Generic;
namespace Rulez
{
public class RuleSet : IDisposable
{
readonly List<IDisposable> _rules = new List<IDisposable>();
public void Dispose()
{
for (int i = _rules.Count; i != 0; --i)
{
var r = _rules[i - 1];
r.Dispose();
}
_rules.Clear();
}
public void add(Action rule)
{
_rules.Add(Rule.activate(rule));
}
}
}
| using System;
using System.Collections.Generic;
namespace Rulez
{
public sealed class RuleSet : IDisposable
{
readonly List<IDisposable> _rules = new List<IDisposable>();
public void Dispose()
{
for (int i = _rules.Count; i != 0; --i)
{
var r = _rules[i - 1];
r.Dispose();
}
_rules.Clear();
}
public void add(Action rule)
{
_rules.Add(Rule.activate(rule));
}
}
}
| bsd-3-clause | C# |
77eff408f8a0a6c5cca36454ac80afdc3ae73104 | Fix problem with invalid whitespaces and lower characters in input license key code | mohsansaleem/patchkit-patcher-unity,mohsansaleem/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity,patchkit-net/patchkit-patcher-unity | src/Assets/Scripts/Licensing/KeyLicenseObtainer.cs | src/Assets/Scripts/Licensing/KeyLicenseObtainer.cs | using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
namespace PatchKit.Unity.Patcher.Licensing
{
public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer
{
private State _state = State.None;
private KeyLicense _keyLicense;
private Animator _animator;
public InputField KeyInputField;
public GameObject ErrorMessage;
private void Awake()
{
_animator = GetComponent<Animator>();
}
private void Update()
{
_animator.SetBool("IsOpened", _state == State.Obtaining);
ErrorMessage.SetActive(ShowError);
}
public void Cancel()
{
_state = State.Cancelled;
}
public void Confirm()
{
string key = KeyInputField.text;
key = key.ToUpper().Trim();
_keyLicense = new KeyLicense
{
Key = key
};
_state = State.Confirmed;
}
public bool ShowError { get; set; }
ILicense ILicenseObtainer.Obtain()
{
_state = State.Obtaining;
while (_state != State.Confirmed && _state != State.Cancelled)
{
Thread.Sleep(10);
}
if (_state == State.Cancelled)
{
throw new OperationCanceledException();
}
return _keyLicense;
}
private enum State
{
None,
Obtaining,
Confirmed,
Cancelled
}
}
} | using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
namespace PatchKit.Unity.Patcher.Licensing
{
public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer
{
private State _state = State.None;
private KeyLicense _keyLicense;
private Animator _animator;
public InputField KeyInputField;
public GameObject ErrorMessage;
private void Awake()
{
_animator = GetComponent<Animator>();
}
private void Update()
{
_animator.SetBool("IsOpened", _state == State.Obtaining);
ErrorMessage.SetActive(ShowError);
}
public void Cancel()
{
_state = State.Cancelled;
}
public void Confirm()
{
string key = KeyInputField.text;
key = key.ToUpper().Trim();
_keyLicense = new KeyLicense
{
Key = KeyInputField.text
};
_state = State.Confirmed;
}
public bool ShowError { get; set; }
ILicense ILicenseObtainer.Obtain()
{
_state = State.Obtaining;
while (_state != State.Confirmed && _state != State.Cancelled)
{
Thread.Sleep(10);
}
if (_state == State.Cancelled)
{
throw new OperationCanceledException();
}
return _keyLicense;
}
private enum State
{
None,
Obtaining,
Confirmed,
Cancelled
}
}
} | mit | C# |
5b1b8f92afdc9b7a1b787847b99beb19b38d0ae5 | Update Method.cs | hprose/hprose-dotnet | src/Hprose.RPC/Method.cs | src/Hprose.RPC/Method.cs | /*--------------------------------------------------------*\
| |
| hprose |
| |
| Official WebSite: https://hprose.com |
| |
| Method.cs |
| |
| Method class for C#. |
| |
| LastModified: Jan 26, 2019 |
| Author: Ma Bingyao <andot@hprose.com> |
| |
\*________________________________________________________*/
using Hprose.IO;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Hprose.RPC {
public class Method {
public bool Missing { get; set; } = false;
public string Fullname { get; private set; }
public MethodInfo MethodInfo { get; private set; }
public ParameterInfo[] Parameters { get; private set; }
public object Target { get; private set; }
public Method(MethodInfo methodInfo, string fullname, object target = null) {
MethodInfo = methodInfo;
Fullname = fullname ?? methodInfo.Name;
Target = target;
Parameters = methodInfo.GetParameters();
}
public Method(MethodInfo methodInfo, object target = null) : this(methodInfo, methodInfo.Name, target) { }
}
} | /*--------------------------------------------------------*\
| |
| hprose |
| |
| Official WebSite: https://hprose.com |
| |
| Method.cs |
| |
| Method class for C#. |
| |
| LastModified: Jan 26, 2019 |
| Author: Ma Bingyao <andot@hprose.com> |
| |
\*________________________________________________________*/
using Hprose.IO;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Hprose.RPC {
public class Method {
public bool Missing { get; set; } = false;
public string Fullname { get; private set; }
public MethodInfo MethodInfo { get; private set; }
public ParameterInfo[] Parameters { get; private set; }
public object Target { get; private set; }
public Method(MethodInfo methodInfo, string fullname, object target = null) {
MethodInfo = methodInfo;
Fullname = fullname;
Target = target;
Parameters = methodInfo.GetParameters();
}
public Method(MethodInfo methodInfo, object target = null) : this(methodInfo, methodInfo.Name, target) { }
}
} | mit | C# |
ae6b3dd9110b121c67f5de063518c243da15c98a | Initialize DomainCustomization with an TextReaderCustomization | appharbor/appharbor-cli | src/AppHarbor.Tests/DomainCustomization.cs | src/AppHarbor.Tests/DomainCustomization.cs | using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
namespace AppHarbor.Tests
{
public class DomainCustomization : CompositeCustomization
{
public DomainCustomization()
: base(
new AutoMoqCustomization(),
new TextReaderCustomization(),
new TextWriterCustomization())
{
}
}
}
| using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
namespace AppHarbor.Tests
{
public class DomainCustomization : CompositeCustomization
{
public DomainCustomization()
: base(
new AutoMoqCustomization(),
new TextWriterCustomization())
{
}
}
}
| mit | C# |
0708bbab8e27be1258ae62ca00ef304b5978cb25 | Initialize AppDeleteCommand with an IApplicationConfiguration | appharbor/appharbor-cli | src/AppHarbor/Commands/AppDeleteCommand.cs | src/AppHarbor/Commands/AppDeleteCommand.cs | using System;
namespace AppHarbor.Commands
{
[CommandHelp("Delete application")]
public class AppDeleteCommand : ICommand
{
private readonly IAppHarborClient _appharborClient;
private readonly IApplicationConfiguration _applicationConfiguration;
public AppDeleteCommand(IAppHarborClient appharborClient, IApplicationConfiguration applicationConfiguration)
{
_appharborClient = appharborClient;
_applicationConfiguration = applicationConfiguration;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
| using System;
namespace AppHarbor.Commands
{
[CommandHelp("Delete application")]
public class AppDeleteCommand : ICommand
{
private readonly IAppHarborClient _appharborClient;
public AppDeleteCommand(IAppHarborClient appharborClient)
{
_appharborClient = appharborClient;
}
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
475600c7ea6cb655ff1906b76be533fcf52a70ca | Fix typo in AfterMap xml comment | CandidoCleyton/AutoMapper,BlaiseD/AutoMapper,TylerCarlson1/AutoMapper,mjalil/AutoMapper,seanlin816/AutoMapper,mwpowellhtx/MicroMapper,jbogard/AutoMapper,michaelkauflin/AutoMapper,jasonholloway/AutoMapper,jnm2/AutoMapper,lbargaoanu/AutoMapper,gentledepp/AutoMapper,AutoMapper/AutoMapper,sh-sabooni/AutoMapper,AutoMapper/AutoMapper | src/AutoMapper/IMappingOperationOptions.cs | src/AutoMapper/IMappingOperationOptions.cs | namespace AutoMapper
{
using System;
using System.Collections.Generic;
/// <summary>
/// Options for a single map operation
/// </summary>
public interface IMappingOperationOptions
{
/// <summary>
/// Construct services using this callback. Use this for child/nested containers
/// </summary>
/// <param name="constructor"></param>
void ConstructServicesUsing(Func<Type, object> constructor);
/// <summary>
/// Create any missing type maps, if found
/// </summary>
bool CreateMissingTypeMaps { get; set; }
/// <summary>
/// Add context items to be accessed at map time inside an <see cref="IValueResolver"/> or <see cref="ITypeConverter{TSource, TDestination}"/>
/// </summary>
IDictionary<string, object> Items { get; }
/// <summary>
/// Disable the cache used to re-use destination instances based on equality
/// </summary>
bool DisableCache { get; set; }
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
void BeforeMap(Action<object, object> beforeFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
void AfterMap(Action<object, object> afterFunction);
}
public interface IMappingOperationOptions<TSource, TDestination> : IMappingOperationOptions
{
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
void BeforeMap(Action<TSource, TDestination> beforeFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types after member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
void AfterMap(Action<TSource, TDestination> afterFunction);
}
}
| namespace AutoMapper
{
using System;
using System.Collections.Generic;
/// <summary>
/// Options for a single map operation
/// </summary>
public interface IMappingOperationOptions
{
/// <summary>
/// Construct services using this callback. Use this for child/nested containers
/// </summary>
/// <param name="constructor"></param>
void ConstructServicesUsing(Func<Type, object> constructor);
/// <summary>
/// Create any missing type maps, if found
/// </summary>
bool CreateMissingTypeMaps { get; set; }
/// <summary>
/// Add context items to be accessed at map time inside an <see cref="IValueResolver"/> or <see cref="ITypeConverter{TSource, TDestination}"/>
/// </summary>
IDictionary<string, object> Items { get; }
/// <summary>
/// Disable the cache used to re-use destination instances based on equality
/// </summary>
bool DisableCache { get; set; }
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
void BeforeMap(Action<object, object> beforeFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
void AfterMap(Action<object, object> afterFunction);
}
public interface IMappingOperationOptions<TSource, TDestination> : IMappingOperationOptions
{
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="beforeFunction">Callback for the source/destination types</param>
void BeforeMap(Action<TSource, TDestination> beforeFunction);
/// <summary>
/// Execute a custom function to the source and/or destination types before member mapping
/// </summary>
/// <param name="afterFunction">Callback for the source/destination types</param>
void AfterMap(Action<TSource, TDestination> afterFunction);
}
} | mit | C# |
c3346bac2c6f3bec6dae2ebe5f1b004ba2df6beb | extend clearable | YarGU-Demidov/math-site,YarGU-Demidov/math-site,YarGU-Demidov/math-site,YarGU-Demidov/math-site,YarGU-Demidov/math-site | src/MathSite.Db/DbExtensions/ClearableDbContext.cs | src/MathSite.Db/DbExtensions/ClearableDbContext.cs | using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace MathSite.Db.DbExtensions
{
public static class ClearableDbContext
{
public static async Task Clear<TEntity>(this MathSiteDbContext context, string tableName = null)
where TEntity : class
{
try
{
await context.Database.ExecuteSqlCommandAsync($"TRUNCATE TABLE \"{tableName ?? typeof(TEntity).Name}\"");
}
catch (Exception e) when (e.GetType().Name == "SqliteException")
{
try
{
var sql = $"DELETE FROM \"{tableName ?? typeof(TEntity).Name}\"";
await context.Database.ExecuteSqlCommandAsync(sql);
}
catch (Exception)
{
context.Set<TEntity>().RemoveRange(context.Set<TEntity>());
}
}
}
}
} | using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace MathSite.Db.DbExtensions
{
public static class ClearableDbContext
{
public static async Task Clear<TEntity>(this MathSiteDbContext context, string tableName = null)
where TEntity : class
{
try
{
await context.Database.ExecuteSqlCommandAsync($"TRUNCATE TABLE \"{tableName ?? typeof(TEntity).Name}\"");
}
catch (Exception e) when (e.GetType().Name == "SqliteException")
{
var sql = $"DELETE FROM \"{tableName ?? typeof(TEntity).Name}\"";
await context.Database.ExecuteSqlCommandAsync(sql);
}
}
}
} | mit | C# |
2397720ff9e15919eb8501b6ec86ec751f58b1e7 | Fix collection aggregate | StanleyGoldman/NRules,prashanthr/NRules,NRules/NRules,StanleyGoldman/NRules | src/NRules/NRules.RuleModel/CollectionAggregate.cs | src/NRules/NRules.RuleModel/CollectionAggregate.cs | using System.Collections.Generic;
namespace NRules.RuleModel
{
/// <summary>
/// Aggregate that folds matching facts into a collection.
/// </summary>
/// <typeparam name="T">Type of facts to collect.</typeparam>
internal class CollectionAggregate<T> : IAggregate
{
private readonly List<T> _items = new List<T>();
private bool _initialized;
public AggregationResults Add(object fact)
{
_items.Add((T) fact);
if (!_initialized)
{
_initialized = true;
return AggregationResults.Added;
}
return AggregationResults.Modified;
}
public AggregationResults Modify(object fact)
{
return AggregationResults.None;
}
public AggregationResults Remove(object fact)
{
_items.Remove((T) fact);
if (_items.Count > 0)
{
return AggregationResults.Modified;
}
return AggregationResults.Removed;
}
public object Result
{
get { return _items; }
}
}
} | using System.Collections.Generic;
namespace NRules.RuleModel
{
/// <summary>
/// Aggregate that folds matching facts into a collection.
/// </summary>
/// <typeparam name="T">Type of facts to collect.</typeparam>
internal class CollectionAggregate<T> : IAggregate
{
private readonly List<T> _items = new List<T>();
private bool _initialized;
public AggregationResults Add(object fact)
{
_items.Add((T) fact);
if (!_initialized)
{
_initialized = true;
return AggregationResults.Added;
}
return AggregationResults.Modified;
}
public AggregationResults Modify(object fact)
{
return AggregationResults.Modified;
}
public AggregationResults Remove(object fact)
{
_items.Remove((T) fact);
if (_items.Count > 0)
{
return AggregationResults.Modified;
}
return AggregationResults.Removed;
}
public object Result
{
get { return _items; }
}
}
} | mit | C# |
51928be80a138cadf3a8f3507c88dd01096cf0ae | Order by filename ASC, so that detached versions appear always after the original photo, even if Reverse Order is used | NguyenMatthieu/f-spot,GNOME/f-spot,mono/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,NguyenMatthieu/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,GNOME/f-spot,GNOME/f-spot,dkoeb/f-spot,Sanva/f-spot,mans0954/f-spot,Yetangitu/f-spot,mono/f-spot,Sanva/f-spot,Yetangitu/f-spot,Sanva/f-spot,dkoeb/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,GNOME/f-spot,Yetangitu/f-spot,mans0954/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,nathansamson/F-Spot-Album-Exporter,Yetangitu/f-spot,mans0954/f-spot,mono/f-spot,mono/f-spot,NguyenMatthieu/f-spot,dkoeb/f-spot,nathansamson/F-Spot-Album-Exporter,mans0954/f-spot,GNOME/f-spot,dkoeb/f-spot,dkoeb/f-spot,Sanva/f-spot,mono/f-spot,dkoeb/f-spot | src/Query/OrderByTime.cs | src/Query/OrderByTime.cs | /*
* FSpot.Query.OrderByTime.cs
*
* Author(s):
* Stephane Delcroix <stephane@delcroix.org>
*
* This is free software. See COPYING for details.
*
*/
using System;
using FSpot.Utils;
namespace FSpot.Query {
public class OrderByTime : IQueryCondition, IOrderCondition
{
public static OrderByTime OrderByTimeAsc = new OrderByTime (true);
public static OrderByTime OrderByTimeDesc = new OrderByTime (false);
bool asc;
public bool Asc {
get { return asc; }
}
public OrderByTime (bool asc)
{
this.asc = asc;
}
public string SqlClause ()
{
// filenames must always appear in alphabetical order if times are the same
return String.Format (" time {0}, filename ASC ", asc ? "ASC" : "DESC");
}
}
}
| /*
* FSpot.Query.OrderByTime.cs
*
* Author(s):
* Stephane Delcroix <stephane@delcroix.org>
*
* This is free software. See COPYING for details.
*
*/
using System;
using FSpot.Utils;
namespace FSpot.Query {
public class OrderByTime : IQueryCondition, IOrderCondition
{
public static OrderByTime OrderByTimeAsc = new OrderByTime (true);
public static OrderByTime OrderByTimeDesc = new OrderByTime (false);
bool asc;
public bool Asc {
get { return asc; }
}
public OrderByTime (bool asc)
{
this.asc = asc;
}
public string SqlClause ()
{
return String.Format (" time {0}, filename {0} ", asc ? "ASC" : "DESC");
}
}
}
| mit | C# |
9a4d62d011ac3debcc789b64cc6352c083e21b50 | Add some comments to the new PhotosDirectory field so users understand how it is used. | JC-Chris/XFExtensions | XFExtensions.MetaMedia/MetaMediaPlugin.Abstractions/IMediaService.cs | XFExtensions.MetaMedia/MetaMediaPlugin.Abstractions/IMediaService.cs | using System.Threading.Tasks;
namespace MetaMediaPlugin.Abstractions
{
public interface IMediaService
{
bool IsCameraAvailable { get; }
bool IsTakePhotoSupported { get; }
bool IsPickPhotoSupported { get; }
/// <summary>
/// Specify the photo directory to use for your app.
/// In iOS, this has no effect.
/// In Android, this will be the name of the subdirectory within the shared photos directory.
/// </summary>
/// <value>The photos directory.</value>
string PhotosDirectory { get; set; } // this is only used in Android to specify the sub-directory in photos that your app uses
Task<IMediaFile> PickPhotoAsync();
Task<IMediaFile> TakePhotoAsync();
}
} | using System.Threading.Tasks;
namespace MetaMediaPlugin.Abstractions
{
public interface IMediaService
{
bool IsCameraAvailable { get; }
bool IsTakePhotoSupported { get; }
bool IsPickPhotoSupported { get; }
string PhotosDirectory { get; set; } // this is only used in Android to specify the sub-directory in photos that your app uses
Task<IMediaFile> PickPhotoAsync();
Task<IMediaFile> TakePhotoAsync();
}
} | apache-2.0 | C# |
874bae2cfe37ea4efce392bb9d3407f03faa25ca | delete unused | saturn72/saturn72 | src/Core/Saturn72.Core/Infrastructure/DependencyManagement/IIocRegistrator.cs | src/Core/Saturn72.Core/Infrastructure/DependencyManagement/IIocRegistrator.cs | #region
using System;
using System.Collections.Generic;
#endregion
namespace Saturn72.Core.Infrastructure.DependencyManagement
{
public interface IIocRegistrator
{
IocRegistrationRecord RegisterInstance<TService>(TService implementation, object key = null, Type[] interceptorTypes = null)
where TService : class;
IocRegistrationRecord RegisterType<TServiceImpl, TService>(LifeCycle lifecycle, object key = null, Type[] interceptorTypes = null)
where TService : class
where TServiceImpl : TService;
void RegisterTypes(LifeCycle lifeCycle, params Type[] serviceImplTypes);
void RegisterType(Type serviceImplType, LifeCycle lifeCycle = LifeCycle.PerDependency, Type[] interceptorTypes = null);
void RegisterType<TServiceImpl>(LifeCycle lifeCycle = LifeCycle.PerDependency);
IocRegistrationRecord RegisterType(Type serviceImplType, Type serviceType, LifeCycle lifecycle, object key = null, Type[] interceptorTypes = null);
IocRegistrationRecord RegisterType(Type serviceImplType, Type[] serviceTypes, LifeCycle lifecycle, Type[] interceptorTypes = null);
void Register(IEnumerable<Action<IIocRegistrator>> registerActions);
IocRegistrationRecord Register<TService>(Func<TService> resolveHandler, LifeCycle lifecycle, object key = null, Type[] interceptorTypes = null);
void RegisterDelegate<TService>(Func<IIocResolver, TService> func, LifeCycle lifeCycle, Type[] interceptorTypes = null);
}
} | #region
using System;
using System.Collections.Generic;
using Castle.DynamicProxy;
#endregion
namespace Saturn72.Core.Infrastructure.DependencyManagement
{
public interface IIocRegistrator
{
IocRegistrationRecord RegisterInstance<TService>(TService implementation, object key = null, Type[] interceptorTypes = null)
where TService : class;
IocRegistrationRecord RegisterType<TServiceImpl, TService>(LifeCycle lifecycle, object key = null, Type[] interceptorTypes = null)
where TService : class
where TServiceImpl : TService;
void RegisterTypes(LifeCycle lifeCycle, params Type[] serviceImplTypes);
void RegisterType(Type serviceImplType, LifeCycle lifeCycle = LifeCycle.PerDependency, Type[] interceptorTypes = null);
void RegisterType<TServiceImpl>(LifeCycle lifeCycle = LifeCycle.PerDependency);
IocRegistrationRecord RegisterType(Type serviceImplType, Type serviceType, LifeCycle lifecycle, object key = null, Type[] interceptorTypes = null);
IocRegistrationRecord RegisterType(Type serviceImplType, Type[] serviceTypes, LifeCycle lifecycle, Type[] interceptorTypes = null);
void Register(IEnumerable<Action<IIocRegistrator>> registerActions);
IocRegistrationRecord Register<TService>(Func<TService> resolveHandler, LifeCycle lifecycle, object key = null, Type[] interceptorTypes = null);
void RegisterDelegate<TService>(Func<IIocResolver, TService> func, LifeCycle lifeCycle, Type[] interceptorTypes = null);
}
} | mit | C# |
df0e7d05d66f8c458b2fb4db9a9cacbe3899f9c5 | tidy up formatting | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EAS.Portal/Application/Services/Commitments/CommitmentsService.cs | src/SFA.DAS.EAS.Portal/Application/Services/Commitments/CommitmentsService.cs | using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SFA.DAS.Commitments.Api.Types.Commitment;
using SFA.DAS.EAS.Portal.Application.Services.Commitments.Http;
using SFA.DAS.Http;
namespace SFA.DAS.EAS.Portal.Application.Services.Commitments
{
public class CommitmentsService : ICommitmentsService
{
private readonly ILogger<CommitmentsService> _log;
private readonly RestHttpClient _restHttpClient;
public CommitmentsService(
ICommitmentsApiHttpClientFactory commitmentsApiHttpClientFactory,
ILogger<CommitmentsService> log)
{
_log = log;
_restHttpClient = new RestHttpClient(commitmentsApiHttpClientFactory.CreateHttpClient());
}
public Task<CommitmentView> GetProviderCommitment(
long providerId,
long commitmentId,
CancellationToken cancellationToken = default)
{
_log.LogInformation($"Getting commitment {commitmentId} for provider {providerId}");
return _restHttpClient.Get<CommitmentView>(
$"/api/provider/{providerId}/commitments/{commitmentId}",
null,
cancellationToken);
}
}
} | using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SFA.DAS.Commitments.Api.Types.Commitment;
using SFA.DAS.EAS.Portal.Application.Services.Commitments.Http;
using SFA.DAS.Http;
namespace SFA.DAS.EAS.Portal.Application.Services.Commitments
{
public class CommitmentsService : ICommitmentsService
{
private readonly ILogger<CommitmentsService> _log;
private readonly RestHttpClient _restHttpClient;
public CommitmentsService(ICommitmentsApiHttpClientFactory commitmentsApiHttpClientFactory, ILogger<CommitmentsService> log)
{
_log = log;
_restHttpClient = new RestHttpClient(commitmentsApiHttpClientFactory.CreateHttpClient());
}
public Task<CommitmentView> GetProviderCommitment(long providerId, long commitmentId,
CancellationToken cancellationToken = default)
{
_log.LogInformation($"Getting commitment {commitmentId} for provider {providerId}");
return _restHttpClient.Get<CommitmentView>($"/api/provider/{providerId}/commitments/{commitmentId}",
null, cancellationToken);
}
}
} | mit | C# |
ddc3192b9770413fe92cb8d4fd21bdb1cf6afe1f | Update Vector2.cs | elacy/PopulationSimulator | PopSim.Logic/Vector2.cs | PopSim.Logic/Vector2.cs | using System;
namespace PopSim.Logic
{
public class Vector2
{
public Vector2(double x, double y)
{
X = x;
Y = y;
IsZero = Math.Abs(x) < double.Epsilon && Math.Abs(y) < double.Epsilon;
}
public bool IsZero { get; private set; }
public double X { get; private set; }
public double Y { get; private set; }
public Vector2 Add(Vector2 vector2)
{
return new Vector2(X + vector2.X,Y + vector2.Y);
}
public double GetDistance(Vector2 vector2)
{
return Math.Sqrt(Squared(vector2.X - X) + Squared(vector2.Y - Y));
}
private static double Squared(double value)
{
return Math.Pow(value, 2);
}
public double AngleBetween(Vector2 vector2)
{
return Math.Atan2(vector2.Y - Y, vector2.X - X);
}
public Vector2 GetDirection(Vector2 destination)
{
var angle = AngleBetween(destination);
return new Vector2(Math.Cos(angle),Math.Sin(angle));
}
public Vector2 ScalarMultiply(double multiplier)
{
RetVector = new Vector2(X*multiplier,Y*multiplier);
RetVector = RetVector.UnitVector();
return RetVector;
}
public double VectorMagnitude()
{
return Math.Sqrt(X*X + Y*Y);
}
public Vector2 UnitVector()
{
return new Vector2( X / VectorMagnitude(), Y / VectorMagnitude())
}
}
}
| using System;
namespace PopSim.Logic
{
public class Vector2
{
public Vector2(double x, double y)
{
X = x;
Y = y;
IsZero = Math.Abs(x) < double.Epsilon && Math.Abs(y) < double.Epsilon;
}
public bool IsZero { get; private set; }
public double X { get; private set; }
public double Y { get; private set; }
public Vector2 Add(Vector2 vector2)
{
return new Vector2(X + vector2.X,Y + vector2.Y);
}
public double GetDistance(Vector2 vector2)
{
return Math.Sqrt(Squared(vector2.X - X) + Squared(vector2.Y - Y));
}
private static double Squared(double value)
{
return Math.Pow(value, 2);
}
public double AngleBetween(Vector2 vector2)
{
return Math.Atan2(vector2.Y - Y, vector2.X - X);
}
public Vector2 GetDirection(Vector2 destination)
{
var angle = AngleBetween(destination);
return new Vector2(Math.Cos(angle),Math.Sin(angle));
}
public Vector2 ScalarMultiply(double multiplier)
{
return new Vector2(X*multiplier,Y*multiplier);
}
public double VectorMagnitude()
{
return Math.Sqrt(X*X + Y*Y);
}
public Vector2 UnitVector()
{
return new Vector2( X / VectorMagnitude(), Y / VectorMagnitude())
}
}
}
| mit | C# |
39c3244a725435972a65bad5c5a444a172fdc02f | Add XML doc comments | jorik041/dnlib,Arthur2e5/dnlib,0xd4d/dnlib,modulexcite/dnlib,ZixiangBoy/dnlib,picrap/dnlib,kiootic/dnlib,yck1509/dnlib,ilkerhalil/dnlib | src/DotNet/Emit/OperandType.cs | src/DotNet/Emit/OperandType.cs | using dot10.DotNet.MD;
namespace dot10.DotNet.Emit {
/// <summary>
/// CIL opcode operand type
/// </summary>
public enum OperandType : byte {
/// <summary>4-byte relative instruction offset</summary>
InlineBrTarget,
/// <summary>4-byte field token (<see cref="Table.Field"/> or <see cref="Table.MemberRef"/>)</summary>
InlineField,
/// <summary>int32</summary>
InlineI,
/// <summary>int64</summary>
InlineI8,
/// <summary>4-byte method token (<see cref="Table.Method"/>, <see cref="Table.MemberRef"/>
/// or <see cref="Table.MethodSpec"/>)</summary>
InlineMethod,
/// <summary>No operand</summary>
InlineNone,
/// <summary>Never used</summary>
InlinePhi,
/// <summary>64-bit real</summary>
InlineR,
/// <summary></summary>
NOT_USED_8,
/// <summary>4-byte method sig token (<see cref="Table.StandAloneSig"/>)</summary>
InlineSig,
/// <summary>4-byte string token (<c>0x70xxxxxx</c>)</summary>
InlineString,
/// <summary>4-byte count N followed by N 4-byte relative instruction offsets</summary>
InlineSwitch,
/// <summary>4-byte token (<see cref="Table.Field"/>, <see cref="Table.MemberRef"/>,
/// <see cref="Table.Method"/>, <see cref="Table.MethodSpec"/>, <see cref="Table.TypeDef"/>,
/// <see cref="Table.TypeRef"/> or <see cref="Table.TypeSpec"/>)</summary>
InlineTok,
/// <summary>4-byte type token (<see cref="Table.TypeDef"/>, <see cref="Table.TypeRef"/> or
/// <see cref="Table.TypeSpec"/>)</summary>
InlineType,
/// <summary>2-byte param/local index</summary>
InlineVar,
/// <summary>1-byte relative instruction offset</summary>
ShortInlineBrTarget,
/// <summary>1-byte sbyte (<see cref="Code.Ldc_I4_S"/>) or byte (the rest)</summary>
ShortInlineI,
/// <summary>32-bit real</summary>
ShortInlineR,
/// <summary>1-byte param/local index</summary>
ShortInlineVar,
}
}
| namespace dot10.DotNet.Emit {
/// <summary>
/// CIL opcode operand type
/// </summary>
public enum OperandType : byte {
/// <summary></summary>
InlineBrTarget,
/// <summary></summary>
InlineField,
/// <summary></summary>
InlineI,
/// <summary></summary>
InlineI8,
/// <summary></summary>
InlineMethod,
/// <summary></summary>
InlineNone,
/// <summary></summary>
InlinePhi,
/// <summary></summary>
InlineR,
/// <summary></summary>
NOT_USED_8,
/// <summary></summary>
InlineSig,
/// <summary></summary>
InlineString,
/// <summary></summary>
InlineSwitch,
/// <summary></summary>
InlineTok,
/// <summary></summary>
InlineType,
/// <summary></summary>
InlineVar,
/// <summary></summary>
ShortInlineBrTarget,
/// <summary></summary>
ShortInlineI,
/// <summary></summary>
ShortInlineR,
/// <summary></summary>
ShortInlineVar,
}
}
| mit | C# |
dd7506024e47014b8b6c0538983034339caea09d | Add ability do dependency inject a HttpMessageHandler into HttpService | schwamster/HttpService,schwamster/HttpService | src/HttpService/HttpService.cs | src/HttpService/HttpService.cs | using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
using Microsoft.AspNetCore.Authentication;
namespace HttpService
{
public class HttpService : IHttpService
{
private readonly IContextReader _tokenExtractor;
private HttpClient _client;
public HttpService(IHttpContextAccessor accessor, HttpMessageHandler handler = null) : this(new HttpContextReader(accessor), handler)
{
}
public HttpService(IContextReader tokenExtractor, HttpMessageHandler handler = null)
{
_tokenExtractor = tokenExtractor;
_client = handler == null ? new HttpClient() : new HttpClient(handler);
}
public async Task<HttpResponseMessage> GetAsync(string requestUri, bool passToken) =>
await SendAsync(HttpMethod.Get, requestUri, passToken);
public async Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, bool passToken) =>
await SendAsync(HttpMethod.Post, requestUri, passToken, content);
public async Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, bool passToken) =>
await SendAsync(HttpMethod.Put, requestUri, passToken, content);
public async Task<HttpResponseMessage> DeleteAsync(string requestUri, bool passToken) =>
await SendAsync(HttpMethod.Delete, requestUri, passToken);
private async Task<HttpResponseMessage> SendAsync(HttpMethod method, string requestUri, bool passToken, HttpContent content = null)
{
var msg = new HttpRequestMessage(method, requestUri);
if (passToken)
{
var token = await _tokenExtractor.GetTokenAsync();
if (!string.IsNullOrEmpty(token))
{
msg.Headers.Add("Authorization", $"Bearer {token}");
}
}
if (content != null)
{
msg.Content = content;
}
return await _client.SendAsync(msg);
}
}
public interface IContextReader
{
Task<string> GetTokenAsync();
}
public class HttpContextReader : IContextReader
{
private readonly IHttpContextAccessor _accessor;
public HttpContextReader(IHttpContextAccessor accessor)
{
this._accessor = accessor;
}
public async Task<string> GetTokenAsync()
{
var token = await this._accessor.HttpContext.GetTokenAsync("access_token");
return token;
}
}
} | using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
using Microsoft.AspNetCore.Authentication;
namespace HttpService
{
public class HttpService : IHttpService
{
private readonly IContextReader _tokenExtractor;
private HttpClient _client;
public HttpService(IHttpContextAccessor accessor) : this(new HttpContextReader(accessor))
{
}
public HttpService(IContextReader tokenExtractor)
{
_tokenExtractor = tokenExtractor;
_client = new HttpClient();
}
public async Task<HttpResponseMessage> GetAsync(string requestUri, bool passToken) =>
await SendAsync(HttpMethod.Get, requestUri, passToken);
public async Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, bool passToken) =>
await SendAsync(HttpMethod.Post, requestUri, passToken, content);
public async Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, bool passToken) =>
await SendAsync(HttpMethod.Put, requestUri, passToken, content);
public async Task<HttpResponseMessage> DeleteAsync(string requestUri, bool passToken) =>
await SendAsync(HttpMethod.Delete, requestUri, passToken);
private async Task<HttpResponseMessage> SendAsync(HttpMethod method, string requestUri, bool passToken, HttpContent content = null)
{
var msg = new HttpRequestMessage(method, requestUri);
if (passToken)
{
var token = await _tokenExtractor.GetTokenAsync();
if (!string.IsNullOrEmpty(token))
{
msg.Headers.Add("Authorization", $"Bearer {token}");
}
}
if (content != null)
{
msg.Content = content;
}
return await _client.SendAsync(msg);
}
}
public interface IContextReader
{
Task<string> GetTokenAsync();
}
public class HttpContextReader : IContextReader
{
private readonly IHttpContextAccessor _accessor;
public HttpContextReader(IHttpContextAccessor accessor)
{
this._accessor = accessor;
}
public async Task<string> GetTokenAsync()
{
var token = await this._accessor.HttpContext.GetTokenAsync("access_token");
return token;
}
}
} | mit | C# |
6db4aebd06f8c15761c77ac7c5a0e30ee234336d | Update _Error403.cshtml | SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice | src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Error/_Error403.cshtml | src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Error/_Error403.cshtml | @{
ViewBag.Title = "Access denied - Error 403";
ViewBag.PageId = "error-403";
ViewBag.HideNavBar = true;
}
<main id="content" role="main" class="error-403">
<div class="grid-row">
<div class="column-two-thirds">
<div class="hgroup">
<h1 class="heading-xlarge">
You do not have permission to access this page
</h1>
</div>
<div class="inner">
<p>
If you think you should have permission to access this page or want to confirm what permissions you have, contact an account owner.
</p>
<p>
<a href="@Url.Action("Index", "Account")"> Go back to home page </a>
</p>
</div>
</div>
</div>
</main> | @{
ViewBag.Title = "Access denied - Error 403";
ViewBag.PageId = "error-403";
ViewBag.HideNavBar = true;
}
<main id="content" role="main" class="error-403">
<div class="grid-row">
<div class="column-two-thirds">
<div class="hgroup">
<h1 class="heading-xlarge">
You do not have permission to access this page
</h1>
</div>
<div class="inner">
<p>
If you think you should have permission to access this page or want to confirm what permissions you have, contact an account owner.
</p>
<p>
<a href="@Url.Action("Index", "Account")" target="_blank"> Go back to home page </a>
</p>
</div>
</div>
</div>
</main> | mit | C# |
9e6bc3969bb07cd558951158276f0d8dd41db9c7 | Clean up using statements, and add remark about InstallUtil | Luke-Wolf/wolfybot | WolfyBot.CLI/Program.cs | WolfyBot.CLI/Program.cs | //
// Copyright 2014 luke
//
// 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.Windows.Forms;
using WolfyBot.Core;
using WolfyBot.Config;
using System.Linq;
using System.ServiceProcess;
namespace WolfyBot.CLI
{
class WolfyBotService : ServiceBase
{
public WolfyBotService ()
{
this.ServiceName = "Wolfybot";
this.EventLog.Log = "Application";
// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
/*this.CanHandlePowerEvent = false;
this.CanHandleSessionChangeEvent = false;
this.CanShutdown = false;*/
this.CanPauseAndContinue = true;
this.CanStop = true;
}
public static void Main (string[] args)
{
if (args.Contains ("--help") || args.Length == 0) {
Console.WriteLine ("WolfyBot IRC Bot");
Console.WriteLine ("Use mono-service to start the service under Linux or Mac, or InstallUtil under Windows");
Console.WriteLine ("Arguments:");
Console.WriteLine ("--help: Print this Help");
Console.WriteLine ("--new-config: Generate a new configuration file");
Application.Exit ();
}
if (args.Contains ("--new-config")) {
Configurator.WriteNewConfig ();
Console.WriteLine ("New Config File Written");
Application.Exit ();
}
ServiceBase.Run (new WolfyBotService ());
}
protected override void OnStart (string[] args)
{
Configurator.Configure ();
controller = Configurator.BuildBotController ();
server = Configurator.BuildIRCServer ();
Configurator.WireUp (controller, server);
server.Connect ();
base.OnStart (args);
}
protected override void OnStop ()
{
server.MessageReceived -= controller.ReceiveMessageHandler;
controller.MessageSent -= server.SendMessageHandler;
controller = null;
server = null;
base.OnStop ();
}
protected override void OnPause ()
{
server.MessageReceived -= controller.ReceiveMessageHandler;
controller.MessageSent -= server.SendMessageHandler;
controller = null;
server = null;
base.OnPause ();
}
protected override void OnContinue ()
{
controller = Configurator.BuildBotController ();
server = Configurator.BuildIRCServer ();
Configurator.WireUp (controller, server);
server.Connect ();
base.OnContinue ();
}
BotController controller;
IRCServer server;
}
}
| //
// Copyright 2014 luke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using WolfyBot.Core;
using WolfyBot.Config;
using KeepAliveCommand;
using System.Threading;
using System.Linq;
using System.ServiceProcess;
namespace WolfyBot.CLI
{
class WolfyBotService : ServiceBase
{
public WolfyBotService ()
{
this.ServiceName = "Wolfybot";
this.EventLog.Log = "Application";
// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
/*this.CanHandlePowerEvent = false;
this.CanHandleSessionChangeEvent = false;
this.CanShutdown = false;*/
this.CanPauseAndContinue = true;
this.CanStop = true;
}
public static void Main (string[] args)
{
if (args.Contains ("--help") || args.Length == 0) {
Console.WriteLine ("WolfyBot IRC Bot");
Console.WriteLine ("Use mono-service to start the service");
Console.WriteLine ("Arguments:");
Console.WriteLine ("--help: Print this Help");
Console.WriteLine ("--new-config: Generate a new configuration file");
Application.Exit ();
}
if (args.Contains ("--new-config")) {
Configurator.WriteNewConfig ();
Console.WriteLine ("New Config File Written");
Application.Exit ();
}
ServiceBase.Run (new WolfyBotService ());
}
protected override void OnStart (string[] args)
{
Configurator.Configure ();
controller = Configurator.BuildBotController ();
server = Configurator.BuildIRCServer ();
Configurator.WireUp (controller, server);
server.Connect ();
base.OnStart (args);
}
protected override void OnStop ()
{
server.MessageReceived -= controller.ReceiveMessageHandler;
controller.MessageSent -= server.SendMessageHandler;
controller = null;
server = null;
base.OnStop ();
}
/// <summary>
/// OnPause: Put your pause code here
/// - Pause working threads, etc.
/// </summary>
protected override void OnPause ()
{
server.MessageReceived -= controller.ReceiveMessageHandler;
controller.MessageSent -= server.SendMessageHandler;
controller = null;
server = null;
base.OnPause ();
}
protected override void OnContinue ()
{
controller = Configurator.BuildBotController ();
server = Configurator.BuildIRCServer ();
Configurator.WireUp (controller, server);
server.Connect ();
base.OnContinue ();
}
BotController controller;
IRCServer server;
}
}
| apache-2.0 | C# |
ecd2586e37517bc9e4ab96d00407932617fb7e40 | Fix getters of ReleaseInfo class (#208) | Eclo/nf-debugger,nanoframework/nf-debugger | source/nanoFramework.Tools.DebugLibrary.Shared/WireProtocol/ReleaseInfo.cs | source/nanoFramework.Tools.DebugLibrary.Shared/WireProtocol/ReleaseInfo.cs | //
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Text;
namespace nanoFramework.Tools.Debugger.WireProtocol
{
public class ReleaseInfo : IConverter
{
// these constants reflect the size of the struct NFReleaseInfo in native code @ nanoHAL_ReleaseInfo.h
private const int c_sizeOfVersion = 8;
private const int c_sizeOfInfo = 128;
private const int c_sizeOfTargetName = 32;
private const int c_sizeOfPlatformName = 32;
private VersionStruct _version;
private byte[] _rawInfo;
public ReleaseInfo()
{
_version = new VersionStruct();
_rawInfo = new byte[c_sizeOfInfo + c_sizeOfTargetName + c_sizeOfPlatformName];
}
public void PrepareForDeserialize(int size, byte[] data, Converter converter)
{
_rawInfo = new byte[c_sizeOfInfo + c_sizeOfTargetName + c_sizeOfPlatformName];
}
public Version Version => _version.Version;
public string Info
{
get
{
var myString = Encoding.UTF8.GetString(_rawInfo, 0, c_sizeOfInfo);
return myString.Substring(0, myString.IndexOf('\0'));
}
}
public string TargetName
{
get
{
var myString = Encoding.UTF8.GetString(_rawInfo, c_sizeOfInfo, c_sizeOfTargetName);
return myString.Substring(0, myString.IndexOf('\0'));
}
}
public string PlatformName
{
get
{
var myString = Encoding.UTF8.GetString(_rawInfo, c_sizeOfInfo + c_sizeOfTargetName, c_sizeOfPlatformName);
return myString.Substring(0, myString.IndexOf('\0'));
}
}
}
}
| //
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Text;
namespace nanoFramework.Tools.Debugger.WireProtocol
{
public class ReleaseInfo : IConverter
{
// these constants reflect the size of the struct NFReleaseInfo in native code @ nanoHAL_ReleaseInfo.h
private const int c_sizeOfVersion = 8;
private const int c_sizeOfInfo = 128;
private const int c_sizeOfTargetName = 32;
private const int c_sizeOfPlatformName = 32;
private VersionStruct _version;
private byte[] _rawInfo;
public ReleaseInfo()
{
_version = new VersionStruct();
_rawInfo = new byte[c_sizeOfInfo + c_sizeOfTargetName + c_sizeOfPlatformName];
}
public void PrepareForDeserialize(int size, byte[] data, Converter converter)
{
_rawInfo = new byte[c_sizeOfInfo + c_sizeOfTargetName + c_sizeOfPlatformName];
}
public Version Version => _version.Version;
public string Info => Encoding.UTF8.GetString(_rawInfo, 0, c_sizeOfInfo).TrimEnd('\0');
public string TargetName => Encoding.UTF8.GetString(_rawInfo, c_sizeOfInfo, c_sizeOfTargetName).TrimEnd('\0');
public string PlatformName => Encoding.UTF8.GetString(_rawInfo, c_sizeOfInfo + c_sizeOfTargetName, c_sizeOfPlatformName).TrimEnd('\0');
}
}
| apache-2.0 | C# |
85220f8e8b967ba6bff8420482fc7d148ef8664e | Fix bad merge | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade/Util/XmlUtil.cs | src/Arkivverket.Arkade/Util/XmlUtil.cs | using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
namespace Arkivverket.Arkade.Util
{
public class XmlUtil
{
public static void Validate(String xmlString, String xmlSchemaString)
{
MemoryStream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
MemoryStream xmlSchemaStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlSchemaString));
Validate(xmlStream, xmlSchemaStream);
}
public static void Validate(Stream xmlStream, Stream xmlSchemaStream)
{
XmlSchema xmlSchema = XmlSchema.Read(xmlSchemaStream, new ValidationEventHandler(ValidationCallBack));
using (var validationReader = XmlReader.Create(xmlStream, SetupXmlValidation(xmlSchema)))
{
while (validationReader.Read())
{
}
}
}
private static XmlReaderSettings SetupXmlValidation(XmlSchema xmlSchema)
{
var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.Schemas.Add(xmlSchema);
return settings;
}
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
// TODO: Gather all problems
throw args.Exception;
}
}
}
| using Arkivverket.Arkade.Test.Core;
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
namespace Arkivverket.Arkade.Util
{
public class XmlUtil
{
public static void Validate(String xmlString, String xmlSchemaString)
{
MemoryStream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
MemoryStream xmlSchemaStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlSchemaString));
Validate(xmlStream, xmlSchemaStream);
}
public static void Validate(Stream xmlStream, Stream xmlSchemaStream)
{
XmlSchema xmlSchema = XmlSchema.Read(xmlSchemaStream, new ValidationEventHandler(ValidationCallBack));
using (var validationReader = XmlReader.Create(xmlStream, SetupXmlValidation(xmlSchema)))
{
while (validationReader.Read())
{
}
}
}
private static XmlReaderSettings SetupXmlValidation(XmlSchema xmlSchema)
{
var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.Schemas.Add(xmlSchema);
return settings;
}
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
// TODO: Gather all problems
throw args.Exception;
}
}
}
| agpl-3.0 | C# |
4e143b7882e3710c2b0b8118947875ee6804da2b | 更新 .net 4.5 项目版本号 | JeffreySu/WxOpen,JeffreySu/WxOpen | src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Properties/AssemblyInfo.cs | src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Senparc.Weixin.WxOpen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Senparc.Weixin.WxOpen")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("379d8c97-4f96-45af-9f91-6bd160514495")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.5.2.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Senparc.Weixin.WxOpen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Senparc.Weixin.WxOpen")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("379d8c97-4f96-45af-9f91-6bd160514495")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.5.1.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
26ddf23e04069a7fad4cf7cc06b3c15af69d1614 | remove unneeded setter | petrhaus/RedCapped,AppSpaceIT/RedCapped | src/RedCapped.Core/RedCappedMessage.cs | src/RedCapped.Core/RedCappedMessage.cs | using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace RedCapped.Core
{
public class MessageHeader<T>
{
[BsonElement("v")]
public string Version
{
get
{
return "1";
}
}
[BsonElement("t")]
public string Type
{
get { return typeof(T).FullName; }
}
[BsonElement("qos")]
public QoS QoS { get; set; }
[BsonElement("sent")]
public DateTime SentAt { get; set; }
[BsonElement("ack")]
public DateTime AcknowledgedAt { get; set; }
[BsonElement("retry-limit")]
[BsonIgnoreIfDefault]
public int RetryLimit { get; set; }
[BsonElement("retry-count")]
public int RetryCount { get; set; }
}
public class RedCappedMessage<T>
{
public RedCappedMessage(T message)
{
Header = new MessageHeader<T>();
Message = message;
}
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string MessageId { get; set; }
[BsonElement("header")]
public MessageHeader<T> Header { get; set; }
[BsonElement("topic")]
public string Topic { get; set; }
[BsonElement("payload")]
public T Message { get; set; }
}
} | using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace RedCapped.Core
{
public class MessageHeader<T>
{
[BsonElement("v")]
public string Version
{
get
{
return "1";
}
set
{
}
}
[BsonElement("t")]
public string Type
{
get { return typeof(T).FullName; }
}
[BsonElement("qos")]
public QoS QoS { get; set; }
[BsonElement("sent")]
public DateTime SentAt { get; set; }
[BsonElement("ack")]
public DateTime AcknowledgedAt { get; set; }
[BsonElement("retry-limit")]
[BsonIgnoreIfDefault]
public int RetryLimit { get; set; }
[BsonElement("retry-count")]
public int RetryCount { get; set; }
}
public class RedCappedMessage<T>
{
public RedCappedMessage(T message)
{
Header = new MessageHeader<T>();
Message = message;
}
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string MessageId { get; set; }
[BsonElement("header")]
public MessageHeader<T> Header { get; set; }
[BsonElement("topic")]
public string Topic { get; set; }
[BsonElement("payload")]
public T Message { get; set; }
}
} | apache-2.0 | C# |
43a9364a592fdbf9afb3b585ea739ae5f73eba55 | Set verbosity to diagnostic on hosted build. | KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog | src/StructuredLogViewer/HostedBuild.cs | src/StructuredLogViewer/HostedBuild.cs | using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Logging.StructuredLogger;
using Microsoft.Build.Utilities;
namespace StructuredLogViewer
{
public class HostedBuild
{
private string projectFilePath;
public HostedBuild(string projectFilePath)
{
this.projectFilePath = projectFilePath;
}
public Task<Build> BuildAndGetResult(BuildProgress progress)
{
var msbuildExe = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion);
var loggerDll = typeof(StructuredLogger).Assembly.Location;
var commandLine = $@"""{msbuildExe}"" ""{projectFilePath}"" /t:Rebuild /v:diag /noconlog /logger:{nameof(StructuredLogger)},""{loggerDll}"";BuildLog.xml";
progress.MSBuildCommandLine = commandLine;
StructuredLogger.SaveLogToDisk = false;
return System.Threading.Tasks.Task.Run(() =>
{
try
{
var result = MSBuildApp.Execute(commandLine);
return StructuredLogger.CurrentBuild;
}
catch (Exception ex)
{
var build = new Build();
build.Succeeded = false;
build.AddChild(new Message() { Text = "Exception occurred during build:" });
build.AddChild(new Error() { Text = ex.ToString() });
return build;
}
});
}
}
}
| using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Logging.StructuredLogger;
using Microsoft.Build.Utilities;
namespace StructuredLogViewer
{
public class HostedBuild
{
private string projectFilePath;
public HostedBuild(string projectFilePath)
{
this.projectFilePath = projectFilePath;
}
public Task<Build> BuildAndGetResult(BuildProgress progress)
{
var msbuildExe = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion);
var loggerDll = typeof(StructuredLogger).Assembly.Location;
var commandLine = $@"""{msbuildExe}"" ""{projectFilePath}"" /t:Rebuild /noconlog /logger:{nameof(StructuredLogger)},""{loggerDll}"";BuildLog.xml";
progress.MSBuildCommandLine = commandLine;
StructuredLogger.SaveLogToDisk = false;
return System.Threading.Tasks.Task.Run(() =>
{
try
{
var result = MSBuildApp.Execute(commandLine);
return StructuredLogger.CurrentBuild;
}
catch (Exception ex)
{
var build = new Build();
build.Succeeded = false;
build.AddChild(new Message() { Text = "Exception occurred during build:" });
build.AddChild(new Error() { Text = ex.ToString() });
return build;
}
});
}
}
}
| mit | C# |
3a1e6fffd2c3b953d6ad9320714ae0102346a451 | Update IConfigurationValidationStrategy.cs | tiksn/TIKSN-Framework | TIKSN.Core/Configuration/ValidationStrategy/IConfigurationValidationStrategy.cs | TIKSN.Core/Configuration/ValidationStrategy/IConfigurationValidationStrategy.cs | namespace TIKSN.Configuration.ValidationStrategy
{
public interface IConfigurationValidationStrategy<T>
{
void Validate(T instance);
}
}
| namespace TIKSN.Configuration.ValidationStrategy
{
public interface IConfigurationValidationStrategy<T>
{
void Validate(T instance);
}
} | mit | C# |
69dce6dd119bc6ef1df157e23a86dafdb93983ba | Change namespace for XmlReaderFactory | Seddryck/Idunn.SqlServer | Idunn.Console/Parser/XmlReaderFactory.cs | Idunn.Console/Parser/XmlReaderFactory.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Idunn.Console.Parser
{
public class XmlReaderFactory
{
public XmlReader Instantiate(StreamReader reader)
{
var xmlReader = XmlReader.Create(reader);
return xmlReader;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Idunn.Console.Parser.XmlParser
{
public class XmlReaderFactory
{
public XmlReader Instantiate(StreamReader reader)
{
var xmlReader = XmlReader.Create(reader);
return xmlReader;
}
}
}
| apache-2.0 | C# |
cba5d786bc6ea104b8d08cbb9a3cf8723ff87595 | Fix for TargetException. | hungweng/MarkerMetro.Unity.WinLegacy,MarkerMetro/MarkerMetro.Unity.WinLegacy | MarkerMetro.Unity.WinLegacyUnity/System/Reflection/TargetException.cs | MarkerMetro.Unity.WinLegacyUnity/System/Reflection/TargetException.cs | namespace MarkerMetro.Unity.WinLegacy.Reflection
{
class TargetException : System.Exception
{
public TargetException() : base() { }
public TargetException(string message) : base(message) { }
}
}
| #if NETFX_CORE
namespace MarkerMetro.Unity.WinLegacy.Reflection
{
class TargetException : System.Exception
{
public TargetException() : base() { }
public TargetException(string message) : base(message) { }
}
}
#endif | mit | C# |
3e2ce4bea9767fe39e255a91dbefd66749e79715 | Fix possible NullReferenceException | pdfforge/translatable | Source/Translatable.NGettext/GettextTranslationSource.cs | Source/Translatable.NGettext/GettextTranslationSource.cs | using NGettext;
using System.Globalization;
using System.IO;
using Translation;
namespace Translatable.NGettext
{
public class GettextTranslationSource : ITranslationSource
{
private readonly Catalog _catalog;
public GettextTranslationSource(string translationFolder, string moDomain, CultureInfo cultureInfo)
{
_catalog = new Catalog(moDomain, translationFolder, cultureInfo);
}
public GettextTranslationSource(Stream moStream, CultureInfo cultureInfo)
{
_catalog = new Catalog(moStream, cultureInfo);
}
public GettextTranslationSource(Catalog catalog)
{
_catalog = catalog;
}
public IPluralBuilder GetPluralBuilder()
{
if (_catalog == null)
return new DefaultPluralBuilder();
return new GettextPluralBuilder(_catalog.PluralRule);
}
public string GetTranslation(string translationKey, string context = "")
{
if (string.IsNullOrWhiteSpace(context))
return _catalog.GetString(translationKey);
return _catalog.GetParticularString(context, translationKey);
}
public string[] GetAllTranslations(string translationKey, string context, IPluralBuilder pluralBuilder)
{
if (!string.IsNullOrWhiteSpace(context))
translationKey = context + Catalog.CONTEXT_GLUE + translationKey;
if (!_catalog.Translations.ContainsKey(translationKey))
return new string[] { };
var translations = _catalog.GetTranslations(translationKey);
if (translations.Length != pluralBuilder.NumberOfPlurals)
return new string[] { };
return translations;
}
}
}
| using System.Globalization;
using System.IO;
using System.Linq;
using NGettext;
using Translation;
namespace Translatable.NGettext
{
public class GettextTranslationSource : ITranslationSource
{
private readonly Catalog _catalog;
public GettextTranslationSource(string translationFolder, string moDomain, CultureInfo cultureInfo)
{
_catalog = new Catalog(moDomain, translationFolder, cultureInfo);
}
public GettextTranslationSource(Stream moStream, CultureInfo cultureInfo)
{
_catalog = new Catalog(moStream, cultureInfo);
}
public GettextTranslationSource(Catalog catalog)
{
_catalog = catalog;
}
public IPluralBuilder GetPluralBuilder()
{
if (_catalog == null)
return new DefaultPluralBuilder();
return new GettextPluralBuilder(_catalog.PluralRule);
}
public string GetTranslation(string translationKey, string context = "")
{
if (string.IsNullOrWhiteSpace(context))
return _catalog.GetString(translationKey);
return _catalog.GetParticularString(context, translationKey);
}
public string[] GetAllTranslations(string translationKey, string context, IPluralBuilder pluralBuilder)
{
if (!_catalog.Translations.ContainsKey(translationKey))
return new string[] {};
if (!string.IsNullOrWhiteSpace(context))
translationKey = context + Catalog.CONTEXT_GLUE + translationKey;
var translations = _catalog.GetTranslations(translationKey);
if (translations.Length != pluralBuilder.NumberOfPlurals)
return new string[] {};
return translations;
}
}
}
| mit | C# |
0dc438f60b744fb7b8ee7d9433f06efeddb90805 | Mark BounceException as serializable (the shadow copying needs to serialize things across process boundaries) | socialdotcom/bounce,sreal/bounce,refractalize/bounce,refractalize/bounce,refractalize/bounce,sreal/bounce,socialdotcom/bounce,sreal/bounce,socialdotcom/bounce,socialdotcom/bounce | Bounce.Framework/BounceException.cs | Bounce.Framework/BounceException.cs | using System;
using System.IO;
namespace Bounce.Framework {
[Serializable]
public class BounceException : Exception {
public BounceException(string message) : base(message) {
}
public BounceException(string message, Exception innerException) : base(message, innerException) {
}
public BounceException() {
}
public virtual void Explain(TextWriter stderr) {
stderr.WriteLine(this);
}
}
} | using System;
using System.IO;
namespace Bounce.Framework {
public class BounceException : Exception {
public BounceException(string message) : base(message) {
}
public BounceException(string message, Exception innerException) : base(message, innerException) {
}
public BounceException() {
}
public virtual void Explain(TextWriter stderr) {
stderr.WriteLine(this);
}
}
} | bsd-2-clause | C# |
45a9b4f85f34451948419d9aed8971fff991f1e9 | Add a more concrete test. Still have a ways to go in understanding the MicroKernel. | castleproject/castle-READONLY-SVN-dump,carcer/Castle.Components.Validator,castleproject/Castle.Transactions,codereflection/Castle.Components.Scheduler,castleproject/Castle.Facilities.Wcf-READONLY,castleproject/Castle.Transactions,castleproject/castle-READONLY-SVN-dump,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,castleproject/Castle.Facilities.Wcf-READONLY | Facilities/Logging/Castle.Facilities.Logging.Tests/LoggingFacilityTestCase.cs | Facilities/Logging/Castle.Facilities.Logging.Tests/LoggingFacilityTestCase.cs | // Copyright 2004-2005 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Castle.Facilities.Logging.Tests
{
using System;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Model.Configuration;
using Castle.Windsor;
using NUnit.Framework;
using Castle.MicroKernel;
/// <summary>
/// Summary description for LoggingFacilityTestCase.
/// </summary>
[TestFixture]
public class LoggingFacilityTestCase {
private IWindsorContainer kernel;
[SetUp]
public void Setup()
{
kernel = CreateConfiguredContainer();
kernel.AddFacility("logging", new LoggingFacility());
}
[TearDown]
public void Teardown()
{
kernel.Dispose();
kernel = null;
}
[Test]
public void SimpleTest() {
String expectedLogOutput = "HellowWorld";
String actualLogOutput = "";
kernel.AddComponent("component", typeof(Classes.LoggingComponent));
Classes.LoggingComponent test = kernel["component"] as Classes.LoggingComponent;
test.HelloWorld(); //should cause some kind of HelloWorld to be logged.
//dump log output to the actualLogOutput variable
Assert.IsTrue(expectedLogOutput.Equals(actualLogOutput));
}
protected virtual IWindsorContainer CreateConfiguredContainer()
{
IWindsorContainer container = new WindsorContainer(new DefaultConfigurationStore());
MutableConfiguration confignode = new MutableConfiguration("facility");
confignode.Children.Add(new MutableConfiguration("framework", "log4net"));
confignode.Children.Add(new MutableConfiguration("config", "logging.config"));
confignode.Children.Add(new MutableConfiguration("intercept", "false"));
container.Kernel.ConfigurationStore.AddFacilityConfiguration("logging", confignode);
return container;
}
}
} | // Copyright 2004-2005 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Castle.Facilities.Logging.Tests
{
using System;
using NUnit.Framework;
using Castle.MicroKernel;
/// <summary>
/// Summary description for LoggingFacilityTestCase.
/// </summary>
[TestFixture]
public class LoggingFacilityTestCase {
private IKernel kernel;
[SetUp]
public void Setup()
{
kernel = new DefaultKernel();
kernel.AddFacility("logging", new LoggingFacility());
}
[TearDown]
public void Teardown()
{
kernel.Dispose();
kernel = null;
}
[Test]
public void SimpleTest() {
String expectedLogOutput = "hello world";
String actualLogOutput = "";
//do something to cause a log message "hello world"
//dump log output to the actualLogOutput variable
Assert.IsTrue(expectedLogOutput.Equals(actualLogOutput));
}
}
} | apache-2.0 | C# |
b53264a993dbbb32103077ea336b151af3a3481c | Fix server.Address not returning external IP | LaserHydra/Oxide,Visagalis/Oxide,LaserHydra/Oxide,Nogrod/Oxide-2,Nogrod/Oxide-2,Visagalis/Oxide | Games/Unity/Oxide.Game.ReignOfKings/Libraries/Covalence/ReignOfKingsServer.cs | Games/Unity/Oxide.Game.ReignOfKings/Libraries/Covalence/ReignOfKingsServer.cs | using System.Linq;
using System.Net;
using CodeHatch.Build;
using CodeHatch.Engine.Core.Commands;
using CodeHatch.Engine.Networking;
using Steamworks;
using Oxide.Core.Libraries.Covalence;
namespace Oxide.Game.ReignOfKings.Libraries.Covalence
{
/// <summary>
/// Represents the server hosting the game instance
/// </summary>
public class ReignOfKingsServer : IServer
{
#region Information
/// <summary>
/// Gets the public-facing name of the server
/// </summary>
public string Name => DedicatedServerBypass.Settings?.ServerName;
/// <summary>
/// Gets the public-facing IP address of the server, if known
/// </summary>
public IPAddress Address
{
get
{
var ip = SteamGameServer.GetPublicIP();
return ip == 0 ? null : new IPAddress(ip >> 24 | ((ip & 0xff0000) >> 8) | ((ip & 0xff00) << 8) | ((ip & 0xff) << 24));
}
}
/// <summary>
/// Gets the public-facing network port of the server, if known
/// </summary>
public ushort Port => CodeHatch.Engine.Core.Gaming.Game.ServerData.Port;
/// <summary>
/// Gets the version number/build of the server
/// </summary>
public string Version => GameInfo.VersionName.ToLower();
#endregion
#region Chat and Commands
/// <summary>
/// Broadcasts a chat message to all player clients
/// </summary>
/// <param name="message"></param>
public void Broadcast(string message) => Server.BroadcastMessage($"Server: {message}");
/// <summary>
/// Runs the specified server command
/// </summary>
/// <param name="command"></param>
/// <param name="args"></param>
public void Command(string command, params object[] args)
{
CommandManager.ExecuteCommand(Server.Instance.ServerPlayer.Id, command + " " + string.Join(" ", args.ToList().ConvertAll(a => (string)a).ToArray()));
}
#endregion
}
}
| using System.Linq;
using System.Net;
using CodeHatch.Build;
using CodeHatch.Engine.Core.Commands;
using CodeHatch.Engine.Networking;
using Oxide.Core.Libraries.Covalence;
namespace Oxide.Game.ReignOfKings.Libraries.Covalence
{
/// <summary>
/// Represents the server hosting the game instance
/// </summary>
public class ReignOfKingsServer : IServer
{
#region Information
/// <summary>
/// Gets the public-facing name of the server
/// </summary>
public string Name => DedicatedServerBypass.Settings?.ServerName;
/// <summary>
/// Gets the public-facing IP address of the server, if known
/// </summary>
public IPAddress Address => IPAddress.Parse(CodeHatch.Engine.Core.Gaming.Game.ServerData.IP);
/// <summary>
/// Gets the public-facing network port of the server, if known
/// </summary>
public ushort Port => CodeHatch.Engine.Core.Gaming.Game.ServerData.Port;
/// <summary>
/// Gets the version number/build of the server
/// </summary>
public string Version => GameInfo.VersionName.ToLower();
#endregion
#region Chat and Commands
/// <summary>
/// Broadcasts a chat message to all player clients
/// </summary>
/// <param name="message"></param>
public void Broadcast(string message) => Server.BroadcastMessage($"Server: {message}");
/// <summary>
/// Runs the specified server command
/// </summary>
/// <param name="command"></param>
/// <param name="args"></param>
public void Command(string command, params object[] args)
{
CommandManager.ExecuteCommand(Server.Instance.ServerPlayer.Id, command + " " + string.Join(" ", args.ToList().ConvertAll(a => (string)a).ToArray()));
}
#endregion
}
}
| mit | C# |
4f47f12c96af82d09f9e4d682be0c07dceae0133 | Extend stale-while-revalidate | mayuki/PlatformStatusTracker,mayuki/PlatformStatusTracker,mayuki/PlatformStatusTracker | PlatformStatusTracker/PlatformStatusTracker.Web/Controllers/HomeController.cs | PlatformStatusTracker/PlatformStatusTracker.Web/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PlatformStatusTracker.Core.Repository;
using PlatformStatusTracker.Web.ViewModels.Home;
using PlatformStatusTracker.Web.Filters;
namespace PlatformStatusTracker.Web.Controllers
{
public class HomeController : Controller
{
private IChangeSetRepository _changeSetRepository;
public HomeController(IChangeSetRepository changeSetRepository)
{
_changeSetRepository = changeSetRepository;
}
[StaleWhileRevalidate(CacheProfileName = "DefaultCache", StaleWhileRevalidateDuration = 60 * 60 * 24)]
public async Task<IActionResult> Index()
{
return View(await HomeIndexViewModel.CreateAsync(_changeSetRepository));
}
[StaleWhileRevalidate(CacheProfileName = "DefaultCache", StaleWhileRevalidateDuration = 60 * 60 * 24)]
public async Task<IActionResult> Feed(bool shouldFilterIncomplete = true)
{
var result = View(await HomeIndexViewModel.CreateAsync(_changeSetRepository, shouldFilterIncomplete));
result.ContentType = "application/atom+xml";
return result;
}
[StaleWhileRevalidate(CacheProfileName = "DefaultCache", StaleWhileRevalidateDuration = 60 * 60 * 24)]
public async Task<IActionResult> Changes(String date)
{
if (String.IsNullOrWhiteSpace(date))
{
return RedirectToAction("Index");
}
DateTime dateTime;
if (!DateTime.TryParse(date, out dateTime))
{
return RedirectToAction("Index");
}
var viewModel = await ChangesViewModel.CreateAsync(_changeSetRepository, dateTime);
return View(viewModel);
}
public IActionResult Error()
{
return View();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PlatformStatusTracker.Core.Repository;
using PlatformStatusTracker.Web.ViewModels.Home;
using PlatformStatusTracker.Web.Filters;
namespace PlatformStatusTracker.Web.Controllers
{
public class HomeController : Controller
{
private IChangeSetRepository _changeSetRepository;
public HomeController(IChangeSetRepository changeSetRepository)
{
_changeSetRepository = changeSetRepository;
}
[StaleWhileRevalidate(CacheProfileName = "DefaultCache", StaleWhileRevalidateDuration = 60 * 60 * 2)]
public async Task<IActionResult> Index()
{
return View(await HomeIndexViewModel.CreateAsync(_changeSetRepository));
}
[StaleWhileRevalidate(CacheProfileName = "DefaultCache", StaleWhileRevalidateDuration = 60 * 60 * 2)]
public async Task<IActionResult> Feed(bool shouldFilterIncomplete = true)
{
var result = View(await HomeIndexViewModel.CreateAsync(_changeSetRepository, shouldFilterIncomplete));
result.ContentType = "application/atom+xml";
return result;
}
[StaleWhileRevalidate(CacheProfileName = "DefaultCache", StaleWhileRevalidateDuration = 60 * 60 * 2)]
public async Task<IActionResult> Changes(String date)
{
if (String.IsNullOrWhiteSpace(date))
{
return RedirectToAction("Index");
}
DateTime dateTime;
if (!DateTime.TryParse(date, out dateTime))
{
return RedirectToAction("Index");
}
var viewModel = await ChangesViewModel.CreateAsync(_changeSetRepository, dateTime);
return View(viewModel);
}
public IActionResult Error()
{
return View();
}
}
}
| mit | C# |
ddfa72b1a48e3874266f7413bdf4c962d5e86cad | Add new unit test | 0culus/ElectronicCash | ElectronicCash.Tests/HelperTests.cs | ElectronicCash.Tests/HelperTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace ElectronicCash.Tests
{
[TestFixture]
internal class HelperTests
{
[Test]
public void DummyTest()
{
Assert.True(true);
}
[Test]
public void GetBytesGivenString_ShouldYieldNonNullByteArray()
{
string test = "ThisIsAnAwesomeString";
byte[] result = Helpers.GetBytes(test);
Assert.IsNotNull(result);
}
[Test]
public void GetStringGivenBytes_ShouldYieldNonNullString()
{
var rnd = new Random();
var testBytes = new byte[10];
string result = Helpers.GetString(testBytes);
Assert.IsNotNull(result);
}
[Test]
public void GetStringGivenBytes_ShouldYieldSameString()
{
string test = "ThisIsAnAwesomeString";
byte[] result = Helpers.GetBytes(test);
string fromBytes = Helpers.GetString(result);
Assert.AreEqual(fromBytes, test);
}
[STAThread]
private static void Main()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace ElectronicCash.Tests
{
[TestFixture]
internal class HelperTests
{
[Test]
public void DummyTest()
{
Assert.True(true);
}
[Test]
public void GetBytesGivenString_ShouldYieldNonNullByteArray()
{
string test = "ThisIsAnAwesomeString";
byte[] result = Helpers.GetBytes(test);
Assert.IsNotNull(result);
}
[Test]
public void GetStringGivenBytes_ShouldYieldNonNullString()
{
var rnd = new Random();
var testBytes = new byte[10];
string result = Helpers.GetString(testBytes);
Assert.IsNotNull(result);
}
[STAThread]
private static void Main()
{
}
}
}
| mit | C# |
402b31c7f4fe2680a0e794209a0d394ca19c7401 | Mark the previous field as deprecated in response to CR feedback | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit.Services/InputSystem/InputSystemGlobalListener.cs | Assets/MixedRealityToolkit.Services/InputSystem/InputSystemGlobalListener.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.Threading.Tasks;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// This component ensures that all input events are forwarded to this <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> when focus or gaze is not required.
/// </summary>
public class InputSystemGlobalListener : MonoBehaviour
{
private bool lateInitialize = true;
/// <summary>
/// Prefer using EnsureInputSystemValid(), which will only await if the input system isn't
/// yet valid.
/// </summary>
[Obsolete("Prefer using EnsureInputSystemValid()")]
protected readonly WaitUntil WaitUntilInputSystemValid = new WaitUntil(() => MixedRealityToolkit.InputSystem != null);
protected virtual void OnEnable()
{
if (MixedRealityToolkit.IsInitialized && MixedRealityToolkit.InputSystem != null && !lateInitialize)
{
MixedRealityToolkit.InputSystem.Register(gameObject);
}
}
protected virtual async void Start()
{
if (lateInitialize)
{
await EnsureInputSystemValid();
// We've been destroyed during the await.
if (this == null)
{
return;
}
lateInitialize = false;
MixedRealityToolkit.InputSystem.Register(gameObject);
}
}
protected virtual void OnDisable()
{
MixedRealityToolkit.InputSystem?.Unregister(gameObject);
}
/// <summary>
/// A task that will only complete when the input system has in a valid state.
/// </summary>
/// <remarks>
/// It's possible for this object to have been destroyed after the await, which
/// implies that callers should check that this != null after awaiting this task.
/// </remarks>
protected async Task EnsureInputSystemValid()
{
if (MixedRealityToolkit.InputSystem == null)
{
#pragma warning disable CS0618 // WaitUntilInputSystemValid is obsolete for outside-of-class usage.
await WaitUntilInputSystemValid;
#pragma warning restore CS0618
}
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities;
using System.Threading.Tasks;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// This component ensures that all input events are forwarded to this <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> when focus or gaze is not required.
/// </summary>
public class InputSystemGlobalListener : MonoBehaviour
{
private bool lateInitialize = true;
/// <summary>
/// Prefer using EnsureInputSystemValid(), which will only await if the input system isn't
/// yet valid.
/// </summary>
protected readonly WaitUntil WaitUntilInputSystemValid = new WaitUntil(() => MixedRealityToolkit.InputSystem != null);
protected virtual void OnEnable()
{
if (MixedRealityToolkit.IsInitialized && MixedRealityToolkit.InputSystem != null && !lateInitialize)
{
MixedRealityToolkit.InputSystem.Register(gameObject);
}
}
protected virtual async void Start()
{
if (lateInitialize)
{
await EnsureInputSystemValid();
// We've been destroyed during the await.
if (this == null)
{
return;
}
lateInitialize = false;
MixedRealityToolkit.InputSystem.Register(gameObject);
}
}
protected virtual void OnDisable()
{
MixedRealityToolkit.InputSystem?.Unregister(gameObject);
}
/// <summary>
/// A task that will only complete when the input system has in a valid state.
/// </summary>
/// <remarks>
/// It's possible for this object to have been destroyed after the await, which
/// implies that callers should check that this != null after awaiting this task.
/// </remarks>
protected async Task EnsureInputSystemValid()
{
if (MixedRealityToolkit.InputSystem == null)
{
await WaitUntilInputSystemValid;
}
}
}
}
| mit | C# |
e3eddd0cf9b79ee324c25540a8cd024fcc75721b | Tweak submit text | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/SUTA/New.cshtml | Battery-Commander.Web/Views/SUTA/New.cshtml | @model BatteryCommander.Web.Commands.AddSUTARequest
<div class="alert alert-info">
Use this form to submit a Substitute Unit Training (SUTA) request to your chain of command.
</div>
@using (Html.BeginForm("New", "SUTA", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Soldier)
@Html.DropDownListFor(model => model.Soldier, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --", new { @class = "select2" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.StartDate)
@Html.EditorFor(model => model.StartDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.EndDate)
@Html.EditorFor(model => model.EndDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Reasoning)
@Html.TextAreaFor(model => model.Reasoning)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.MitigationPlan)
@Html.TextAreaFor(model => model.MitigationPlan)
</div>
<div class="alert alert-warning">
Disclaimer: ALL requests are subject to mission requirements and Commander's approval.
</div>
<button type="submit">Submit for Review</button>
}
| @model BatteryCommander.Web.Commands.AddSUTARequest
<div class="alert alert-info">
Use this form to submit a Substitute Unit Training (SUTA) request to your chain of command.
</div>
@using (Html.BeginForm("New", "SUTA", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Soldier)
@Html.DropDownListFor(model => model.Soldier, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --", new { @class = "select2" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.StartDate)
@Html.EditorFor(model => model.StartDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.EndDate)
@Html.EditorFor(model => model.EndDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Reasoning)
@Html.TextAreaFor(model => model.Reasoning)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.MitigationPlan)
@Html.TextAreaFor(model => model.MitigationPlan)
</div>
<div class="alert alert-warning">
Disclaimer: ALL requests are subject to mission requirements and Commander's approval.
</div>
<button type="submit">Submit</button>
}
| mit | C# |
d77de3bb127dbc96dd36901a197b5b047cdfb4b6 | Remove debug code | chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck | Core/Utils/BrowserProcesses.cs | Core/Utils/BrowserProcesses.cs | using System.Collections.Generic;
using System.Diagnostics;
using CefSharp;
namespace TweetDuck.Core.Utils{
static class BrowserProcesses{
private static readonly Dictionary<int, int> PIDs = new Dictionary<int, int>();
public static void Link(int identifier, int pid){
PIDs[identifier] = pid;
}
public static void Forget(int identifier){
PIDs.Remove(identifier);
}
public static Process FindProcess(IBrowser browser){
if (PIDs.TryGetValue(browser.Identifier, out int pid) && WindowsUtils.IsChildProcess(pid)){ // child process is checked in two places for safety
return Process.GetProcessById(pid);
}
else{
return null;
}
}
}
}
| using System.Collections.Generic;
using System.Diagnostics;
using CefSharp;
namespace TweetDuck.Core.Utils{
static class BrowserProcesses{
private static readonly Dictionary<int, int> PIDs = new Dictionary<int, int>();
public static void Link(int identifier, int pid){
PIDs[identifier] = pid;
}
public static void Forget(int identifier){
PIDs.Remove(identifier);
Debug.WriteLine("rip "+identifier);
}
public static Process FindProcess(IBrowser browser){
if (PIDs.TryGetValue(browser.Identifier, out int pid) && WindowsUtils.IsChildProcess(pid)){ // child process is checked in two places for safety
return Process.GetProcessById(pid);
}
else{
return null;
}
}
}
}
| mit | C# |
3df6e89069695cfbc0e49ede0f4422c895f49541 | Support for custom layout in title | elmahio/elmah.io.nlog | Elmah.Io.NLog/ElmahIoTarget.cs | Elmah.Io.NLog/ElmahIoTarget.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Elmah.Io.Client;
using Elmah.Io.Client.Models;
using NLog;
using NLog.Config;
using NLog.Targets;
namespace Elmah.Io.NLog
{
[Target("elmah.io")]
public class ElmahIoTarget : TargetWithLayout
{
private IElmahioAPI _client;
[RequiredParameter]
public string ApiKey { get; set; }
[RequiredParameter]
public Guid LogId { get; set; }
public ElmahIoTarget()
{
}
public ElmahIoTarget(IElmahioAPI client)
{
_client = client;
}
protected override void Write(LogEventInfo logEvent)
{
if (_client == null)
{
_client = ElmahioAPI.Create(ApiKey);
}
var title = Layout != null && Layout.ToString() != "'${longdate}|${level:uppercase=true}|${logger}|${message}'"
? Layout.Render(logEvent)
: logEvent.FormattedMessage;
var message = new CreateMessage
{
Title = title,
Severity = LevelToSeverity(logEvent.Level),
DateTime = logEvent.TimeStamp.ToUniversalTime(),
Detail = logEvent.Exception?.ToString(),
Data = PropertiesToData(logEvent.Properties)
};
_client.Messages.CreateAndNotify(LogId, message);
}
private List<Item> PropertiesToData(IDictionary<object, object> properties)
{
return properties.Keys.Select(key => new Item{Key = key.ToString(), Value = properties[key].ToString()}).ToList();
}
private string LevelToSeverity(LogLevel level)
{
if (level == LogLevel.Debug) return Severity.Debug.ToString();
if (level == LogLevel.Error) return Severity.Error.ToString();
if (level == LogLevel.Fatal) return Severity.Fatal.ToString();
if (level == LogLevel.Trace) return Severity.Verbose.ToString();
if (level == LogLevel.Warn) return Severity.Warning.ToString();
return Severity.Information.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Elmah.Io.Client;
using Elmah.Io.Client.Models;
using NLog;
using NLog.Config;
using NLog.Targets;
namespace Elmah.Io.NLog
{
[Target("elmah.io")]
public class ElmahIoTarget : Target
{
private IElmahioAPI _client;
[RequiredParameter]
public string ApiKey { get; set; }
[RequiredParameter]
public Guid LogId { get; set; }
public ElmahIoTarget()
{
}
public ElmahIoTarget(IElmahioAPI client)
{
_client = client;
}
protected override void Write(LogEventInfo logEvent)
{
if (_client == null)
{
_client = ElmahioAPI.Create(ApiKey);
}
var message = new CreateMessage
{
Title = logEvent.FormattedMessage,
Severity = LevelToSeverity(logEvent.Level),
DateTime = logEvent.TimeStamp.ToUniversalTime(),
Detail = logEvent.Exception?.ToString(),
Data = PropertiesToData(logEvent.Properties)
};
_client.Messages.CreateAndNotify(LogId, message);
}
private List<Item> PropertiesToData(IDictionary<object, object> properties)
{
return properties.Keys.Select(key => new Item{Key = key.ToString(), Value = properties[key].ToString()}).ToList();
}
private string LevelToSeverity(LogLevel level)
{
if (level == LogLevel.Debug) return Severity.Debug.ToString();
if (level == LogLevel.Error) return Severity.Error.ToString();
if (level == LogLevel.Fatal) return Severity.Fatal.ToString();
if (level == LogLevel.Trace) return Severity.Verbose.ToString();
if (level == LogLevel.Warn) return Severity.Warning.ToString();
return Severity.Information.ToString();
}
}
}
| apache-2.0 | C# |
38c820816f74b89073e8e0fded726f6429340852 | Bump to version 2.3.3.0 | Silv3rPRO/proshine,bobus15/proshine | PROShine/Properties/AssemblyInfo.cs | PROShine/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
// 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("PROShine")]
[assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Silv3r")]
[assembly: AssemblyProduct("PROShine")]
[assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[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)
)]
// 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.3.3.0")]
[assembly: AssemblyFileVersion("2.3.3.0")]
[assembly: NeutralResourcesLanguage("en")]
| using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
// 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("PROShine")]
[assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Silv3r")]
[assembly: AssemblyProduct("PROShine")]
[assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[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)
)]
// 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.3.2.0")]
[assembly: AssemblyFileVersion("2.3.2.0")]
[assembly: NeutralResourcesLanguage("en")]
| mit | C# |
b4da649d720c4857f9c1858c8106ebb10bce99eb | Fix bug that was preventing transation of some items. | ShunKun/KanColleViewer,the-best-flash/KanColleViewer | source/Grabacr07.KanColleWrapper/Translation/ItemTranslationHelper.cs | source/Grabacr07.KanColleWrapper/Translation/ItemTranslationHelper.cs | namespace Grabacr07.KanColleWrapper.Translation
{
public static class ItemTranslationHelper
{
public static string TranslateItemName(string name)
{
string stripped = name;
string translated = (string.IsNullOrEmpty(stripped) ? null : Equipment.Resources.ResourceManager.GetString(stripped, Equipment.Resources.Culture));
return (string.IsNullOrEmpty(translated) ? name : translated);
}
}
}
| namespace Grabacr07.KanColleWrapper.Translation
{
public static class ItemTranslationHelper
{
public static string TranslateItemName(string name)
{
string stripped = TranslationHelper.StripInvalidCharacters(name);
string translated = (string.IsNullOrEmpty(stripped) ? null : Equipment.Resources.ResourceManager.GetString(stripped, Equipment.Resources.Culture));
return (string.IsNullOrEmpty(translated) ? name : translated);
}
}
}
| mit | C# |
0130c1d56466802815c8c57506d38474a523a54e | Handle HttpException explicitly and include comments for workaround | verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate | src/Abp.Web/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs | src/Abp.Web/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs | using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using System.Web;
namespace Abp.Web.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason
{
get
{
if (OverridedValue != null)
{
return OverridedValue.Reason;
}
try
{
return HttpContext.Current?.Request.Url.AbsoluteUri;
}
catch (HttpException ex)
{
/* Workaround:
* Accessing HttpContext.Request during Application_Start or Application_End will throw exception.
* This behavior is intentional from microsoft
* See https://stackoverflow.com/questions/2518057/request-is-not-available-in-this-context/23908099#comment2514887_2518066
*/
Logger.Warn("HttpContext.Request access when it is not suppose to", ex);
return null;
}
}
}
public HttpRequestEntityChangeSetReasonProvider(
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
}
}
}
| using System;
using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using System.Web;
namespace Abp.Web.EntityHistory
{
/// <summary>
/// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
/// </summary>
public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
{
[CanBeNull]
public override string Reason
{
get
{
if (OverridedValue != null)
{
return OverridedValue.Reason;
}
try
{
return HttpContext.Current?.Request.Url.AbsoluteUri;
}
catch (Exception ex)
{
Logger.Warn(ex.ToString(), ex);
return null;
}
}
}
public HttpRequestEntityChangeSetReasonProvider(
IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
) : base(reasonOverrideScopeProvider)
{
}
}
}
| mit | C# |
313d1b205fbf517243dcd1365297566e5d9b70fa | Remove unused function | leighwoltman/Flickr-Photo-Scanner,leighwoltman/PDF-Scanning-App | Source/DataSource.cs | Source/DataSource.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using Utils;
namespace PDFScanningApp
{
public class ScanSettings
{
}
public class DataSourceNewPageEventArgs : EventArgs
{
public Page ThePage;
}
public class DataSource
{
public bool Acquire(ScanSettings settings)
{
bool success = false;
return success;
}
public bool Scan(string scannerName, double width, double height, double resolution)
{
bool result = false;
List<Image> images = WIAScanner.Scan(scannerName, width, height, resolution);
if (images != null && images.Count != 0)
{
for(int i = 0; i < images.Count; i++)
{
// get a temporary path
string fileName = Path.GetTempFileName();
UtilImaging.SaveImageAsJpeg(images[i], fileName, 75L);
Page myPage = new Page(fileName, true, height == 14 ? ScanPageSize.Legal : ScanPageSize.Letter);
Raise_OnNewPictureData(myPage);
}
// TODO: Do we really need this?
// close all these images
while(images.Count > 0)
{
Image img = images[0];
images.RemoveAt(0);
img.Dispose();
}
Raise_OnScanningComplete();
result = true;
}
return result;
}
public event EventHandler OnNewPage;
private void Raise_OnNewPictureData(Page page)
{
if(OnNewPage != null)
{
DataSourceNewPageEventArgs args = new DataSourceNewPageEventArgs();
args.ThePage = page;
OnNewPage(this, args);
}
}
public event EventHandler OnScanningComplete;
private void Raise_OnScanningComplete()
{
if(OnScanningComplete != null)
{
OnScanningComplete(this, EventArgs.Empty);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using Utils;
namespace PDFScanningApp
{
public class ScanSettings
{
}
public class DataSourceNewPageEventArgs : EventArgs
{
public Page ThePage;
}
public class DataSource
{
public bool Acquire(ScanSettings settings)
{
bool success = false;
return success;
}
public bool Scan(string scannerName, double width, double height, double resolution)
{
bool result = false;
List<Image> images = WIAScanner.Scan(scannerName, width, height, resolution);
if (images != null && images.Count != 0)
{
for(int i = 0; i < images.Count; i++)
{
// get a temporary path
string fileName = Path.GetTempFileName();
UtilImaging.SaveImageAsJpeg(images[i], fileName, 75L);
Page myPage = new Page(fileName, true, height == 14 ? ScanPageSize.Legal : ScanPageSize.Letter);
Raise_OnNewPictureData(myPage);
}
// TODO: Do we really need this?
// close all these images
while(images.Count > 0)
{
Image img = images[0];
images.RemoveAt(0);
img.Dispose();
}
Raise_OnScanningComplete();
result = true;
}
return result;
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach(ImageCodecInfo codec in codecs)
{
if(codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
public event EventHandler OnNewPage;
private void Raise_OnNewPictureData(Page page)
{
if(OnNewPage != null)
{
DataSourceNewPageEventArgs args = new DataSourceNewPageEventArgs();
args.ThePage = page;
OnNewPage(this, args);
}
}
public event EventHandler OnScanningComplete;
private void Raise_OnScanningComplete()
{
if(OnScanningComplete != null)
{
OnScanningComplete(this, EventArgs.Empty);
}
}
}
}
| mit | C# |
7d7dc8e21fb7d76b02f5d72275175acfe243fe05 | Fix OSX bug on MachineName #5732. | krytarowski/corefx,MaggieTsang/corefx,ellismg/corefx,tijoytom/corefx,alphonsekurian/corefx,manu-silicon/corefx,Priya91/corefx-1,DnlHarvey/corefx,parjong/corefx,krk/corefx,Priya91/corefx-1,dotnet-bot/corefx,Petermarcu/corefx,dhoehna/corefx,kkurni/corefx,BrennanConroy/corefx,fgreinacher/corefx,adamralph/corefx,manu-silicon/corefx,shimingsg/corefx,cydhaselton/corefx,nchikanov/corefx,tstringer/corefx,manu-silicon/corefx,ericstj/corefx,billwert/corefx,cydhaselton/corefx,zhenlan/corefx,shimingsg/corefx,marksmeltzer/corefx,YoupHulsebos/corefx,ptoonen/corefx,tijoytom/corefx,ravimeda/corefx,gkhanna79/corefx,Jiayili1/corefx,kkurni/corefx,axelheer/corefx,Petermarcu/corefx,dotnet-bot/corefx,dhoehna/corefx,jhendrixMSFT/corefx,ellismg/corefx,marksmeltzer/corefx,alexperovich/corefx,wtgodbe/corefx,the-dwyer/corefx,ptoonen/corefx,janhenke/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,stone-li/corefx,shmao/corefx,jcme/corefx,dsplaisted/corefx,weltkante/corefx,Chrisboh/corefx,Jiayili1/corefx,rubo/corefx,mmitche/corefx,ravimeda/corefx,elijah6/corefx,benjamin-bader/corefx,stephenmichaelf/corefx,nbarbettini/corefx,axelheer/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,rubo/corefx,weltkante/corefx,cydhaselton/corefx,fgreinacher/corefx,dhoehna/corefx,seanshpark/corefx,weltkante/corefx,stephenmichaelf/corefx,JosephTremoulet/corefx,Jiayili1/corefx,seanshpark/corefx,MaggieTsang/corefx,DnlHarvey/corefx,jcme/corefx,Jiayili1/corefx,ptoonen/corefx,shahid-pk/corefx,manu-silicon/corefx,JosephTremoulet/corefx,shimingsg/corefx,iamjasonp/corefx,twsouthwick/corefx,mokchhya/corefx,alexperovich/corefx,the-dwyer/corefx,jlin177/corefx,alexperovich/corefx,twsouthwick/corefx,dsplaisted/corefx,ericstj/corefx,tijoytom/corefx,dotnet-bot/corefx,mazong1123/corefx,ViktorHofer/corefx,krytarowski/corefx,rubo/corefx,yizhang82/corefx,benpye/corefx,khdang/corefx,krytarowski/corefx,tstringer/corefx,BrennanConroy/corefx,alexperovich/corefx,cartermp/corefx,Petermarcu/corefx,billwert/corefx,MaggieTsang/corefx,adamralph/corefx,DnlHarvey/corefx,richlander/corefx,shahid-pk/corefx,cartermp/corefx,shimingsg/corefx,yizhang82/corefx,gkhanna79/corefx,alphonsekurian/corefx,nchikanov/corefx,rjxby/corefx,kkurni/corefx,manu-silicon/corefx,richlander/corefx,fgreinacher/corefx,ellismg/corefx,ViktorHofer/corefx,billwert/corefx,ViktorHofer/corefx,jhendrixMSFT/corefx,marksmeltzer/corefx,krytarowski/corefx,Chrisboh/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,billwert/corefx,seanshpark/corefx,seanshpark/corefx,stone-li/corefx,janhenke/corefx,jlin177/corefx,wtgodbe/corefx,stephenmichaelf/corefx,dhoehna/corefx,ravimeda/corefx,ellismg/corefx,rahku/corefx,zhenlan/corefx,richlander/corefx,mazong1123/corefx,tstringer/corefx,YoupHulsebos/corefx,axelheer/corefx,alphonsekurian/corefx,alexperovich/corefx,cydhaselton/corefx,cartermp/corefx,nchikanov/corefx,janhenke/corefx,DnlHarvey/corefx,jlin177/corefx,YoupHulsebos/corefx,jhendrixMSFT/corefx,mokchhya/corefx,benpye/corefx,dhoehna/corefx,manu-silicon/corefx,krk/corefx,weltkante/corefx,twsouthwick/corefx,wtgodbe/corefx,SGuyGe/corefx,ViktorHofer/corefx,benpye/corefx,lggomez/corefx,jlin177/corefx,ViktorHofer/corefx,rjxby/corefx,Priya91/corefx-1,seanshpark/corefx,dotnet-bot/corefx,pallavit/corefx,shahid-pk/corefx,billwert/corefx,shahid-pk/corefx,nchikanov/corefx,zhenlan/corefx,mazong1123/corefx,shmao/corefx,lggomez/corefx,iamjasonp/corefx,SGuyGe/corefx,parjong/corefx,jcme/corefx,jhendrixMSFT/corefx,Petermarcu/corefx,iamjasonp/corefx,wtgodbe/corefx,the-dwyer/corefx,lggomez/corefx,rubo/corefx,tstringer/corefx,rahku/corefx,elijah6/corefx,billwert/corefx,benjamin-bader/corefx,Jiayili1/corefx,alphonsekurian/corefx,BrennanConroy/corefx,Ermiar/corefx,mazong1123/corefx,alexperovich/corefx,kkurni/corefx,jlin177/corefx,gkhanna79/corefx,rahku/corefx,mafiya69/corefx,fgreinacher/corefx,Ermiar/corefx,lggomez/corefx,alexperovich/corefx,benjamin-bader/corefx,marksmeltzer/corefx,zhenlan/corefx,seanshpark/corefx,ericstj/corefx,marksmeltzer/corefx,rjxby/corefx,ptoonen/corefx,nbarbettini/corefx,shmao/corefx,nchikanov/corefx,Priya91/corefx-1,mafiya69/corefx,weltkante/corefx,Jiayili1/corefx,DnlHarvey/corefx,rahku/corefx,Priya91/corefx-1,benjamin-bader/corefx,benpye/corefx,richlander/corefx,pallavit/corefx,ViktorHofer/corefx,nbarbettini/corefx,parjong/corefx,axelheer/corefx,Chrisboh/corefx,JosephTremoulet/corefx,iamjasonp/corefx,dhoehna/corefx,cartermp/corefx,YoupHulsebos/corefx,wtgodbe/corefx,benjamin-bader/corefx,mmitche/corefx,weltkante/corefx,Chrisboh/corefx,stephenmichaelf/corefx,ptoonen/corefx,yizhang82/corefx,cartermp/corefx,khdang/corefx,shimingsg/corefx,mmitche/corefx,gkhanna79/corefx,YoupHulsebos/corefx,wtgodbe/corefx,tijoytom/corefx,jhendrixMSFT/corefx,janhenke/corefx,axelheer/corefx,benjamin-bader/corefx,jlin177/corefx,ravimeda/corefx,mafiya69/corefx,jlin177/corefx,stephenmichaelf/corefx,parjong/corefx,zhenlan/corefx,dhoehna/corefx,gkhanna79/corefx,elijah6/corefx,mazong1123/corefx,stone-li/corefx,benpye/corefx,tstringer/corefx,jcme/corefx,mmitche/corefx,shmao/corefx,khdang/corefx,lggomez/corefx,rubo/corefx,tijoytom/corefx,ericstj/corefx,dsplaisted/corefx,nbarbettini/corefx,dotnet-bot/corefx,ericstj/corefx,jhendrixMSFT/corefx,jhendrixMSFT/corefx,Ermiar/corefx,Ermiar/corefx,khdang/corefx,mmitche/corefx,shahid-pk/corefx,ravimeda/corefx,shimingsg/corefx,Jiayili1/corefx,nbarbettini/corefx,wtgodbe/corefx,Ermiar/corefx,nbarbettini/corefx,ptoonen/corefx,tijoytom/corefx,seanshpark/corefx,shmao/corefx,krk/corefx,krk/corefx,cydhaselton/corefx,MaggieTsang/corefx,weltkante/corefx,zhenlan/corefx,rahku/corefx,marksmeltzer/corefx,ravimeda/corefx,richlander/corefx,SGuyGe/corefx,krytarowski/corefx,alphonsekurian/corefx,rjxby/corefx,stone-li/corefx,elijah6/corefx,lggomez/corefx,yizhang82/corefx,SGuyGe/corefx,YoupHulsebos/corefx,alphonsekurian/corefx,khdang/corefx,JosephTremoulet/corefx,krk/corefx,pallavit/corefx,khdang/corefx,shahid-pk/corefx,pallavit/corefx,stone-li/corefx,SGuyGe/corefx,manu-silicon/corefx,pallavit/corefx,shimingsg/corefx,rjxby/corefx,elijah6/corefx,Petermarcu/corefx,alphonsekurian/corefx,Petermarcu/corefx,twsouthwick/corefx,ericstj/corefx,nchikanov/corefx,mokchhya/corefx,richlander/corefx,Chrisboh/corefx,parjong/corefx,SGuyGe/corefx,kkurni/corefx,krk/corefx,pallavit/corefx,mazong1123/corefx,janhenke/corefx,axelheer/corefx,parjong/corefx,mmitche/corefx,mafiya69/corefx,twsouthwick/corefx,mokchhya/corefx,richlander/corefx,parjong/corefx,kkurni/corefx,MaggieTsang/corefx,stone-li/corefx,Ermiar/corefx,yizhang82/corefx,mmitche/corefx,nbarbettini/corefx,yizhang82/corefx,the-dwyer/corefx,iamjasonp/corefx,nchikanov/corefx,ravimeda/corefx,ptoonen/corefx,MaggieTsang/corefx,mokchhya/corefx,elijah6/corefx,cartermp/corefx,rjxby/corefx,rahku/corefx,marksmeltzer/corefx,lggomez/corefx,jcme/corefx,Ermiar/corefx,tstringer/corefx,gkhanna79/corefx,stone-li/corefx,stephenmichaelf/corefx,Priya91/corefx-1,the-dwyer/corefx,krk/corefx,rahku/corefx,ellismg/corefx,the-dwyer/corefx,ellismg/corefx,krytarowski/corefx,DnlHarvey/corefx,billwert/corefx,mafiya69/corefx,mafiya69/corefx,yizhang82/corefx,gkhanna79/corefx,dotnet-bot/corefx,janhenke/corefx,tijoytom/corefx,MaggieTsang/corefx,mazong1123/corefx,Chrisboh/corefx,iamjasonp/corefx,JosephTremoulet/corefx,twsouthwick/corefx,benpye/corefx,the-dwyer/corefx,elijah6/corefx,Petermarcu/corefx,jcme/corefx,stephenmichaelf/corefx,cydhaselton/corefx,shmao/corefx,twsouthwick/corefx,shmao/corefx,zhenlan/corefx,mokchhya/corefx,cydhaselton/corefx,adamralph/corefx,ericstj/corefx,iamjasonp/corefx,krytarowski/corefx,rjxby/corefx | src/System.Runtime.Extensions/tests/System/Environment.MachineName.cs | src/System.Runtime.Extensions/tests/System/Environment.MachineName.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Runtime.Extensions.Tests
{
public class Environment_MachineName
{
[Fact]
public void TestMachineNameProperty()
{
string computerName = GetComputerName();
Assert.Equal(computerName, Environment.MachineName);
}
internal static string GetComputerName()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Environment.GetEnvironmentVariable("COMPUTERNAME");
}
else
{
string temp = Interop.Sys.GetNodeName();
int index = temp.IndexOf('.');
return index < 0 ? temp : temp.Substring(0, index);
}
}
}
} | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Runtime.Extensions.Tests
{
public class Environment_MachineName
{
[ActiveIssue(5732, PlatformID.OSX)]
[Fact]
public void TestMachineNameProperty()
{
string computerName = GetComputerName();
Assert.Equal(computerName, Environment.MachineName);
}
internal static string GetComputerName()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Environment.GetEnvironmentVariable("COMPUTERNAME");
}
else
{
return Interop.Sys.GetNodeName();
}
}
}
} | mit | C# |
91e406b6daf6b77bb15c9d18b53e0d1a4f3a84ca | Fix typo in assemblyinfo Fixes #76 | jamesmontemagno/GeolocatorPlugin,jamesmontemagno/GeolocatorPlugin | src/Geolocator.Plugin.Android/Properties/AssemblyInfo.cs | src/Geolocator.Plugin.Android/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("Plugin.Geolocator")]
[assembly: AssemblyProduct("Plugin.Geolocator")]
[assembly: ComVisible(false)]
[assembly: UsesPermission(Android.Manifest.Permission.AccessCoarseLocation)]
[assembly: UsesPermission(Android.Manifest.Permission.AccessFineLocation)]
//Required when targeting Android API 21+
[assembly: UsesFeature("android.hardware.location.gps")]
[assembly: UsesFeature("android.hardware.location.network")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("Plugin.Geolocator")]
[assembly: AssemblyProduct("Plugin.Geolocator")]
[assembly: ComVisible(false)]
[assembly: UsesPermission(Android.Manifest.Permission.AccessCoarseLocation)]
[assembly: UsesPermission(Android.Manifest.Permission.AccessFineLocation)]
//Required when targeting Android API 21+
[assembly: UsesFeature("android.feature.location.gps")]
[assembly: UsesFeature("android.feature.location.network")] | mit | C# |
8b49c0d088157bb6cea18d9a2445d9b761e3de37 | Move validation into assembly resolve | TBAPI-0KA/NSass,TBAPI-0KA/NSass,TBAPI-0KA/NSass,TBAPI-0KA/NSass,TBAPI-0KA/NSass,TBAPI-0KA/NSass | NSass.Core/AssemblyResolver.cs | NSass.Core/AssemblyResolver.cs | using System;
using System.IO;
using System.Reflection;
namespace NSass
{
public static class AssemblyResolver
{
private const string AssemblyName = "NSass.Wrapper";
private const string AssembliesDir = "NSass.Wrapper";
public static void Initialize()
{
string assemblyDir = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
// PrivateBinPath is empty in test scenarios; use BaseDirectory instead
if (String.IsNullOrEmpty(assemblyDir))
{
assemblyDir = AppDomain.CurrentDomain.BaseDirectory;
}
assemblyDir = Path.Combine(assemblyDir, AssembliesDir);
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
if (args.Name.StartsWith(String.Format("{0}.proxy,", AssemblyName), StringComparison.OrdinalIgnoreCase))
{
if (IsProxyPresent(assemblyDir))
{
throw new InvalidOperationException(String.Format("Found {0}.proxy.dll which cannot exist. Must instead have {0}.x86.dll and {0}.x64.dll. Check your build settings." + assemblyDir, AssemblyName));
}
string x86FullPath = Path.Combine(assemblyDir, String.Format("{0}.x86.dll", AssemblyName));
string x64FullPath = Path.Combine(assemblyDir, String.Format("{0}.x64.dll", AssemblyName));
string fileName = Environment.Is64BitProcess ? x64FullPath : x86FullPath;
if (!File.Exists(fileName))
{
throw new InvalidOperationException(string.Format("Could not find the wrapper assembly. It may not have been copied to the output directory. Path='{0}'",fileName));
}
return Assembly.LoadFile(fileName);
}
return null;
};
}
private static bool IsProxyPresent(string assemblyDir)
{
return File.Exists(Path.Combine(assemblyDir, AssemblyName + ".proxy.dll"));
}
}
} | using System;
using System.IO;
using System.Reflection;
namespace NSass
{
public static class AssemblyResolver
{
private const string AssemblyName = "NSass.Wrapper";
private const string AssembliesDir = "NSass.Wrapper";
public static void Initialize()
{
string assemblyDir = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
// PrivateBinPath is empty in test scenarios; use BaseDirectory instead
if (String.IsNullOrEmpty(assemblyDir))
{
assemblyDir = AppDomain.CurrentDomain.BaseDirectory;
}
assemblyDir = Path.Combine(assemblyDir, AssembliesDir);
string proxyFullPath = Path.Combine(assemblyDir, String.Format("{0}.proxy.dll", AssemblyName));
string x86FullPath = Path.Combine(assemblyDir, String.Format("{0}.x86.dll", AssemblyName));
string x64FullPath = Path.Combine(assemblyDir, String.Format("{0}.x64.dll", AssemblyName));
if (File.Exists(proxyFullPath) || !File.Exists(x86FullPath) || !File.Exists(x64FullPath))
{
throw new InvalidOperationException(String.Format("Found {0}.proxy.dll which cannot exist. Must instead have {0}.x86.dll and {0}.x64.dll. Check your build settings." + assemblyDir, AssemblyName));
}
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
if (args.Name.StartsWith(String.Format("{0}.proxy,", AssemblyName), StringComparison.OrdinalIgnoreCase))
{
string fileName = Path.Combine(assemblyDir, String.Format("{0}.{1}.dll", AssemblyName, Environment.Is64BitProcess ? "x64" : "x86"));
return Assembly.LoadFile(fileName);
}
return null;
};
}
}
} | mit | C# |
f1e2b72cb73279d936f748ab1d94dd3979524397 | Refactor prerequisite check for audit queue address | Simution/NServiceBus.Recoverability.RetrySuccessNotification | src/RetrySuccessNotification/RetrySuccessNotification.cs | src/RetrySuccessNotification/RetrySuccessNotification.cs | namespace NServiceBus.Features
{
using Recoverability;
using Transport;
/// <inheritdoc />
/// <summary>
/// Provides the retry success notification feature
/// </summary>
public class RetrySuccessNotification : Feature
{
internal const string TriggerHeadersKey = "RetrySuccessNotifications.Headers";
internal const string AddressKey = "RetrySuccessNotifications.Address";
internal const string CopyBody = "RetrySuccessNotification.CopyBody";
// ReSharper disable once MemberCanBePrivate.Global
internal static string[] DefaultTriggerHeaders = {
ServiceControlRetryHeaders.OldRetryId,
ServiceControlRetryHeaders.UniqueMessageId
};
internal RetrySuccessNotification()
{
EnableByDefault();
Defaults(settings =>
{
settings.Set(TriggerHeadersKey, DefaultTriggerHeaders);
settings.Set(CopyBody, false);
});
Prerequisite(config =>
{
if (!config.Settings.IsFeatureActive(typeof(Audit)))
{
return true;
}
config.Settings.TryGetAuditQueueAddress(out var auditAddress);
return auditAddress != config.Settings.GetOrDefault<string>(AddressKey);
}, "Retry Success Notifications cannot be sent to the same queue as Audits");
Prerequisite(config => !string.IsNullOrWhiteSpace(config.Settings.GetOrDefault<string>(AddressKey)), "No configured retry success notification address was configured");
}
/// <inheritdoc />
protected override void Setup(FeatureConfigurationContext context)
{
var endpointName = context.Settings.EndpointName();
var notificationAddress = context.Settings.Get<string>(AddressKey);
var triggerHeaders = context.Settings.Get<string[]>(TriggerHeadersKey);
var copyBody = context.Settings.Get<bool>(CopyBody);
context.Settings.Get<QueueBindings>().BindSending(notificationAddress);
context.Pipeline.Register(new RetrySuccessNotificationBehavior(endpointName, notificationAddress, triggerHeaders, copyBody), "Adds a retry success notification to the pending transport operations.");
}
}
}
| namespace NServiceBus.Features
{
using Recoverability;
using Transport;
/// <inheritdoc />
/// <summary>
/// Provides the retry success notification feature
/// </summary>
public class RetrySuccessNotification : Feature
{
internal const string TriggerHeadersKey = "RetrySuccessNotifications.Headers";
internal const string AddressKey = "RetrySuccessNotifications.Address";
internal const string CopyBody = "RetrySuccessNotification.CopyBody";
// ReSharper disable once MemberCanBePrivate.Global
internal static string[] DefaultTriggerHeaders = {
ServiceControlRetryHeaders.OldRetryId,
ServiceControlRetryHeaders.UniqueMessageId
};
internal RetrySuccessNotification()
{
EnableByDefault();
Defaults(settings =>
{
settings.Set(TriggerHeadersKey, DefaultTriggerHeaders);
settings.Set(CopyBody, false);
});
Prerequisite(config =>
{
if (!config.Settings.IsFeatureActive(typeof(Audit)))
{
return true;
}
if (!config.Settings.TryGetAuditQueueAddress(out var auditAddress))
{
return true;
}
return auditAddress != config.Settings.GetOrDefault<string>(AddressKey);
}, "Retry Success Notifications cannot be sent to the same queue as Audits");
Prerequisite(config => !string.IsNullOrWhiteSpace(config.Settings.GetOrDefault<string>(AddressKey)), "No configured retry success notification address was configured");
}
/// <inheritdoc />
protected override void Setup(FeatureConfigurationContext context)
{
var endpointName = context.Settings.EndpointName();
var notificationAddress = context.Settings.Get<string>(AddressKey);
var triggerHeaders = context.Settings.Get<string[]>(TriggerHeadersKey);
var copyBody = context.Settings.Get<bool>(CopyBody);
context.Settings.Get<QueueBindings>().BindSending(notificationAddress);
context.Pipeline.Register(new RetrySuccessNotificationBehavior(endpointName, notificationAddress, triggerHeaders, copyBody), "Adds a retry success notification to the pending transport operations.");
}
}
}
| mit | C# |
5cb650411c83fe030b5befbf0ad62904dcbbbdc4 | Update AbpProjectNameWebModule.cs | aspnetboilerplate/module-zero-template,aspnetboilerplate/module-zero-template,aspnetboilerplate/module-zero-template | src/AbpCompanyName.AbpProjectName.WebMpa/App_Start/AbpProjectNameWebModule.cs | src/AbpCompanyName.AbpProjectName.WebMpa/App_Start/AbpProjectNameWebModule.cs | using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Abp.Auditing;
using Abp.Dependency;
using Abp.Hangfire;
using Abp.Hangfire.Configuration;
using Abp.Zero.Configuration;
using Abp.Modules;
using Abp.Web.Mvc;
using Abp.Web.SignalR;
using AbpCompanyName.AbpProjectName.Api;
using Castle.Core;
using Castle.MicroKernel.Registration;
using Hangfire;
using Microsoft.Owin.Security;
namespace AbpCompanyName.AbpProjectName.WebMpa
{
[DependsOn(
typeof(AbpProjectNameDataModule),
typeof(AbpProjectNameApplicationModule),
typeof(AbpProjectNameWebApiModule),
typeof(AbpWebSignalRModule),
//typeof(AbpHangfireModule), - ENABLE TO USE HANGFIRE INSTEAD OF DEFAULT JOB MANAGER
typeof(AbpWebMvcModule))]
public class AbpProjectNameWebModule : AbpModule
{
public override void PreInitialize()
{
//Enable database based localization
Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();
//Configure navigation/menu
Configuration.Navigation.Providers.Add<AbpProjectNameNavigationProvider>();
//Configure Hangfire - ENABLE TO USE HANGFIRE INSTEAD OF DEFAULT JOB MANAGER
//Configuration.BackgroundJobs.UseHangfire(configuration =>
//{
// configuration.GlobalConfiguration.UseSqlServerStorage("Default");
//});
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
IocManager.IocContainer.Register(
Component
.For<IAuthenticationManager>()
.UsingFactoryMethod(() => HttpContext.Current.GetOwinContext().Authentication)
.LifestyleTransient()
);
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Abp.Auditing;
using Abp.Dependency;
using Abp.Hangfire;
using Abp.Hangfire.Configuration;
using Abp.Zero.Configuration;
using Abp.Modules;
using Abp.Web.Mvc;
using Abp.Web.SignalR;
using AbpCompanyName.AbpProjectName.Api;
using Castle.Core;
using Castle.MicroKernel.Registration;
using Hangfire;
using Microsoft.Owin.Security;
namespace AbpCompanyName.AbpProjectName.WebMpa
{
[DependsOn(
typeof(AbpProjectNameDataModule),
typeof(AbpProjectNameApplicationModule),
typeof(AbpProjectNameWebApiModule),
typeof(AbpWebSignalRModule),
//typeof(AbpHangfireModule), - ENABLE TO USE HANGFIRE INSTEAD OF DEFAULT JOB MANAGER
typeof(AbpWebMvcModule))]
public class AbpProjectNameWebModule : AbpModule
{
public override void PreInitialize()
{
//Enable database based localization
Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();
//Configure navigation/menu
Configuration.Navigation.Providers.Add<AbpProjectNameNavigationProvider>();
//Configure Hangfire - ENABLE TO USE HANGFIRE INSTEAD OF DEFAULT JOB MANAGER
//Configuration.BackgroundJobs.UseHangfire(configuration =>
//{
// configuration.GlobalConfiguration.UseSqlServerStorage("Default");
//});
Configuration.ReplaceService(typeof(IClientInfoProvider), () =>
{
Configuration.IocManager.Register<IClientInfoProvider, AbpZeroTemplateClientInfoProvider>(DependencyLifeStyle.Transient);
});
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
IocManager.IocContainer.Register(
Component
.For<IAuthenticationManager>()
.UsingFactoryMethod(() => HttpContext.Current.GetOwinContext().Authentication)
.LifestyleTransient()
);
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| mit | C# |
27f1ccbbf21cf62417d7fb89f37f13914af6aa29 | Update doc comment | Cyberboss/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools | TGServiceInterface/ServiceBridge.cs | TGServiceInterface/ServiceBridge.cs | using System;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;
using System.ServiceModel;
namespace TGServiceInterface
{
/// <summary>
/// Used by DD to access the interop API with call()()
/// </summary>
[ServiceContract]
public interface ITGServiceBridge
{
/// <summary>
/// Called from /world/ExportService(command)
/// </summary>
/// <param name="command">The command to run</param>
/// <returns>true on success, false on failure</returns>
[OperationContract]
bool InteropMessage(string command);
}
/// <summary>
/// Holds the proc that DD calls to access <see cref="ITGServiceBridge"/>
/// </summary>
public class DDInteropCallHolder
{
/// <summary>
/// The proc that DD calls to access <see cref="ITGServiceBridge"/>
/// </summary>
/// <param name="args">The arguments passed</param>
/// <returns>0</returns>
[DllExport("DDEntryPoint", CallingConvention = CallingConvention.Cdecl)]
public static int DDEntryPoint(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 0)]string[] args)
{
try
{
ChannelFactory<ITGServiceBridge> channel = null;
try
{
Server.GetComponentAndChannel(out channel).InteropMessage(String.Join(" ", args));
channel.Close();
}
catch
{
if(channel != null)
channel.Abort();
}
}
catch { }
return 0;
}
}
}
| using System;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;
using System.ServiceModel;
namespace TGServiceInterface
{
/// <summary>
/// Used by DD to access the interop API with call()()
/// </summary>
[ServiceContract]
public interface ITGServiceBridge
{
/// <summary>
/// Called from /world/ExportService(command)
/// </summary>
/// <param name="command">The command to run</param>
/// <returns>true on success, false on failure</returns>
[OperationContract]
bool InteropMessage(string command);
}
/// <summary>
/// Holds the proc that DD calls to access <see cref="ITGServiceBridge"/>
/// </summary>
public class DDInteropCallHolder
{
/// <summary>
/// The proc that DD calls to access <see cref="ITGServiceBridge"/>
/// </summary>
/// <param name="args">The arguments passed</param>
/// <returns>0 success, -1 on a WCF, error, 1 on an operation error</returns>
[DllExport("DDEntryPoint", CallingConvention = CallingConvention.Cdecl)]
public static int DDEntryPoint(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 0)]string[] args)
{
try
{
ChannelFactory<ITGServiceBridge> channel = null;
try
{
Server.GetComponentAndChannel(out channel).InteropMessage(String.Join(" ", args));
channel.Close();
}
catch
{
if(channel != null)
channel.Abort();
}
}
catch { }
return 0;
}
}
}
| agpl-3.0 | C# |
c5f7fa52a799a0701032ada4b4d969fe8336ed93 | Fix for gallio on non-windows systems | Psychobilly87/bari,Psychobilly87/bari,vigoo/bari,vigoo/bari,vigoo/bari,Psychobilly87/bari,Psychobilly87/bari,vigoo/bari | src/dotnetplugins/Bari.Plugins.Gallio/cs/Tools/Gallio.cs | src/dotnetplugins/Bari.Plugins.Gallio/cs/Tools/Gallio.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Bari.Core.Generic;
using Bari.Core.Tools;
using Bari.Core.UI;
namespace Bari.Plugins.Gallio.Tools
{
public class Gallio: DownloadablePackedExternalTool, IGallio
{
private readonly IFileSystemDirectory targetDir;
public Gallio([TargetRoot] IFileSystemDirectory targetDir, IParameters parameters)
: base("Gallio", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "gallio"),
Path.Combine("bin", "Gallio.Echo.exe"), new Uri("http://mb-unit.googlecode.com/files/GallioBundle-3.4.14.0.zip"), true, parameters)
{
this.targetDir = targetDir;
}
public bool RunTests(IEnumerable<TargetRelativePath> testAssemblies)
{
List<string> ps = testAssemblies.Select(p => (string)p).ToList();
ps.Add("/report-type:Xml");
ps.Add("/report-directory:.");
ps.Add("/report-formatter-property:AttachmentContentDisposition=Absent");
ps.Add("/report-name-format:test-report");
return Run(targetDir, ps.ToArray());
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Bari.Core.Generic;
using Bari.Core.Tools;
using Bari.Core.UI;
namespace Bari.Plugins.Gallio.Tools
{
public class Gallio: DownloadablePackedExternalTool, IGallio
{
private readonly IFileSystemDirectory targetDir;
public Gallio([TargetRoot] IFileSystemDirectory targetDir, IParameters parameters)
: base("Gallio", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "gallio"),
@"bin\Gallio.Echo.exe", new Uri("http://mb-unit.googlecode.com/files/GallioBundle-3.4.14.0.zip"), true, parameters)
{
this.targetDir = targetDir;
}
public bool RunTests(IEnumerable<TargetRelativePath> testAssemblies)
{
List<string> ps = testAssemblies.Select(p => (string)p).ToList();
ps.Add("/report-type:Xml");
ps.Add("/report-directory:.");
ps.Add("/report-formatter-property:AttachmentContentDisposition=Absent");
ps.Add("/report-name-format:test-report");
return Run(targetDir, ps.ToArray());
}
}
} | apache-2.0 | C# |
c9a09c0d3053214954cbe97da1a92afd540ebd52 | Add a couple of SharpDX Math related assertion helpers | virtuallynaked/virtually-naked,virtuallynaked/virtually-naked | Viewer/src/common/DebugUtilities.cs | Viewer/src/common/DebugUtilities.cs | using SharpDX;
using System;
using System.Diagnostics;
using System.Threading;
static class DebugUtilities {
public static void Burn(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
}
}
public static void Sleep(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
Thread.Yield();
}
}
[Conditional("DEBUG")]
public static void AssertSamePosition(Vector3 v1, Vector3 v2) {
float distance = Vector3.Distance(v1, v2);
float denominator = (Vector3.Distance(v1, Vector3.Zero) + Vector3.Distance(v2, Vector3.Zero)) / 2 + 1e-1f;
float relativeDistance = distance / denominator;
Debug.Assert(relativeDistance < 1e-2, "not same position");
}
[Conditional("DEBUG")]
public static void AssertSameDirection(Vector3 v1, Vector3 v2) {
Vector3 u1 = Vector3.Normalize(v1);
Vector3 u2 = Vector3.Normalize(v2);
float dotProduct = Vector3.Dot(u1, u2);
Debug.Assert(Math.Abs(dotProduct - 1) < 1e-2f, "not same direction");
}
}
| using System.Diagnostics;
using System.Threading;
static class DebugUtilities {
public static void Burn(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
}
}
public static void Sleep(long ms) {
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < ms) {
Thread.Yield();
}
}
}
| mit | C# |
d11119f12eb4d94a7f6d69475d5918a2c43935a5 | make constructor of ObcSimplyfingSerializerFactory public | OBeautifulCode/OBeautifulCode.Serialization | OBeautifulCode.Serialization/SerializerFactory/ObcSimplifyingSerializerFactory.cs | OBeautifulCode.Serialization/SerializerFactory/ObcSimplifyingSerializerFactory.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ObcSimplifyingSerializerFactory.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.Serialization
{
using OBeautifulCode.Type;
/// <summary>
/// A serializer factory that wraps the serializers built by a backing factory with an <see cref="ObcSimplifyingSerializer"/>.
/// </summary>
public class ObcSimplifyingSerializerFactory : ISerializerFactory
{
/// <summary>
/// Initializes a new instance of the <see cref="ObcSimplifyingSerializerFactory"/> class.
/// </summary>
/// <param name="backingSerializerFactory">The backing serializer factory.</param>
public ObcSimplifyingSerializerFactory(
ISerializerFactory backingSerializerFactory)
{
this.BackingSerializerFactory = backingSerializerFactory;
}
/// <summary>
/// Gets the backing serializer factory.
/// </summary>
public ISerializerFactory BackingSerializerFactory { get; }
/// <inheritdoc />
public ISerializer BuildSerializer(
SerializerRepresentation serializerRepresentation,
VersionMatchStrategy assemblyVersionMatchStrategy = VersionMatchStrategy.AnySingleVersion)
{
var fallbackSerializer = this.BackingSerializerFactory.BuildSerializer(serializerRepresentation, assemblyVersionMatchStrategy);
var result = new ObcSimplifyingSerializer(fallbackSerializer);
return result;
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ObcSimplifyingSerializerFactory.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.Serialization
{
using OBeautifulCode.Type;
/// <summary>
/// A serializer factory that wraps the serializers built by a backing factory with an <see cref="ObcSimplifyingSerializer"/>.
/// </summary>
public class ObcSimplifyingSerializerFactory : ISerializerFactory
{
/// <summary>
/// Initializes a new instance of the <see cref="ObcSimplifyingSerializerFactory"/> class.
/// </summary>
/// <param name="backingSerializerFactory">The backing serializer factory.</param>
protected ObcSimplifyingSerializerFactory(
ISerializerFactory backingSerializerFactory)
{
this.BackingSerializerFactory = backingSerializerFactory;
}
/// <summary>
/// Gets the backing serializer factory.
/// </summary>
public ISerializerFactory BackingSerializerFactory { get; }
/// <inheritdoc />
public ISerializer BuildSerializer(
SerializerRepresentation serializerRepresentation,
VersionMatchStrategy assemblyVersionMatchStrategy = VersionMatchStrategy.AnySingleVersion)
{
var fallbackSerializer = this.BackingSerializerFactory.BuildSerializer(serializerRepresentation, assemblyVersionMatchStrategy);
var result = new ObcSimplifyingSerializer(fallbackSerializer);
return result;
}
}
}
| mit | C# |
791d69267575e8f20c96bdc9cebc1e7329b27cc7 | Fix short conversion | SnapMD/connectedcare-sdk,dhawalharsora/connectedcare-sdk | SnapMD.VirtualCare.ApiModels/Scheduling/AppointmentOptimizationCode.cs | SnapMD.VirtualCare.ApiModels/Scheduling/AppointmentOptimizationCode.cs | namespace SnapMD.VirtualCare.ApiModels.Scheduling
{
/// <summary>
/// Appointment optimization code.
/// </summary>
public enum AppointmentOptimizationCode : short
{
/// <summary>
/// Single booking.
/// </summary>
SingleBooking,
/// <summary>
/// Double booking.
/// </summary>
DoubleBooking
}
}
| namespace SnapMD.VirtualCare.ApiModels.Scheduling
{
/// <summary>
/// Appointment optimization code.
/// </summary>
public enum AppointmentOptimizationCode
{
/// <summary>
/// Single booking.
/// </summary>
SingleBooking,
/// <summary>
/// Double booking.
/// </summary>
DoubleBooking
}
}
| apache-2.0 | C# |
8ab736e5022dcc5a47feeb828480b960eef92374 | Update Index.cshtml | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Home/Index.cshtml | Anlab.Mvc/Views/Home/Index.cshtml | @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<!-- <h2 style="color: blue">PLEASE NOTE: There will be a modest increase in our rates effective in early October.</h2> -->
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses.
</p>
<p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the
operation of a number of analytical methods and instruments.</p>
<p>Please Note: Dirk Holstege has recently retired as Laboratory Director of the UC Davis Analytical Laboratory.
We thank him for his nearly twenty years of service as Director of the Analytical Lab and his thirty-two years of service
as a UC Davis employee. We wish him all the best in his retirement.<br/> <br/>
Traci Francis, Laboratory Supervisor, is serving as Interim Director. </p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
</address>
</div>
| @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<h2 style="color: blue">PLEASE NOTE: There will be a modest increase in our rates effective in early October.</h2>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses.
</p>
<p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the
operation of a number of analytical methods and instruments.</p>
<p>Please Note: Dirk Holstege has recently retired as Laboratory Director of the UC Davis Analytical Laboratory.
We thank him for his nearly twenty years of service as Director of the Analytical Lab and his thirty-two years of service
as a UC Davis employee. We wish him all the best in his retirement.<br/> <br/>
Traci Francis, Laboratory Supervisor, is serving as Interim Director. </p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
</address>
</div>
| mit | C# |
20143a01653e9eb1d5c68ce4e9f642603f4d53c3 | Attach the application to the WebApp's graceful shutdown event. | MarinAtanasov/AppBrix,MarinAtanasov/AppBrix.NetCore | src/AppBrix.WebApp/Startup.cs | src/AppBrix.WebApp/Startup.cs | using AppBrix.Application;
using AppBrix.Configuration;
using AppBrix.Configuration.Files;
using AppBrix.Configuration.Yaml;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
namespace AppBrix.WebApp
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
// Add AppBrix app.
var configManager = new ConfigManager(new FilesConfigProvider("./Config", "yaml"), new YamlConfigSerializer());
if (configManager.Get<AppConfig>().Modules.Count == 0)
configManager.Get<AppConfig>().Modules.Add(ModuleConfigElement.Create<ConfigInitializerModule>());
this.App = AppBrix.App.Create(configManager);
this.App.Start();
}
public IConfigurationRoot Configuration { get; }
public IApp App { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// Add AppBrix app to the DI container.
services.AddApp(this.App);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// Add AppBrix logging provider.
loggerFactory.AddProvider(this.App);
app.UseMvc();
// Dispose of AppBrix app during a graceful shutdown.
lifetime.ApplicationStopped.Register(this.App.Stop);
}
}
}
| using AppBrix.Application;
using AppBrix.Configuration;
using AppBrix.Configuration.Files;
using AppBrix.Configuration.Yaml;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
namespace AppBrix.WebApp
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
// Add AppBrix app.
var configManager = new ConfigManager(new FilesConfigProvider("./Config", "yaml"), new YamlConfigSerializer());
if (configManager.Get<AppConfig>().Modules.Count == 0)
configManager.Get<AppConfig>().Modules.Add(ModuleConfigElement.Create<ConfigInitializerModule>());
this.App = AppBrix.App.Create(configManager);
this.App.Start();
}
public IConfigurationRoot Configuration { get; }
public IApp App { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// Add AppBrix app to the DI container.
services.AddApp(this.App);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// Add AppBrix logging provider.
loggerFactory.AddProvider(this.App);
app.UseMvc();
}
}
}
| mit | C# |
bf3442c631903ee420037b4d1b14e2e584454324 | add more properties to SalesAgent | HeadspringLabs/vandelay,pmcvtm/vandelay,HeadspringLabs/vandelay,pmcvtm/vandelay,pmcvtm/vandelay | src/Core/Models/SalesAgent.cs | src/Core/Models/SalesAgent.cs | namespace Core.Models
{
using System.Collections.Generic;
public class SalesAgent : Entity
{
public string ImageUrl { get; set; }
public Location Location { get; set; }
public List<Export> Exports { get; set; }
public List<Import> Imports { get; set; }
}
} | namespace Core.Models
{
public class SalesAgent : Entity
{
public Location Location { get; set; }
}
} | unlicense | C# |
0eac933c1491242b241fb8809390a44b85e1913f | Convert .Text and .Primitive to interfaces | kornelijepetak/incident-cs | IncidentCS/Incident.Initialize.cs | IncidentCS/Incident.Initialize.cs | using System;
using System.Linq;
namespace KornelijePetak.IncidentCS
{
public static partial class Incident
{
internal static Random Rand { get; private set; }
public static IPrimitiveRandomizer Primitive { get; private set; }
public static ITextRandomizer Text { get; private set; }
static Incident()
{
Rand = new Random();
setupConcreteRandomizers();
}
public static int Seed
{
set
{
Rand = new Random(value);
}
}
}
}
| using System;
using System.Linq;
namespace KornelijePetak.IncidentCS
{
public static partial class Incident
{
internal static Random Rand { get; private set; }
public static PrimitiveRandomizer Primitive { get; private set; }
public static TextRandomizer Text { get; private set; }
static Incident()
{
Rand = new Random();
setupConcreteRandomizers();
}
public static int Seed
{
set
{
Rand = new Random(value);
}
}
}
}
| mit | C# |
23e1c2f89e26c9265f12a6c9f083bd4c008a104c | Add more testing for BasicHttpSecurityMode modes | shmao/wcf,zhenlan/wcf,mconnew/wcf,iamjasonp/wcf,SajayAntony/wcf,shmao/wcf,ElJerry/wcf,imcarolwang/wcf,ericstj/wcf,dotnet/wcf,MattGal/wcf,khdang/wcf,mconnew/wcf,dotnet/wcf,StephenBonikowsky/wcf,SajayAntony/wcf,khdang/wcf,StephenBonikowsky/wcf,ericstj/wcf,ElJerry/wcf,iamjasonp/wcf,hongdai/wcf,MattGal/wcf,mconnew/wcf,KKhurin/wcf,imcarolwang/wcf,dotnet/wcf,zhenlan/wcf,hongdai/wcf,imcarolwang/wcf,KKhurin/wcf | src/System.ServiceModel.Http/tests/ServiceModel/SecurityBindingElementTest.cs | src/System.ServiceModel.Http/tests/ServiceModel/SecurityBindingElementTest.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Xunit;
public static class SecurityBindingElementTest
{
[Fact]
public static void Create_HttpBinding_SecurityMode_TransportWithMessageCredential_Build_Throws()
{
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
var bindingElements = binding.CreateBindingElements();
var securityBindingElement = bindingElements.FirstOrDefault(x => x is SecurityBindingElement) as SecurityBindingElement;
Assert.True(securityBindingElement != null, "securityBindingElement should not be null when BasicHttpSecurityMode is 'TransportWithMessageCredential'");
Assert.True(binding.CanBuildChannelFactory<IRequestChannel>(), "CanBuildChannelFactory should return true for BasicHttpSecurityMode:'TransportWithMessageCredential'");
Assert.Throws<PlatformNotSupportedException>(() => {
binding.BuildChannelFactory<IRequestChannel>();
});
}
[Theory]
[InlineData(BasicHttpSecurityMode.TransportCredentialOnly)]
[InlineData(BasicHttpSecurityMode.Transport)]
[InlineData(BasicHttpSecurityMode.None)]
public static void Create_HttpBinding_SecurityMode_Without_SecurityBindingElement(BasicHttpSecurityMode securityMode)
{
BasicHttpBinding binding = new BasicHttpBinding(securityMode);
var bindingElements = binding.CreateBindingElements();
var securityBindingElement = bindingElements.FirstOrDefault(x => x is SecurityBindingElement) as SecurityBindingElement;
Assert.True(securityBindingElement == null, string.Format("securityBindingElement should be null when BasicHttpSecurityMode is '{0}'", securityMode));
Assert.True(binding.CanBuildChannelFactory<IRequestChannel>(), string.Format("CanBuildChannelFactory should return true for BasicHttpSecurityMode:'{0}'", securityMode));
binding.BuildChannelFactory<IRequestChannel>();
}
[Theory]
[InlineData(BasicHttpSecurityMode.Message)]
// BasicHttpSecurityMode.Message is not supported
public static void Create_HttpBinding_SecurityMode_Message_Throws_NotSupported(BasicHttpSecurityMode securityMode)
{
BasicHttpBinding binding = new BasicHttpBinding(securityMode);
Assert.Throws<NotSupportedException>(() => {
var bindingElements = binding.CreateBindingElements();
});
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Xunit;
public static class SecurityBindingElementTest
{
[Fact]
public static void Create_HttpBinding_SecurityMode_TransportWithMessageCredential()
{
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
var bindingElements = binding.CreateBindingElements();
var securityBindingElement = bindingElements.FirstOrDefault(x => x is SecurityBindingElement) as SecurityBindingElement;
Assert.True(securityBindingElement != null, "securityBindingElement should not be null when BasicHttpSecurityMode.TransportWithMessageCredential is specified");
}
[Theory]
[InlineData(BasicHttpSecurityMode.TransportCredentialOnly)]
[InlineData(BasicHttpSecurityMode.Transport)]
[InlineData(BasicHttpSecurityMode.None)]
public static void Create_HttpBinding_SecurityMode_Without_SecurityBindingElement(BasicHttpSecurityMode securityMode)
{
BasicHttpBinding binding = new BasicHttpBinding(securityMode);
var bindingElements = binding.CreateBindingElements();
var securityBindingElement = bindingElements.FirstOrDefault(x => x is SecurityBindingElement) as SecurityBindingElement;
Assert.True(securityBindingElement == null, "securityBindingElement should be null when BasicHttpSecurityMode.TransportCredentialOnly is specified");
}
[Theory]
[InlineData(BasicHttpSecurityMode.Message)]
// BasicHttpSecurityMode.Message is not supported
public static void Create_HttpBinding_SecurityMode_Message_Throws_NotSupported(BasicHttpSecurityMode securityMode)
{
BasicHttpBinding binding = new BasicHttpBinding(securityMode);
Assert.Throws<NotSupportedException>(() => {
var bindingElements = binding.CreateBindingElements();
});
}
}
| mit | C# |
4e855d200fa9873ae8bb94e198e466e8c37e4d6e | Update banner | martincostello/api,martincostello/api,martincostello/api | src/API/Views/Home/Index.cshtml | src/API/Views/Home/Index.cshtml | @using System.Reflection
@{
ViewBag.Title = "Home Page";
string? mvcVersion = typeof(Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions)
.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
SiteOptions options = Options.Value;
}
<div class="jumbotron">
<h1>Martin Costello's API</h1>
<p class="lead">
This website is an excercise in the use of ASP.NET Core @Environment.Version.ToString(1) for a website and REST API.
</p>
</div>
<div>
<p>
This website is hosted in <a href="https://azure.microsoft.com" rel="noopener" target="_blank" title="Microsoft Azure">Microsoft Azure</a>
and the source code can be found on <a href="@options.Metadata?.Repository" rel="noopener" target="_blank" title="This application's GitHub repository">GitHub</a>.
</p>
<p>
It is currently running @(System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription).
</p>
</div>
<div class="row">
<div class="col-lg-6">
<h2 class="h3">Website</h2>
<p>My main website.</p>
<p><a id="link-website" href="@options.Metadata?.Author?.Website" class="btn btn-lg btn-primary" rel="noopener" role="button" target="_blank" title="Visit my website">Visit website »</a></p>
</div>
<div class="col-lg-6">
<h2 class="h3">Blog</h2>
<p>I occasionally blog about topics related to .NET development.</p>
<p><a id="link-blog" href="@options.ExternalLinks?.Blog?.AbsoluteUri" class="btn btn-lg btn-primary" rel="noopener" role="button" target="_blank" title="Visit my blog">Visit blog »</a></p>
</div>
</div>
| @using System.Reflection
@{
ViewBag.Title = "Home Page";
string? mvcVersion = typeof(Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions)
.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
SiteOptions options = Options.Value;
}
<div class="jumbotron">
<h1>Martin Costello's API</h1>
<p class="lead">
This website is an excercise in the use of ASP.NET @Environment.Version.ToString(2) for a website and REST API.
</p>
</div>
<div>
<p>
This website is hosted in <a href="https://azure.microsoft.com" rel="noopener" target="_blank" title="Microsoft Azure">Microsoft Azure</a>
and the source code can be found on <a href="@options.Metadata?.Repository" rel="noopener" target="_blank" title="This application's GitHub repository">GitHub</a>.
</p>
<p>
It is currently running @(System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription).
</p>
</div>
<div class="row">
<div class="col-lg-6">
<h2 class="h3">Website</h2>
<p>My main website.</p>
<p><a id="link-website" href="@options.Metadata?.Author?.Website" class="btn btn-lg btn-primary" rel="noopener" role="button" target="_blank" title="Visit my website">Visit website »</a></p>
</div>
<div class="col-lg-6">
<h2 class="h3">Blog</h2>
<p>I occasionally blog about topics related to .NET development.</p>
<p><a id="link-blog" href="@options.ExternalLinks?.Blog?.AbsoluteUri" class="btn btn-lg btn-primary" rel="noopener" role="button" target="_blank" title="Visit my blog">Visit blog »</a></p>
</div>
</div>
| mit | C# |
54f2909df10fd3951f61ad81fc258a8694b6aa9d | update vs | Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal | Master/Appleseed/Projects/PortableAreas/UserManager/Properties/AssemblyInfo.cs | Master/Appleseed/Projects/PortableAreas/UserManager/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("UserManager")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System : MVC User Manager")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("UserManager")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")]
[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("1bbaa317-aebe-425c-8db3-a1aee724365d")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.131.463")]
[assembly: AssemblyFileVersion("1.4.131.463")]
| 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("UserManager")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System : MVC User Manager")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("UserManager")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")]
[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("1bbaa317-aebe-425c-8db3-a1aee724365d")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.98.383")]
[assembly: AssemblyFileVersion("1.4.98.383")]
| apache-2.0 | C# |
142c8197aa573c713b75cd9c354461e509597b9d | Fix compilation error, see #33 | alphacloud/Autofac.Extras.Quartz | src/Samples/Shared/Bootstrap.cs | src/Samples/Shared/Bootstrap.cs | namespace SimpleService.Configuration
{
using System.Collections.Specialized;
using System.Reflection;
using AppServices;
using Autofac;
using Autofac.Extras.Quartz;
using Jobs;
using Logging;
using Logging.LogProviders;
using Serilog;
using Serilog.Sinks.SystemConsole.Themes;
internal class Bootstrap
{
public static void InitializeLogger()
{
var log = new LoggerConfiguration()
.WriteTo.Console(theme: AnsiConsoleTheme.Code)
.CreateLogger();
Log.Logger = log;
LogProvider.SetCurrentLogProvider(new SerilogLogProvider());
}
internal static ContainerBuilder ConfigureContainer(ContainerBuilder cb)
{
// configure and register Quartz
var schedulerConfig = new NameValueCollection {
{"quartz.threadPool.threadCount", "3"},
{"quartz.scheduler.threadName", "Scheduler"}
};
cb.RegisterModule(new QuartzAutofacFactoryModule {
ConfigurationProvider = c => schedulerConfig
});
#if NETCOREAPP1_1
cb.RegisterModule(new QuartzAutofacJobsModule(typeof(HeartbeatJob).GetTypeInfo().Assembly));
#else
cb.RegisterModule(new QuartzAutofacJobsModule(typeof(HeartbeatJob).Assembly));
#endif
RegisterComponents(cb);
return cb;
}
internal static void RegisterComponents(ContainerBuilder cb)
{
// register dependencies
cb.RegisterType<HeartbeatService>().As<IHeartbeatService>();
}
}
}
| using Autofac;
namespace SimpleService.Configuration
{
using System.Collections.Specialized;
using System.Reflection;
using AppServices;
using Autofac.Extras.Quartz;
using JetBrains.Annotations;
using Jobs;
using Logging.LogProviders;
using Serilog;
using Serilog.Sinks.SystemConsole.Themes;
internal class Bootstrap
{
public static void InitializeLogger()
{
var log = new LoggerConfiguration()
.WriteTo.Console(theme: AnsiConsoleTheme.Code)
.CreateLogger();
Log.Logger = log;
var serilogLogProvider = new SerilogLogProvider();
SimpleService.Logging.LogProvider.SetCurrentLogProvider(serilogLogProvider);
Quartz.Logging.LogProvider.SetCurrentLogProvider(serilogLogProvider);
}
internal static ContainerBuilder ConfigureContainer(ContainerBuilder cb)
{
// configure and register Quartz
var schedulerConfig = new NameValueCollection {
{"quartz.threadPool.threadCount", "3"},
{"quartz.scheduler.threadName", "Scheduler"}
};
cb.RegisterModule(new QuartzAutofacFactoryModule
{
ConfigurationProvider = c => schedulerConfig
});
#if NETCOREAPP1_1
cb.RegisterModule(new QuartzAutofacJobsModule(typeof(HeartbeatJob).GetTypeInfo().Assembly));
#else
cb.RegisterModule(new QuartzAutofacJobsModule(typeof(HeartbeatJob).Assembly));
#endif
RegisterComponents(cb);
return cb;
}
internal static void RegisterComponents(ContainerBuilder cb)
{
// register dependencies
cb.RegisterType<HeartbeatService>().As<IHeartbeatService>();
}
}
}
| mit | C# |
441605a46083ee4f318b7b23cd74bb0c8b4cf570 | Disable caching to force fetching of data when navigating backwards. Added api to clear db. | andreassjoberg/topicr-template,andreassjoberg/topicr-template | web/Controllers/Api/TopicController.cs | web/Controllers/Api/TopicController.cs | using System.Linq;
using Microsoft.AspNetCore.Mvc;
using topicr.Models;
namespace topicr.Controllers.Api
{
[Produces("application/json")]
[Route("api/topics")]
public class TopicController : Controller
{
private readonly TopicContext _db;
public TopicController(TopicContext db)
{
_db = db;
}
[HttpGet]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult GetTopics()
{
return Json(_db.Topics
.Select(p => new
{
p.Id,
p.Title,
p.Description
})
.ToList());
}
[HttpPost]
[Route("new")]
public IActionResult PostTopic(Topic topic)
{
_db.Topics.Add(topic);
_db.SaveChanges();
return Ok();
}
[HttpGet]
[Route("clear")]
public IActionResult ClearTopics()
{
foreach (var topic in _db.Topics)
{
_db.Topics.Remove(topic);
}
_db.SaveChanges();
return Ok();
}
}
}
| using System.Linq;
using Microsoft.AspNetCore.Mvc;
using topicr.Models;
namespace topicr.Controllers.Api
{
[Produces("application/json")]
[Route("api/topics")]
public class TopicController : Controller
{
private readonly TopicContext _db;
public TopicController(TopicContext db)
{
_db = db;
}
[HttpGet]
public IActionResult GetTopics()
{
return Json(_db.Topics
.Select(p => new
{
p.Id,
p.Title,
p.Description
})
.ToList());
}
[HttpPost]
[Route("new")]
public IActionResult PostTopic(Topic topic)
{
_db.Topics.Add(topic);
_db.SaveChanges();
return Ok();
}
}
}
| unlicense | C# |
c322d5b689b6d51d5802f2da7345943df03439d2 | update sample to debug multiple namespace/class and inner namespace/class | sdlab-naist/kenja-csharp-parser,sdlab-naist/kenja-csharp-parser | sample/sample.cs | sample/sample.cs | using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace Namespace1
{
namespace InnerNamespace1
{
class Sample
{
string hoge;
public Sample(string hoge)
{
this.hoge = hoge;
}
}
}
class Sample
{
public string hoge = "aa";
private string fuga = "aa";
public string piyo {
get {return fuga;}
}
class InnerClass
{
public InnerClass()
{
Console.WriteLine("Inner Class");
}
}
void SampleMain(string[] args)
{
var a = 10;
Console.WriteLine("Hello, World!");
}
void Hoge(double p1, int p2)
{
double i = p1 + (double)p2;
Console.WriteLine(i);
}
}
}
class Class1
{
int hoge;
private int Hoge()
{
return hoge;
}
}
namespace Namespace2
{
class Sample
{
public int i {get;set;}
public int j_;
public int j {
get {
return j_;
}
set {
j_ = value;
}
}
}
}
class Class2
{
float fuga;
private float Fuga()
{
return fuga;
}
}
| using System;
using System.Collections;
using System.Linq;
using System.Text;
class Program
{
string hoge = "aa";
string hoge2 = "aa";
static void Main(string[] args)
{
var a = 10;
Console.WriteLine(""Hello, World!"");
}
void Hoge(double hoge1, int hoge2)
{
int hoge3 = hoge1 + hoge2;
Console.WriteLine(hoge3);
}
public int i {get;set;}
public int j_;
public int j {
get {
return j_;
}
set {
j_ = value;
}
}
var x = 11;
// class Program2
// {
// public int num = 1;
// void Hoge(double hoge1, int hoge2, string hoge3)
// {
// Console.WriteLine(hoge4);
// }
// }
// }
}
// namespace HelloWorld
// {
// class Program2
// {
// public int num = 1;
// void Hoge(double hoge1, int hoge2, string hoge3)
// {
// Console.WriteLine(hoge4);
// }
// }
// }
| mit | C# |
94717fb50a4ef96e6ea494f6b777e130e3cb142e | use DisplayAttribute for PropertyName in ViewModelValidationRuleTranslator | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/DotVVM.Framework/ViewModel/Validation/ViewModelValidationRuleTranslator.cs | src/DotVVM.Framework/ViewModel/Validation/ViewModelValidationRuleTranslator.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace DotVVM.Framework.ViewModel.Validation
{
public class ViewModelValidationRuleTranslator : IValidationRuleTranslator
{
/// <summary>
/// Gets the validation rules.
/// </summary>
public virtual IEnumerable<ViewModelPropertyValidationRule> TranslateValidationRules(PropertyInfo property, IEnumerable<ValidationAttribute> validationAttributes)
{
foreach (var attribute in validationAttributes)
{
var validationRule = new ViewModelPropertyValidationRule(sourceValidationAttribute: attribute, propertyName: property.Name);
// TODO: extensibility
var displayAttribute = property.GetCustomAttribute<DisplayAttribute>();
if (displayAttribute != null)
validationRule.PropertyName = displayAttribute.GetName();
if (attribute is RequiredAttribute)
{
validationRule.ClientRuleName = "required";
}
else if (attribute is RegularExpressionAttribute)
{
var typedAttribute = (RegularExpressionAttribute)attribute;
validationRule.ClientRuleName = "regularExpression";
validationRule.Parameters = new[] { typedAttribute.Pattern };
}
else if (attribute is RangeAttribute)
{
var typed = (RangeAttribute)attribute;
validationRule.ClientRuleName = "range";
validationRule.Parameters = new[] { typed.Minimum, typed.Maximum };
}
else if (attribute is DotvvmEnforceClientFormatAttribute)
{
var typed = (DotvvmEnforceClientFormatAttribute)attribute;
validationRule.ClientRuleName = "enforceClientFormat";
validationRule.Parameters = new object[] { typed.AllowNull, typed.AllowEmptyString, typed.AllowEmptyStringOrWhitespaces };
}
else
{
validationRule.ClientRuleName = string.Empty;
}
yield return validationRule;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace DotVVM.Framework.ViewModel.Validation
{
public class ViewModelValidationRuleTranslator : IValidationRuleTranslator
{
/// <summary>
/// Gets the validation rules.
/// </summary>
public virtual IEnumerable<ViewModelPropertyValidationRule> TranslateValidationRules(PropertyInfo property, IEnumerable<ValidationAttribute> validationAttributes)
{
foreach (var attribute in validationAttributes)
{
var validationRule = new ViewModelPropertyValidationRule(sourceValidationAttribute: attribute, propertyName: property.Name);
// TODO: extensibility
if (attribute is RequiredAttribute)
{
validationRule.ClientRuleName = "required";
}
else if (attribute is RegularExpressionAttribute)
{
var typedAttribute = (RegularExpressionAttribute)attribute;
validationRule.ClientRuleName = "regularExpression";
validationRule.Parameters = new[] { typedAttribute.Pattern };
}
else if (attribute is RangeAttribute)
{
var typed = (RangeAttribute)attribute;
validationRule.ClientRuleName = "range";
validationRule.Parameters = new[] { typed.Minimum, typed.Maximum };
}
else if (attribute is DotvvmEnforceClientFormatAttribute)
{
var typed = (DotvvmEnforceClientFormatAttribute)attribute;
validationRule.ClientRuleName = "enforceClientFormat";
validationRule.Parameters = new object[] { typed.AllowNull, typed.AllowEmptyString, typed.AllowEmptyStringOrWhitespaces };
}
else
{
validationRule.ClientRuleName = string.Empty;
}
yield return validationRule;
}
}
}
}
| apache-2.0 | C# |
2a44fc8825833c899b9af1d090a75af1014ea53d | add interactive switch for RemovePackageCommand | johnbeisner/cli,livarcocc/cli-1,johnbeisner/cli,livarcocc/cli-1,johnbeisner/cli,livarcocc/cli-1 | src/dotnet/commands/dotnet-remove/dotnet-remove-package/RemovePackageParser.cs | src/dotnet/commands/dotnet-remove/dotnet-remove-package/RemovePackageParser.cs | using Microsoft.DotNet.Cli.CommandLine;
using LocalizableStrings = Microsoft.DotNet.Tools.Remove.PackageReference.LocalizableStrings;
namespace Microsoft.DotNet.Cli
{
internal static class RemovePackageParser
{
public static Command RemovePackage()
{
return Create.Command(
"package",
LocalizableStrings.AppFullName,
Accept.ExactlyOneArgument()
.With(name: Tools.Add.PackageReference.LocalizableStrings.CmdPackage,
description: LocalizableStrings.AppHelpText),
CommonOptions.HelpOption()).
Create.Option("--interactive",
LocalizableStrings.CmdInteractiveRestoreDescription,
Accept.NoArguments()
.ForwardAs("--interactive"));
}
}
}
| using Microsoft.DotNet.Cli.CommandLine;
using LocalizableStrings = Microsoft.DotNet.Tools.Remove.PackageReference.LocalizableStrings;
namespace Microsoft.DotNet.Cli
{
internal static class RemovePackageParser
{
public static Command RemovePackage()
{
return Create.Command(
"package",
LocalizableStrings.AppFullName,
Accept.ExactlyOneArgument()
.With(name: Tools.Add.PackageReference.LocalizableStrings.CmdPackage,
description: LocalizableStrings.AppHelpText),
CommonOptions.HelpOption());
}
}
}
| mit | C# |
bbb8334ad02d477ef4e6662fe066a3679ee4cdb2 | Update example implementation for Bob exercise | robkeim/xcsharp,GKotfis/csharp,exercism/xcsharp,ErikSchierboom/xcsharp,exercism/xcsharp,robkeim/xcsharp,ErikSchierboom/xcsharp,GKotfis/csharp | exercises/bob/Example.cs | exercises/bob/Example.cs | public static class Bob
{
public static string Response(string statement)
{
if (IsSilence(statement))
return "Fine. Be that way!";
if (IsYelling(statement) && IsQuestion(statement))
return "Calm down, I know what I'm doing!";
if (IsYelling(statement))
return "Whoa, chill out!";
if (IsQuestion(statement))
return "Sure.";
return "Whatever.";
}
private static bool IsSilence (string statement)
{
return statement.Trim() == "";
}
private static bool IsYelling (string statement)
{
return statement.ToUpper() == statement && System.Text.RegularExpressions.Regex.IsMatch(statement, "[a-zA-Z]+");
}
private static bool IsQuestion (string statement)
{
return statement.Trim().EndsWith("?");
}
} | public static class Bob
{
public static string Response(string statement)
{
if (IsSilence(statement))
return "Fine. Be that way!";
if (IsYelling(statement))
return "Whoa, chill out!";
if (IsQuestion(statement))
return "Sure.";
return "Whatever.";
}
private static bool IsSilence (string statement)
{
return statement.Trim() == "";
}
private static bool IsYelling (string statement)
{
return statement.ToUpper() == statement && System.Text.RegularExpressions.Regex.IsMatch(statement, "[a-zA-Z]+");
}
private static bool IsQuestion (string statement)
{
return statement.Trim().EndsWith("?");
}
} | mit | C# |
f0d4762ac498eb4bf3346ff94064f1b72b22edbe | Make the guard class internal | haefele/PalmDB | src/PalmDB/Guard.cs | src/PalmDB/Guard.cs | using System;
namespace PalmDB
{
/// <summary>
/// Typical guard class that contains methods to validate method arguments.
/// </summary>
internal static class Guard
{
/// <summary>
/// Throws a <see cref="ArgumentNullException"/> if the specified <paramref name="argument"/> is <c>null</c>.
/// </summary>
/// <param name="argument">The argument to check for null.</param>
/// <param name="name">The name of the argument.</param>
public static void NotNull(object argument, string name)
{
if (argument == null)
throw new ArgumentNullException(name);
}
/// <summary>
/// Throws a <see cref="ArgumentException"/> if the specified <paramref name="argument"/> is less than 0.
/// </summary>
/// <param name="argument">The argument.</param>
/// <param name="name">The name.</param>
public static void NotNegative(int argument, string name)
{
if (argument < 0)
throw new ArgumentException($"{name} cannot be less than 0.", name);
}
}
} | using System;
namespace PalmDB
{
/// <summary>
/// Typical guard class that contains methods to validate method arguments.
/// </summary>
public static class Guard
{
/// <summary>
/// Throws a <see cref="ArgumentNullException"/> if the specified <paramref name="argument"/> is <c>null</c>.
/// </summary>
/// <param name="argument">The argument to check for null.</param>
/// <param name="name">The name of the argument.</param>
public static void NotNull(object argument, string name)
{
if (argument == null)
throw new ArgumentNullException(name);
}
/// <summary>
/// Throws a <see cref="ArgumentException"/> if the specified <paramref name="argument"/> is less than 0.
/// </summary>
/// <param name="argument">The argument.</param>
/// <param name="name">The name.</param>
public static void NotNegative(int argument, string name)
{
if (argument < 0)
throw new ArgumentException($"{name} cannot be less than 0.", name);
}
}
} | mit | C# |
ca7f90680a299a76aea99237682c568f2a4f8abf | Bump version to 0.6.9 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.6.9")]
[assembly: AssemblyInformationalVersionAttribute("0.6.9")]
[assembly: AssemblyFileVersionAttribute("0.6.9")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.6.9";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.6.8")]
[assembly: AssemblyInformationalVersionAttribute("0.6.8")]
[assembly: AssemblyFileVersionAttribute("0.6.8")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.6.8";
}
}
| apache-2.0 | C# |
7e4876402c7754f06f100ce23f6a53bbc8226018 | increment version | fallenidol/GleanETL | Gleanio.Core/Properties/AssemblyInfo.cs | Gleanio.Core/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("Gleanio")]
[assembly:
AssemblyDescription(
"Aims to be a simple framework with which to extract data from text files, particularly if they are in non-standard formats."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Paul Mcilreavy")]
[assembly: AssemblyProduct("Gleanio")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("973d2492-d176-4b26-b0a1-3edf36cbd486")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.2.0")]
[assembly: AssemblyFileVersion("0.1.2.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Gleanio")]
[assembly:
AssemblyDescription(
"Aims to be a simple framework with which to extract data from text files, particularly if they are in non-standard formats."
)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Paul Mcilreavy")]
[assembly: AssemblyProduct("Gleanio")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("973d2492-d176-4b26-b0a1-3edf36cbd486")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.1.0")]
[assembly: AssemblyFileVersion("0.1.1.0")] | mit | C# |
0877bbed87ae028a7a20197f4562ba307e1c5433 | Remove some dependencies | pjf/StuffManager | StuffManager/Commands/DownloadCommand.cs | StuffManager/Commands/DownloadCommand.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace StuffManager.Commands
{
class DownloadCommand
{
public static int HandleCommandLine(string[] args, string[] options)
{
var terms = string.Join(" ", args);
var search = KerbalStuff.Search(terms);
var results = search.Where(r => r.Name.ToUpper() == terms.ToUpper()
|| r.Author.ToUpper() + "/" + r.Name.ToUpper() == terms.ToUpper());
if (!results.Any())
results = search;
if (results.Count() > 1)
{
Console.WriteLine("Error: \"{0}\" is ambiguous between:");
foreach (var m in results)
Console.WriteLine("{0}/{1} [{2}]", m.Author, m.Name, m.Downloads);
return 1;
}
var mod = results.Single();
System.Diagnostics.Process.Start("http://beta.kerbalstuff.com" + mod.Versions.First().DownloadPaths);
return 0;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StuffManager.Commands
{
class DownloadCommand
{
public static int HandleCommandLine(string[] args, string[] options)
{
var terms = string.Join(" ", args);
var search = KerbalStuff.Search(terms);
var results = search.Where(r => r.Name.ToUpper() == terms.ToUpper()
|| r.Author.ToUpper() + "/" + r.Name.ToUpper() == terms.ToUpper());
if (!results.Any())
results = search;
if (results.Count() > 1)
{
Console.WriteLine("Error: \"{0}\" is ambiguous between:");
foreach (var m in results)
Console.WriteLine("{0}/{1} [{2}]", m.Author, m.Name, m.Downloads);
return 1;
}
var mod = results.Single();
System.Diagnostics.Process.Start("http://beta.kerbalstuff.com" + mod.Versions.First().DownloadPaths);
return 0;
}
}
}
| mit | C# |
fbec611202229ac8d67ef8ef1b5988e604ac5c05 | Implement snowball drops from snow blocks | creatorfromhell/TrueCraft,manio143/TrueCraft,creatorfromhell/TrueCraft,blha303/TrueCraft,manio143/TrueCraft,flibitijibibo/TrueCraft,robinkanters/TrueCraft,Mitch528/TrueCraft,SirCmpwn/TrueCraft,illblew/TrueCraft,illblew/TrueCraft,flibitijibibo/TrueCraft,blha303/TrueCraft,christopherbauer/TrueCraft,christopherbauer/TrueCraft,blha303/TrueCraft,SirCmpwn/TrueCraft,thdtjsdn/TrueCraft,thdtjsdn/TrueCraft,christopherbauer/TrueCraft,robinkanters/TrueCraft,Mitch528/TrueCraft,thdtjsdn/TrueCraft,SirCmpwn/TrueCraft,flibitijibibo/TrueCraft,robinkanters/TrueCraft,illblew/TrueCraft,manio143/TrueCraft,Mitch528/TrueCraft | TrueCraft.Core/Logic/Blocks/SnowBlock.cs | TrueCraft.Core/Logic/Blocks/SnowBlock.cs | using System;
using TrueCraft.API.Logic;
using TrueCraft.API;
using TrueCraft.Core.Logic.Items;
namespace TrueCraft.Core.Logic.Blocks
{
public class SnowBlock : BlockProvider, ICraftingRecipe
{
public static readonly byte BlockID = 0x50;
public override byte ID { get { return 0x50; } }
public override double BlastResistance { get { return 1; } }
public override double Hardness { get { return 0.2; } }
public override byte Luminance { get { return 0; } }
public override string DisplayName { get { return "Snow Block"; } }
public override Tuple<int, int> GetTextureMap(byte metadata)
{
return new Tuple<int, int>(2, 4);
}
public ItemStack[,] Pattern
{
get
{
return new[,]
{
{ new ItemStack(SnowballItem.ItemID), new ItemStack(SnowballItem.ItemID) },
{ new ItemStack(SnowballItem.ItemID), new ItemStack(SnowballItem.ItemID) }
};
}
}
public ItemStack Output
{
get
{
return new ItemStack(BlockID);
}
}
public bool SignificantMetadata
{
get
{
return false;
}
}
}
public class SnowfallBlock : BlockProvider
{
public static readonly byte BlockID = 0x4E;
public override byte ID { get { return 0x4E; } }
public override double BlastResistance { get { return 0.5; } }
public override double Hardness { get { return 0; } }
public override byte Luminance { get { return 0; } }
public override bool Opaque { get { return false; } }
public override string DisplayName { get { return "Snow"; } }
public override Tuple<int, int> GetTextureMap(byte metadata)
{
return new Tuple<int, int>(3, 4);
}
protected override ItemStack[] GetDrop(BlockDescriptor descriptor)
{
return new[] { new ItemStack(SnowballItem.ItemID) };
}
}
} | using System;
using TrueCraft.API.Logic;
using TrueCraft.API;
using TrueCraft.Core.Logic.Items;
namespace TrueCraft.Core.Logic.Blocks
{
public class SnowBlock : BlockProvider, ICraftingRecipe
{
public static readonly byte BlockID = 0x50;
public override byte ID { get { return 0x50; } }
public override double BlastResistance { get { return 1; } }
public override double Hardness { get { return 0.2; } }
public override byte Luminance { get { return 0; } }
public override string DisplayName { get { return "Snow Block"; } }
public override Tuple<int, int> GetTextureMap(byte metadata)
{
return new Tuple<int, int>(2, 4);
}
public ItemStack[,] Pattern
{
get
{
return new[,]
{
{ new ItemStack(SnowballItem.ItemID), new ItemStack(SnowballItem.ItemID) },
{ new ItemStack(SnowballItem.ItemID), new ItemStack(SnowballItem.ItemID) }
};
}
}
public ItemStack Output
{
get
{
return new ItemStack(BlockID);
}
}
public bool SignificantMetadata
{
get
{
return false;
}
}
}
public class SnowfallBlock : BlockProvider
{
public static readonly byte BlockID = 0x4E;
public override byte ID { get { return 0x4E; } }
public override double BlastResistance { get { return 0.5; } }
public override double Hardness { get { return 0; } }
public override byte Luminance { get { return 0; } }
public override bool Opaque { get { return false; } }
public override string DisplayName { get { return "Snow"; } }
public override Tuple<int, int> GetTextureMap(byte metadata)
{
return new Tuple<int, int>(3, 4);
}
}
} | mit | C# |
5871897eadf47388bc50e100dbf6dbbcc3a9d7a9 | Change code to avoid build errors on C# < 6 | frackleton/ApplicationInsights-SDK-Labs,Microsoft/ApplicationInsights-SDK-Labs | WCF/Shared/OperationContextExtensions.cs | WCF/Shared/OperationContextExtensions.cs | using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Wcf.Implementation;
using System;
using System.ServiceModel;
namespace Microsoft.ApplicationInsights.Wcf
{
/// <summary>
/// Provides extensions methods for accessing Application Insights Objects
/// </summary>
public static class OperationContextExtensions
{
/// <summary>
/// Obtains a reference to the request telemetry object generated by
/// the Application Insights WCF SDK.
/// </summary>
/// <param name="context">The WCF OperationContext instance
/// associated with the current request</param>
/// <returns>The request object or null</returns>
public static RequestTelemetry GetRequestTelemetry(this OperationContext context)
{
if ( context == null )
return null;
var icontext = WcfOperationContext.FindContext(context);
return icontext != null ? icontext.Request : null;
}
}
}
| using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Wcf.Implementation;
using System;
using System.ServiceModel;
namespace Microsoft.ApplicationInsights.Wcf
{
/// <summary>
/// Provides extensions methods for accessing Application Insights Objects
/// </summary>
public static class OperationContextExtensions
{
/// <summary>
/// Obtains a reference to the request telemetry object generated by
/// the Application Insights WCF SDK.
/// </summary>
/// <param name="context">The WCF OperationContext instance
/// associated with the current request</param>
/// <returns>The request object or null</returns>
public static RequestTelemetry GetRequestTelemetry(this OperationContext context)
{
if ( context == null )
return null;
var icontext = WcfOperationContext.FindContext(context);
return icontext?.Request;
}
}
}
| mit | C# |
9fa6bc75aa8377fc68d05121dfb9775484523660 | Fix focus border issue with menu buttons | mminns/xwt,sevoku/xwt,iainx/xwt,mminns/xwt,hamekoz/xwt,TheBrainTech/xwt,steffenWi/xwt,directhex/xwt,cra0zy/xwt,residuum/xwt,antmicro/xwt,akrisiun/xwt,lytico/xwt,hwthomas/xwt,mono/xwt | Xwt.WPF/Xwt.WPFBackend/DropDownButton.cs | Xwt.WPF/Xwt.WPFBackend/DropDownButton.cs | //
// DropDownButton.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 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 System.Linq;
using System.Windows;
using System.Windows.Controls.Primitives;
using SWC = System.Windows.Controls;
namespace Xwt.WPFBackend
{
public class DropDownButton
: SWC.Primitives.ToggleButton, IWpfWidget
{
public DropDownButton()
{
Checked += OnChecked;
}
public event EventHandler<MenuOpeningEventArgs> MenuOpening;
public WidgetBackend Backend
{
get;
set;
}
protected override System.Windows.Size MeasureOverride (System.Windows.Size constraint)
{
var s = base.MeasureOverride (constraint);
return Backend.MeasureOverride (constraint, s);
}
private void OnChecked (object sender, RoutedEventArgs routedEventArgs)
{
if (!IsChecked.HasValue || !IsChecked.Value)
return;
var args = new MenuOpeningEventArgs ();
var opening = this.MenuOpening;
if (opening != null)
opening (this, args);
var menu = args.ContextMenu;
if (menu == null) {
IsChecked = false;
return;
}
string text = Content as string;
if (!String.IsNullOrWhiteSpace (text)) {
SWC.MenuItem selected = menu.Items.OfType<SWC.MenuItem>().FirstOrDefault (i => i.Header as string == text);
if (selected != null)
selected.IsChecked = true;
}
menu.Closed += OnMenuClosed;
menu.PlacementTarget = this;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
private void OnMenuClosed (object sender, RoutedEventArgs e)
{
var menu = sender as SWC.ContextMenu;
if (menu != null)
menu.Closed -= OnMenuClosed;
IsChecked = false;
}
public class MenuOpeningEventArgs
: EventArgs
{
public SWC.ContextMenu ContextMenu
{
get;
set;
}
}
}
} | //
// DropDownButton.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 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 System.Linq;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using SWC = System.Windows.Controls;
namespace Xwt.WPFBackend
{
public class DropDownButton
: SWC.Primitives.ToggleButton, IWpfWidget
{
public event EventHandler<MenuOpeningEventArgs> MenuOpening;
public WidgetBackend Backend
{
get;
set;
}
protected override void OnToggle()
{
base.OnToggle();
if (!IsChecked.HasValue || !IsChecked.Value)
return;
var args = new MenuOpeningEventArgs ();
var opening = this.MenuOpening;
if (opening != null)
opening (this, args);
var menu = args.ContextMenu;
if (menu == null) {
IsChecked = false;
return;
}
FocusManager.SetIsFocusScope (menu, false);
string text = Content as string;
if (!String.IsNullOrWhiteSpace (text)) {
SWC.MenuItem selected = menu.Items.OfType<SWC.MenuItem>().FirstOrDefault (i => i.Header as string == text);
if (selected != null)
selected.IsChecked = true;
}
menu.Closed += OnMenuClosed;
menu.PlacementTarget = this;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
protected override System.Windows.Size MeasureOverride (System.Windows.Size constraint)
{
var s = base.MeasureOverride (constraint);
return Backend.MeasureOverride (constraint, s);
}
private void OnMenuClosed (object sender, RoutedEventArgs e)
{
var menu = sender as SWC.ContextMenu;
if (menu != null)
menu.Closed -= OnMenuClosed;
IsChecked = false;
}
public class MenuOpeningEventArgs
: EventArgs
{
public SWC.ContextMenu ContextMenu
{
get;
set;
}
}
}
} | mit | C# |
0743ce2639981b5d372e33fa3252ea165b131bb0 | Fix (again) syntax issue with using static | Seddryck/NBi,Seddryck/NBi | NBi.Xml/Items/ResultSet/ResultSetXml.cs | NBi.Xml/Items/ResultSet/ResultSetXml.cs | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core;
using NBi.Core.ResultSet;
namespace NBi.Xml.Items.ResultSet
{
public class ResultSetXml : BaseItem
{
[XmlElement("row")]
public List<RowXml> _rows { get; set; }
public IList<IRow> Rows
{
get { return _rows.Cast<IRow>().ToList(); }
}
public IList<string> Columns
{
get
{
if (_rows.Count == 0)
return new List<string>();
var names = new List<string>();
var row = _rows[0];
foreach (var cell in row.Cells)
{
if (!string.IsNullOrEmpty(cell.ColumnName))
names.Add(cell.ColumnName);
else
names.Add(string.Empty);
}
return names;
}
}
[XmlIgnore]
public ResultSetBuilder.Content Content
{
get { return new ResultSetBuilder.Content(Rows, Columns); }
}
[XmlAttribute("file")]
public string File { get; set; }
public string GetFile()
{
var file = string.Empty;
if (Path.IsPathRooted(File))
file = File;
else
file = Settings.BasePath + File;
return file;
}
public ResultSetXml()
{
_rows = new List<RowXml>();
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core;
using NBi.Core.ResultSet;
using static NBi.Core.ResultSet.ResultSetBuilder;
namespace NBi.Xml.Items.ResultSet
{
public class ResultSetXml : BaseItem
{
[XmlElement("row")]
public List<RowXml> _rows { get; set; }
public IList<IRow> Rows
{
get { return _rows.Cast<IRow>().ToList(); }
}
public IList<string> Columns
{
get
{
if (_rows.Count == 0)
return new List<string>();
var names = new List<string>();
var row = _rows[0];
foreach (var cell in row.Cells)
{
if (!string.IsNullOrEmpty(cell.ColumnName))
names.Add(cell.ColumnName);
else
names.Add(string.Empty);
}
return names;
}
}
[XmlIgnore]
public Content Content
{
get { return new Content(Rows, Columns); }
}
[XmlAttribute("file")]
public string File { get; set; }
public string GetFile()
{
var file = string.Empty;
if (Path.IsPathRooted(File))
file = File;
else
file = Settings.BasePath + File;
return file;
}
public ResultSetXml()
{
_rows = new List<RowXml>();
}
}
}
| apache-2.0 | C# |
30be76f3d997588596958ef8c057bf1e3fca056a | Update DataFactories AssemblyInfo | AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell | src/ResourceManager/DataFactories/Commands.DataFactories/Properties/AssemblyInfo.cs | src/ResourceManager/DataFactories/Commands.DataFactories/Properties/AssemblyInfo.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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Powershell - DataFactory Manager")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: Guid("5d024af0-81c9-44f0-b3b0-7080f103fb4d")]
[assembly: AssemblyVersion("4.0.2")]
[assembly: AssemblyFileVersion("4.0.2")]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.Azure.Commands.DataFactories.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.Azure.Commands.DataFactories.Test")]
#endif
| // ----------------------------------------------------------------------------------
//
// 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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Powershell - DataFactory Manager")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: Guid("5d024af0-81c9-44f0-b3b0-7080f103fb4d")]
[assembly: AssemblyVersion("4.0.1")]
[assembly: AssemblyFileVersion("4.0.1")]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.Azure.Commands.DataFactories.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.Azure.Commands.DataFactories.Test")]
#endif
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.